diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/isympy.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/isympy.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a336af1b4073abea092211ecd55affd56b9c524 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/isympy.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/jsonpatch.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/jsonpatch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae43425ab2cb9a9f9b493014b1e5b48484249c5a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/jsonpatch.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/jsonpointer.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/jsonpointer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8cad5d36457533f9e6e72b00f3f09fa1904422a7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/jsonpointer.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/mypy_extensions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/mypy_extensions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ed6ec19919f9b06ee3af1155b343649fc21a9b7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/mypy_extensions.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/six.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/six.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d325b70ba5ab83a3aa550dbb062273e4327d821 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/six.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/threadpoolctl.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/threadpoolctl.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e0b777dddb21d9d5cd3a50be72666e1d568df88 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/threadpoolctl.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/typing_inspect.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/typing_inspect.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7c75f3f64208e6940f509a80f853b7b64e56d2d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/typing_inspect.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/_distutils_hack/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/_distutils_hack/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..94f71b99ecefd27e6cf3fd06fc3c0eef5fd73910 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/_distutils_hack/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/_distutils_hack/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed5816e55e2654ba65e47d201f6b0c0f47db6342 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/_distutils_hack/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/_distutils_hack/__pycache__/override.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/_distutils_hack/__pycache__/override.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..309a9993808f5bc80521029097d0b64cf4dfcd6f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/_distutils_hack/__pycache__/override.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/_distutils_hack/override.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/_distutils_hack/override.py new file mode 100644 index 0000000000000000000000000000000000000000..2cc433a4a55e3b41fa31089918fb62096092f89f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/_distutils_hack/override.py @@ -0,0 +1 @@ +__import__('_distutils_hack').do_override() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/_yaml/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/_yaml/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7baa8c4b68127d5cdf0be9a799429e61347c2694 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/_yaml/__init__.py @@ -0,0 +1,33 @@ +# This is a stub package designed to roughly emulate the _yaml +# extension module, which previously existed as a standalone module +# and has been moved into the `yaml` package namespace. +# It does not perfectly mimic its old counterpart, but should get +# close enough for anyone who's relying on it even when they shouldn't. +import yaml + +# in some circumstances, the yaml module we imoprted may be from a different version, so we need +# to tread carefully when poking at it here (it may not have the attributes we expect) +if not getattr(yaml, '__with_libyaml__', False): + from sys import version_info + + exc = ModuleNotFoundError if version_info >= (3, 6) else ImportError + raise exc("No module named '_yaml'") +else: + from yaml._yaml import * + import warnings + warnings.warn( + 'The _yaml extension module is now located at yaml._yaml' + ' and its location is subject to change. To use the' + ' LibYAML-based parser and emitter, import from `yaml`:' + ' `from yaml import CLoader as Loader, CDumper as Dumper`.', + DeprecationWarning + ) + del warnings + # Don't `del yaml` here because yaml is actually an existing + # namespace member of _yaml. + +__name__ = '_yaml' +# If the module is top-level (i.e. not a part of any specific package) +# then the attribute should be set to ''. +# https://docs.python.org/3.8/library/types.html +__package__ = '' diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/_yaml/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/_yaml/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92215c13c356b15f4b0a3a1423ead9a643b7e4dd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/_yaml/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers-5.8.1.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers-5.8.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..68b7d66c97d66c58de883ed0c451af2b3183e6f3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers-5.8.1.dist-info/licenses/LICENSE @@ -0,0 +1,203 @@ +Copyright 2018- The Hugging Face team. All rights reserved. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..237f765be195f552e8f4d3fb43fdb8b3343c0ce3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/_typing.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/_typing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59a8717dca4b8608f6f268c179f57c2bb0303be2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/_typing.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/activations.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/activations.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..108c412aaaf0855a292f8bb3f15a152d36bd1f90 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/activations.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/audio_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/audio_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a2e5294bd53cc76c4f656a8481ca458bf6e3400 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/audio_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/backbone_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/backbone_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1cbea02baa1c7437d8bf4a3eae9906f0a1bad0c0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/backbone_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/cache_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/cache_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..520dcf37addf3aaa7117f8a6ab662e63297b278a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/cache_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/configuration_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/configuration_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c85c609457e80e1ab6b4748dab520d7a52fcf58d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/configuration_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/conversion_mapping.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/conversion_mapping.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dab75668052130e691a7db9af3c5c8b349ab2063 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/conversion_mapping.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/convert_slow_tokenizers_checkpoints_to_fast.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/convert_slow_tokenizers_checkpoints_to_fast.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d18f779b790efe30c86d393fd645f5e5048d9f9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/convert_slow_tokenizers_checkpoints_to_fast.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/core_model_loading.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/core_model_loading.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a31487ec66a781226a53ffb74d33b9f688f4fb15 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/core_model_loading.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/debug_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/debug_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..338aa0b06d0f607687cb7376d54b40c67b7c5a24 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/debug_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/dependency_versions_check.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/dependency_versions_check.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78adc3528c39a606e7e4757781194f6cc8370310 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/dependency_versions_check.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/dependency_versions_table.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/dependency_versions_table.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0da8a1e685e91e3cd96cd5fcaa75780c0e67f69 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/dependency_versions_table.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/dynamic_module_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/dynamic_module_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a62e94fefb40fb2e4a4d09548b0d3c5040544f05 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/dynamic_module_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/feature_extraction_sequence_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/feature_extraction_sequence_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a07aa7bae3362e1635b9321076418c759fb1a4b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/feature_extraction_sequence_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/feature_extraction_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/feature_extraction_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5fe8c115045e9d8ac4db092a2f23f1d867560dfd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/feature_extraction_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/file_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/file_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f75fe1749774605f640c364e922ec9e34ca5bf4d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/file_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/fusion_mapping.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/fusion_mapping.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f582f6973acb08b83aeb2e7d424e91229c1eec8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/fusion_mapping.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/hf_argparser.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/hf_argparser.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b6a542079a9b81edb543a03602e3840f99ba1e3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/hf_argparser.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/hyperparameter_search.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/hyperparameter_search.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9d82accddbbad82cbff833b2666c4605d0519d1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/hyperparameter_search.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_processing_backends.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_processing_backends.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b525810a50bbd367c29446da98ad5d57e3585c4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_processing_backends.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_processing_base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_processing_base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..316f74c83cd7795406bb8af0965e0b98fd9aa189 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_processing_base.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_processing_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_processing_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..adfb45be789dbcdcb337b1b13e6c8b2aeecce04a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_processing_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_transforms.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_transforms.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e500210d2bc5ae85af7073fd63da21331fa7fd13 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_transforms.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43dde778d53708f1ef8095b29afa95f8ed253a2e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/initialization.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/initialization.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0f55a85f59577c9fb3ce9d6f3dbe0302b8d8525 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/initialization.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/masking_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/masking_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71b014e7a39d5ea2f1b6d868c5458f5db67af829 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/masking_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/model_debugging_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/model_debugging_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcf793687309fedaa145832945b008bb8987c30d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/model_debugging_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modelcard.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modelcard.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f427731c5f36ee9711538fa8bc3576ec7ff6a989 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modelcard.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_attn_mask_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_attn_mask_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8ae4ce54a4c41e9b62584634fb4b5adde590039 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_attn_mask_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_flash_attention_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_flash_attention_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b8c7c7d60043c9b12b206069fa1dcba2b33079b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_flash_attention_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_gguf_pytorch_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_gguf_pytorch_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02a8f2d22dd8cc862ed6100b391e1f9ec5713eed Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_gguf_pytorch_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_layers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_layers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df528a2e2d9e251f38b483e9f49533a43cef51b3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_layers.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_rope_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_rope_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e71a55278efa511df10564b95a0d6d208f432f1a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_rope_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/monkey_patching.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/monkey_patching.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8caab9a6cec0d3ca1ef492bc61127faba14043f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/monkey_patching.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/optimization.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/optimization.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d9a3b694d0d1b648f21b74453880b9c92322942 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/optimization.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/pytorch_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/pytorch_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88527e62423f9d64d9800be3e078d98669f9393e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/pytorch_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/safetensors_conversion.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/safetensors_conversion.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..688b43d6fee832459a9e81911b5f41e1eb3bb137 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/safetensors_conversion.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/time_series_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/time_series_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16736b3ce9a01c3bd76ee41d35e0b405bc464619 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/time_series_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/tokenization_mistral_common.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/tokenization_mistral_common.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6041311d7f1a34643a08651678c08887226e29f3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/tokenization_mistral_common.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/tokenization_python.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/tokenization_python.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..965ad5be45659de8a89d79ce598b94a60e9201fb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/tokenization_python.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/tokenization_utils_sentencepiece.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/tokenization_utils_sentencepiece.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9e23be10e9b58643cad48bace0ab7e5def0b77a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/tokenization_utils_sentencepiece.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/tokenization_utils_tokenizers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/tokenization_utils_tokenizers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb9c79f0e3d073291c4d4a7d947242b7c02ed757 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/tokenization_utils_tokenizers.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_callback.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_callback.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77d818f41469af1347432cf936c2ef75991da913 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_callback.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_jit_checkpoint.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_jit_checkpoint.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e362573a7babfb1588426f309055dcfedd38ba2d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_jit_checkpoint.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_optimizer.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_optimizer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92021c97488e33f9a5d5ff2cfa41b5090d755120 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_optimizer.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_pt_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_pt_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bacc0cbd80ab55cb1efc0a7e6594384d0d47c732 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_pt_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_seq2seq.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_seq2seq.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cdfac859ae34b85da4b188bcecd80eef241b112 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_seq2seq.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba4474fff631d01fa54abb8da821d28fdb2d69c1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/training_args_seq2seq.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/training_args_seq2seq.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59cb1a2980cd3218bcea5b0397b61c44d53c6c1b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/training_args_seq2seq.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/video_processing_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/video_processing_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ad34794da2a3433a3aaa887623ec45c095ccecc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/video_processing_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/video_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/video_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..792c30c3694366b2785d4abc6ce824655dac73bc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/video_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/cli/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8568c82be1c638c0ccd34d460fd8b0f73dcbec4e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/cli/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2025 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/cli/add_new_model_like.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/cli/add_new_model_like.py new file mode 100644 index 0000000000000000000000000000000000000000..3293f6a4ba8cea00e98fb3bedae4bc996830a615 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/cli/add_new_model_like.py @@ -0,0 +1,790 @@ +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# 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. +import difflib +import os +import re +import subprocess +import textwrap +from collections.abc import Callable +from datetime import date +from pathlib import Path +from typing import Annotated, Any, cast + +import typer + +from ..utils import is_libcst_available + + +# We protect this import to avoid requiring it for all `transformers` CLI commands - however it is actually +# strictly required for this one (we need it both for modular and for the following Visitor) +if is_libcst_available(): + import libcst as cst + from libcst import CSTVisitor + from libcst import matchers as m + + class ClassFinder(CSTVisitor): + """ + A visitor to find all classes in a python module. + """ + + def __init__(self): + self.classes: list = [] + self.public_classes: list = [] + self.is_in_class = False + + def visit_ClassDef(self, node: cst.ClassDef) -> None: + """Record class names. We assume classes always only appear at top-level (i.e. no class definition in function or similar)""" + self.classes.append(node.name.value) + self.is_in_class = True + + def leave_ClassDef(self, node: cst.ClassDef): + self.is_in_class = False + + def visit_SimpleStatementLine(self, node: cst.SimpleStatementLine): + """Record all public classes inside the `__all__` assignment.""" + simple_top_level_assign_structure = m.SimpleStatementLine( + body=[m.Assign(targets=[m.AssignTarget(target=m.Name())])] + ) + if not self.is_in_class and m.matches(node, simple_top_level_assign_structure): + stmt = cast(cst.Assign, node.body[0]) + assigned_variable = cast(cst.Name, stmt.targets[0].target).value + if assigned_variable == "__all__": + elements = cast(cst.Tuple, stmt.value).elements + self.public_classes = [cast(cst.SimpleString, element.value).value for element in elements] + + +CURRENT_YEAR = date.today().year +REPO_PATH = Path(__file__).parents[3] + +COPYRIGHT = f""" +# coding=utf-8 +# Copyright {CURRENT_YEAR} the HuggingFace Team. All rights reserved. +# +# 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. +""".lstrip() + +### Entrypoint + + +def add_new_model_like( + repo_path: Annotated[ + str | None, typer.Argument(help="When not using an editable install, the path to the Transformers repo.") + ] = None, +): + """ + Add a new model to the library, based on an existing one. + """ + ( + old_model_infos, + new_lowercase_name, + new_model_paper_name, + filenames_to_add, + ) = get_user_input() + + _add_new_model_like_internal( + repo_path=Path(repo_path) if repo_path is not None else REPO_PATH, + old_model_infos=old_model_infos, + new_lowercase_name=new_lowercase_name, + new_model_paper_name=new_model_paper_name, + filenames_to_add=filenames_to_add, + ) + + +### Core logic + + +class ModelInfos: + """ + Retrieve the basic information about an existing model classes. + """ + + def __init__(self, lowercase_name: str): + from ..models.auto.configuration_auto import CONFIG_MAPPING_NAMES + from ..models.auto.feature_extraction_auto import FEATURE_EXTRACTOR_MAPPING_NAMES + from ..models.auto.image_processing_auto import IMAGE_PROCESSOR_MAPPING_NAMES + from ..models.auto.processing_auto import PROCESSOR_MAPPING_NAMES + from ..models.auto.tokenization_auto import TOKENIZER_MAPPING_NAMES + from ..models.auto.video_processing_auto import VIDEO_PROCESSOR_MAPPING_NAMES + + # Just to make sure it's indeed lowercase + self.lowercase_name = lowercase_name.lower().replace(" ", "_").replace("-", "_") + if self.lowercase_name not in CONFIG_MAPPING_NAMES: + self.lowercase_name.replace("_", "-") + if self.lowercase_name not in CONFIG_MAPPING_NAMES: + raise ValueError(f"{lowercase_name} is not a valid model name") + + self.config_class = CONFIG_MAPPING_NAMES[self.lowercase_name] + self.camelcase_name = self.config_class.replace("Config", "") + + # Get tokenizer class + if self.lowercase_name in TOKENIZER_MAPPING_NAMES: + self.tokenizer_class = None + self.fast_tokenizer_class = TOKENIZER_MAPPING_NAMES[self.lowercase_name] + self.fast_tokenizer_class = ( + None if self.fast_tokenizer_class == "PreTrainedTokenizerFast" else self.fast_tokenizer_class + ) + else: + self.tokenizer_class, self.fast_tokenizer_class = None, None + + self.image_processor_classes = IMAGE_PROCESSOR_MAPPING_NAMES.get(self.lowercase_name, None) + self.video_processor_class = VIDEO_PROCESSOR_MAPPING_NAMES.get(self.lowercase_name, None) + self.feature_extractor_class = FEATURE_EXTRACTOR_MAPPING_NAMES.get(self.lowercase_name, None) + self.processor_class = PROCESSOR_MAPPING_NAMES.get(self.lowercase_name, None) + + +def add_content_to_file(file_name: str | os.PathLike, new_content: str, add_after: str): + """ + A utility to add some content inside a given file. + + Args: + file_name (`str` or `os.PathLike`): + The name of the file in which we want to insert some content. + new_content (`str`): + The content to add. + add_after (`str`): + The new content is added just after the first instance matching it. + """ + with open(file_name, "r", encoding="utf-8") as f: + old_content = f.read() + + before, after = old_content.split(add_after, 1) + new_content = before + add_after + new_content + after + + with open(file_name, "w", encoding="utf-8") as f: + f.write(new_content) + + +def add_model_to_auto_mappings( + repo_path: Path, + old_model_infos: ModelInfos, + new_lowercase_name: str, + new_model_paper_name: str, + filenames_to_add: list[tuple[str, bool]], +): + """ + Add a model to all the relevant mappings in the auto module. + + Args: + old_model_infos (`ModelInfos`): + The structure containing the class information of the old model. + new_lowercase_name (`str`): + The new lowercase model name. + new_model_paper_name (`str`): + The fully cased name (as in the official paper name) of the new model. + filenames_to_add (`list[tuple[str, bool]]`): + A list of tuples of all potential filenames to add for a new model, along a boolean flag describing if we + should add this file or not. For example, [(`modeling_xxx.px`, True), (`configuration_xxx.py`, True), (`tokenization_xxx.py`, False),...] + """ + new_cased_name = "".join(x.title() for x in new_lowercase_name.replace("-", "_").split("_")) + old_lowercase_name = old_model_infos.lowercase_name + old_cased_name = old_model_infos.camelcase_name + filenames_to_add = [ + (filename.replace(old_lowercase_name, "auto"), to_add) for filename, to_add in filenames_to_add[1:] + ] + # fast tokenizer has the same auto mappings as normal ones + corrected_filenames_to_add = [] + has_image_processor = has_video_processor = False + for file, to_add in filenames_to_add: + if "image_processing" in file: + has_image_processor = True + elif "video_processing" in file: + has_video_processor = True + elif re.search(r"(?:tokenization)|(?:image_processing)_auto_fast.py", file): + previous_file, previous_to_add = corrected_filenames_to_add[-1] + corrected_filenames_to_add[-1] = (previous_file, previous_to_add or to_add) + else: + corrected_filenames_to_add.append((file, to_add)) + + # Add the config and image/video processor mappings directly as the handling is a bit different + add_content_to_file( + repo_path / "src" / "transformers" / "models" / "auto" / "auto_mappings.py", + new_content=f'("{new_lowercase_name}", "{new_cased_name}Config"),\n ', + add_after="CONFIG_MAPPING_NAMES = OrderedDict(\n [\n ", + ) + autofile = (repo_path / "src" / "transformers" / "models" / "auto" / "auto_mappings.py").read_text() + if has_image_processor: + matching_lines = re.findall(rf'^\s+\("{old_lowercase_name}",\s+{{[^}}]+}}\),?$', autofile, re.MULTILINE) + if matching_lines: + match = matching_lines[0] + add_content_to_file( + repo_path / "src" / "transformers" / "models" / "auto" / "auto_mappings.py", + new_content=match.replace(old_lowercase_name, new_lowercase_name).replace( + old_cased_name, new_cased_name + ) + + "\n", + add_after="IMAGE_PROCESSOR_MAPPING_NAMES = OrderedDict(\n [\n", + ) + if has_video_processor: + # Extract the VIDEO_PROCESSOR_MAPPING_NAMES block first + block_match = re.search( + r"VIDEO_PROCESSOR_MAPPING_NAMES\s*=\s*OrderedDict\(\s*\[(.*?)\]\s*\)", autofile, re.DOTALL + ) + block = block_match.group(1) # type: ignore + matching_lines = re.findall(rf'^\s+\("{old_lowercase_name}",\s+"[^"]+"\),?$', block, re.MULTILINE) + if matching_lines: + match = matching_lines[0] + add_content_to_file( + repo_path / "src" / "transformers" / "models" / "auto" / "auto_mappings.py", + new_content=match.replace(old_lowercase_name, new_lowercase_name).replace( + old_cased_name, new_cased_name + ) + + "\n", + add_after="VIDEO_PROCESSOR_MAPPING_NAMES = OrderedDict(\n [\n", + ) + + for filename, to_add in corrected_filenames_to_add: + if to_add: + # The auto mapping + filename = filename.replace("_fast.py", ".py") + file = (repo_path / "src" / "transformers" / "models" / "auto" / filename).read_text() + # The regex has to be a bit complex like this as the tokenizer mapping has new lines everywhere + matching_lines = re.findall( + rf'( {{8,12}}\(\s*"{old_lowercase_name}",.*?\),\n)(?: {{4,12}}\(|\])', file, re.DOTALL + ) + for match in matching_lines: + add_content_to_file( + repo_path / "src" / "transformers" / "models" / "auto" / filename, + new_content=match.replace(old_lowercase_name, new_lowercase_name).replace( + old_cased_name, new_cased_name + ), + add_after=match, + ) + + +def create_doc_file(new_paper_name: str, public_classes: list[str]): + """ + Create a new doc file to fill for the new model. + + Args: + new_paper_name (`str`): + The fully cased name (as in the official paper name) of the new model. + public_classes (`list[str]`): + A list of all the public classes that the model will have in the library. + """ + added_note = ( + "\n\n⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that " + "may not be rendered properly in your Markdown viewer.\n\n-->\n\n" + ) + copyright_for_markdown = re.sub(r"# ?", "", COPYRIGHT).replace("coding=utf-8\n", " batch_size, channels, spec_height * freq_ratio, spec_width // freq_ratio + normalized_input_features = normalized_input_features.reshape( + batch, channels * self.freq_ratio, time // self.freq_ratio, freq + ) + normalized_input_features = normalized_input_features.permute(0, 1, 3, 2).contiguous() + normalized_input_features = normalized_input_features.reshape( + batch, channels, freq * self.freq_ratio, time // self.freq_ratio + ) + + return normalized_input_features + + @can_return_tuple + def forward( + self, + input_features, + is_longer: torch.FloatTensor | None = None, + output_attentions: bool | None = False, + output_hidden_states: bool | None = False, + output_hidden_states_before_downsampling: bool | None = False, + always_partition: bool | None = False, + return_dict: bool | None = True, + ) -> tuple | ClapAudioModelOutput: + # Unique logic so no refactor here yet + output_hidden_states = output_hidden_states or self.config.output_hidden_states + output_attentions = output_attentions or self.config.output_attentions + + input_features = input_features.transpose(1, 3) + normalized_input_features = self.batch_norm(input_features) + normalized_input_features = normalized_input_features.transpose(1, 3) + + is_longer_list_idx = None + if self.enable_fusion: + is_longer_list = is_longer.to(input_features.device) + is_longer_list_idx = torch.where(is_longer_list == 1)[0] + + hidden_states = self.reshape_mel2img(normalized_input_features) + + frames_num = hidden_states.shape[2] + + hidden_states = self.patch_embed(hidden_states, is_longer_list_idx) + + all_hidden_states = () if output_hidden_states else None + all_reshaped_hidden_states = () if output_hidden_states else None + all_self_attentions = () if output_attentions else None + + input_dimensions = self.input_resolutions[0] + + if output_hidden_states: + batch_size, _, hidden_size = hidden_states.shape + # rearrange batch_size (height width) channels -> batch_size channel height width + reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size) + reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2) + all_hidden_states += (hidden_states,) + all_reshaped_hidden_states += (reshaped_hidden_state,) + + for i, layer_module in enumerate(self.layers): + input_dimensions = self.input_resolutions[i] + + layer_outputs = layer_module(hidden_states, input_dimensions, output_attentions, always_partition) + + hidden_states = layer_outputs[0] + + hidden_states_before_downsampling = layer_outputs[1] + output_dimensions = layer_outputs[2] + + input_dimensions = (output_dimensions[-2], output_dimensions[-1]) + + if output_hidden_states and output_hidden_states_before_downsampling: + batch_size, _, hidden_size = hidden_states_before_downsampling.shape + # rearrange batch_size (height width) channels -> batch_size channel height width + # here we use the original (not downsampled) height and width + reshaped_hidden_state = hidden_states_before_downsampling.view( + batch_size, *(output_dimensions[0], output_dimensions[1]), hidden_size + ) + reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2) + all_hidden_states += (hidden_states_before_downsampling,) + all_reshaped_hidden_states += (reshaped_hidden_state,) + elif output_hidden_states and not output_hidden_states_before_downsampling: + batch_size, _, hidden_size = hidden_states.shape + # rearrange batch_size (height width) channels -> batch_size channel height width + reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size) + reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2) + all_hidden_states += (hidden_states,) + all_reshaped_hidden_states += (reshaped_hidden_state,) + + if output_attentions: + all_self_attentions += layer_outputs[3:] + + last_hidden_state = self.norm(hidden_states) + + batch_size, _, n_channels = last_hidden_state.shape + + freq_shape = frames_num // (2 ** (len(self.depths) - 1)) // self.patch_stride[0] + temporal_shape = frames_num // (2 ** (len(self.depths) - 1)) // self.patch_stride[1] + + last_hidden_state = ( + last_hidden_state.permute(0, 2, 1).contiguous().reshape(batch_size, n_channels, freq_shape, temporal_shape) + ) + + batch_size, n_channels, n_frequencies, n_temp = last_hidden_state.shape + # group 2D CNN + c_freq_bin = n_frequencies // self.freq_ratio + last_hidden_state = last_hidden_state.reshape( + batch_size, n_channels, n_frequencies // c_freq_bin, c_freq_bin, n_temp + ) + last_hidden_state = ( + last_hidden_state.permute(0, 1, 3, 2, 4).contiguous().reshape(batch_size, n_channels, c_freq_bin, -1) + ) + latent_output = self.avgpool(torch.flatten(last_hidden_state, 2)) + latent_output = torch.flatten(latent_output, 1) + + return BaseModelOutputWithPooling( + last_hidden_state=last_hidden_state, + pooler_output=latent_output, + hidden_states=all_reshaped_hidden_states, + attentions=all_self_attentions, + ) + + +class ClapProjectionLayer(nn.Module): + def __init__(self, config: ClapAudioConfig | ClapTextConfig): + super().__init__() + self.config = config + hidden_size = config.hidden_size + projection_dim = config.projection_dim + + self.linear1 = nn.Linear(hidden_size, projection_dim) + self.activation = ACT2FN[config.projection_hidden_act] + self.linear2 = nn.Linear(projection_dim, projection_dim) + + def forward(self, hidden_states): + hidden_states = self.linear1(hidden_states) + hidden_states = self.activation(hidden_states) + hidden_states = self.linear2(hidden_states) + return hidden_states + + +# Copied from transformers.models.roberta.modeling_roberta.RobertaEmbeddings with Roberta->ClapText, persistent=False->persistent=True +class ClapTextEmbeddings(nn.Module): + """Construct the embeddings from word, position and token_type embeddings.""" + + def __init__(self, config): + super().__init__() + self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) + self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size) + + self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + # position_ids (1, len position emb) is contiguous in memory and exported when serialized + self.register_buffer( + "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=True + ) + self.register_buffer( + "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=True + ) + + self.padding_idx = config.pad_token_id + self.position_embeddings = nn.Embedding( + config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx + ) + + def forward( + self, + input_ids: torch.LongTensor | None = None, + token_type_ids: torch.LongTensor | None = None, + position_ids: torch.LongTensor | None = None, + inputs_embeds: torch.FloatTensor | None = None, + past_key_values_length: int = 0, + ) -> torch.Tensor: + if position_ids is None: + if input_ids is not None: + # Create the position ids from the input token ids. Any padded tokens remain padded. + position_ids = self.create_position_ids_from_input_ids( + input_ids, self.padding_idx, past_key_values_length + ) + else: + position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds, self.padding_idx) + + if input_ids is not None: + input_shape = input_ids.size() + else: + input_shape = inputs_embeds.size()[:-1] + + batch_size, seq_length = input_shape + + # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs + # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves + # issue #5664 + if token_type_ids is None: + if hasattr(self, "token_type_ids"): + # NOTE: We assume either pos ids to have bsz == 1 (broadcastable) or bsz == effective bsz (input_shape[0]) + buffered_token_type_ids = self.token_type_ids.expand(position_ids.shape[0], -1) + buffered_token_type_ids = torch.gather(buffered_token_type_ids, dim=1, index=position_ids) + token_type_ids = buffered_token_type_ids.expand(batch_size, seq_length) + else: + token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device) + + if inputs_embeds is None: + inputs_embeds = self.word_embeddings(input_ids) + token_type_embeddings = self.token_type_embeddings(token_type_ids) + embeddings = inputs_embeds + token_type_embeddings + + position_embeddings = self.position_embeddings(position_ids) + embeddings = embeddings + position_embeddings + + embeddings = self.LayerNorm(embeddings) + embeddings = self.dropout(embeddings) + return embeddings + + @staticmethod + def create_position_ids_from_inputs_embeds(inputs_embeds, padding_idx): + """ + We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids. + + Args: + inputs_embeds: torch.Tensor + + Returns: torch.Tensor + """ + input_shape = inputs_embeds.size()[:-1] + sequence_length = input_shape[1] + + position_ids = torch.arange( + padding_idx + 1, sequence_length + padding_idx + 1, dtype=torch.long, device=inputs_embeds.device + ) + return position_ids.unsqueeze(0).expand(input_shape) + + @staticmethod + def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0): + """ + Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols + are ignored. This is modified from fairseq's `utils.make_positions`. + + Args: + x: torch.Tensor x: + + Returns: torch.Tensor + """ + # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA. + mask = input_ids.ne(padding_idx).int() + incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask + return incremental_indices.long() + padding_idx + + +# Copied from transformers.models.align.modeling_align.eager_attention_forward +def eager_attention_forward( + module: nn.Module, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attention_mask: torch.Tensor | None, + scaling: float, + dropout: float = 0.0, + **kwargs, +): + attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling + if attention_mask is not None: + attn_weights = attn_weights + attention_mask + + attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) + attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training) + + attn_output = torch.matmul(attn_weights, value) + attn_output = attn_output.transpose(1, 2).contiguous() + return attn_output, attn_weights + + +# Copied from transformers.models.align.modeling_align.AlignTextSelfAttention with Align->Clap +class ClapTextSelfAttention(nn.Module): + def __init__(self, config): + super().__init__() + if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): + raise ValueError( + f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention " + f"heads ({config.num_attention_heads})" + ) + + self.config = config + self.num_attention_heads = config.num_attention_heads + self.attention_head_size = int(config.hidden_size / config.num_attention_heads) + self.all_head_size = self.num_attention_heads * self.attention_head_size + + self.query = nn.Linear(config.hidden_size, self.all_head_size) + self.key = nn.Linear(config.hidden_size, self.all_head_size) + self.value = nn.Linear(config.hidden_size, self.all_head_size) + + self.dropout = nn.Dropout(config.attention_probs_dropout_prob) + self.attention_dropout = config.attention_probs_dropout_prob + self.scaling = self.attention_head_size**-0.5 + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: torch.FloatTensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple[torch.Tensor, torch.Tensor | None]: + input_shape = hidden_states.shape[:-1] + hidden_shape = (*input_shape, -1, self.attention_head_size) + + query_states = self.query(hidden_states).view(hidden_shape).transpose(1, 2) + key_states = self.key(hidden_states).view(hidden_shape).transpose(1, 2) + value_states = self.value(hidden_states).view(hidden_shape).transpose(1, 2) + + attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( + self.config._attn_implementation, eager_attention_forward + ) + + attn_output, attn_weights = attention_interface( + self, + query_states, + key_states, + value_states, + attention_mask, + dropout=0.0 if not self.training else self.attention_dropout, + scaling=self.scaling, + **kwargs, + ) + + attn_output = attn_output.reshape(*input_shape, -1).contiguous() + return attn_output, attn_weights + + +# Copied from transformers.models.bert.modeling_bert.BertSelfOutput +class ClapTextSelfOutput(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.dropout(hidden_states) + hidden_states = self.LayerNorm(hidden_states + input_tensor) + return hidden_states + + +# Copied from transformers.models.align.modeling_align.AlignTextAttention with Align->Clap +class ClapTextAttention(nn.Module): + def __init__(self, config): + super().__init__() + self.self = ClapTextSelfAttention(config) + self.output = ClapTextSelfOutput(config) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: torch.FloatTensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> torch.Tensor: + residual = hidden_states + hidden_states, _ = self.self( + hidden_states, + attention_mask=attention_mask, + **kwargs, + ) + hidden_states = self.output(hidden_states, residual) + return hidden_states + + +# Copied from transformers.models.bert.modeling_bert.BertIntermediate +class ClapTextIntermediate(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.intermediate_size) + if isinstance(config.hidden_act, str): + self.intermediate_act_fn = ACT2FN[config.hidden_act] + else: + self.intermediate_act_fn = config.hidden_act + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.intermediate_act_fn(hidden_states) + return hidden_states + + +# Copied from transformers.models.bert.modeling_bert.BertOutput +class ClapTextOutput(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.intermediate_size, config.hidden_size) + self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.dropout(hidden_states) + hidden_states = self.LayerNorm(hidden_states + input_tensor) + return hidden_states + + +# Copied from transformers.models.align.modeling_align.AlignTextLayer with Align->Clap +class ClapTextLayer(GradientCheckpointingLayer): + def __init__(self, config): + super().__init__() + self.chunk_size_feed_forward = config.chunk_size_feed_forward + self.seq_len_dim = 1 + self.attention = ClapTextAttention(config) + self.intermediate = ClapTextIntermediate(config) + self.output = ClapTextOutput(config) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: torch.FloatTensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> torch.Tensor: + hidden_states = self.attention( + hidden_states, + attention_mask=attention_mask, + **kwargs, + ) + + hidden_states = apply_chunking_to_forward( + self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, hidden_states + ) + + return hidden_states + + def feed_forward_chunk(self, attention_output): + intermediate_output = self.intermediate(attention_output) + layer_output = self.output(intermediate_output, attention_output) + return layer_output + + +# Copied from transformers.models.align.modeling_align.AlignTextEncoder with Align->Clap +class ClapTextEncoder(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.layer = nn.ModuleList([ClapTextLayer(config) for i in range(config.num_hidden_layers)]) + self.gradient_checkpointing = False + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: torch.FloatTensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> BaseModelOutput: + for layer_module in self.layer: + hidden_states = layer_module( + hidden_states, + attention_mask, + **kwargs, + ) + + return BaseModelOutput( + last_hidden_state=hidden_states, + ) + + +# Copied from transformers.models.bert.modeling_bert.BertPooler +class ClapTextPooler(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + self.activation = nn.Tanh() + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + # We "pool" the model by simply taking the hidden state corresponding + # to the first token. + first_token_tensor = hidden_states[:, 0] + pooled_output = self.dense(first_token_tensor) + pooled_output = self.activation(pooled_output) + return pooled_output + + +@auto_docstring +class ClapPreTrainedModel(PreTrainedModel): + config: ClapConfig + base_model_prefix = "clap" + input_modalities = ("audio", "text") + supports_gradient_checkpointing = False + + @torch.no_grad() + def _init_weights(self, module: nn.Module): + """Initialize the weights""" + factor = self.config.initializer_factor + + if isinstance(module, ClapTextEmbeddings): + init.normal_(module.position_embeddings.weight, mean=0.0, std=factor * 0.02) + init.normal_(module.token_type_embeddings.weight, mean=0.0, std=factor * 0.02) + init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1))) + init.zeros_(module.token_type_ids) + elif isinstance(module, ClapModel): + init.constant_(module.logit_scale_a, math.log(self.config.logit_scale_init_value)) + init.constant_(module.logit_scale_t, math.log(self.config.logit_scale_init_value)) + elif isinstance(module, nn.Embedding): + init.normal_(module.weight, mean=0.0, std=factor * 0.02) + elif isinstance(module, (nn.LayerNorm, nn.BatchNorm2d)): + init.zeros_(module.bias) + init.ones_(module.weight) + if getattr(module, "running_mean", None) is not None: + init.zeros_(module.running_mean) + init.ones_(module.running_var) + init.zeros_(module.num_batches_tracked) + elif isinstance(module, (nn.Conv2d, nn.Linear)): + in_proj_std = (self.config.hidden_size**-0.5) * ((2 * self.config.num_hidden_layers) ** -0.5) * factor + init.normal_(module.weight, std=in_proj_std) + if module.bias is not None: + init.zeros_(module.bias) + elif isinstance(module, ClapAudioSelfAttention): + init.zeros_(module.relative_position_bias_table) + init.copy_(module.relative_position_index, module.create_relative_position_index()) + + +class ClapAudioModel(ClapPreTrainedModel): + config: ClapAudioConfig + main_input_name = "input_features" + input_modalities = "audio" + + def __init__(self, config: ClapAudioConfig): + super().__init__(config) + self.audio_encoder = ClapAudioEncoder(config) + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self) -> nn.Module: + return self.audio_encoder.patch_embed.proj + + @auto_docstring + def forward( + self, + input_features: torch.FloatTensor | None = None, + is_longer: torch.BoolTensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | BaseModelOutputWithPooling: + r""" + is_longer (`torch.FloatTensor`, of shape `(batch_size, 1)`, *optional*): + Whether the audio clip is longer than `max_length`. If `True`, a feature fusion will be enabled to enhance + the features. + + Examples: + + ```python + >>> from datasets import load_dataset + >>> from transformers import AutoProcessor, ClapAudioModel + + >>> dataset = load_dataset("hf-internal-testing/ashraq-esc50-1-dog-example") + >>> audio_sample = dataset["train"]["audio"][0]["array"] + + >>> model = ClapAudioModel.from_pretrained("laion/clap-htsat-fused") + >>> processor = AutoProcessor.from_pretrained("laion/clap-htsat-fused") + + >>> inputs = processor(audio=audio_sample, return_tensors="pt") + + >>> outputs = model(**inputs) + >>> last_hidden_state = outputs.last_hidden_state + ```""" + return self.audio_encoder( + input_features=input_features, + is_longer=is_longer, + **kwargs, + ) + + +@auto_docstring( + custom_intro=""" + The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of + cross-attention is added between the self-attention layers, following the architecture described in *Attention is + all you need*_ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz + Kaiser and Illia Polosukhin. + + To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set + to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and + `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass. + + .. _*Attention is all you need*: https://huggingface.co/papers/1706.03762 + """ +) +class ClapTextModel(ClapPreTrainedModel): + config: ClapTextConfig + input_modalities = ("text",) + _can_record_outputs = { + "hidden_states": ClapTextLayer, + "attentions": ClapTextSelfAttention, + } + + def __init__(self, config, add_pooling_layer=True): + r""" + add_pooling_layer (bool, *optional*, defaults to `True`): + Whether to add a pooling layer + """ + super().__init__(config) + self.config = config + + self.embeddings = ClapTextEmbeddings(config) + self.encoder = ClapTextEncoder(config) + + self.pooler = ClapTextPooler(config) if add_pooling_layer else None + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.embeddings.word_embeddings + + def set_input_embeddings(self, value): + self.embeddings.word_embeddings = value + + @merge_with_config_defaults + @capture_outputs + @auto_docstring + def forward( + self, + input_ids: torch.Tensor | None = None, + attention_mask: torch.Tensor | None = None, + token_type_ids: torch.Tensor | None = None, + position_ids: torch.Tensor | None = None, + inputs_embeds: torch.Tensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> BaseModelOutputWithPooling: + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") + elif input_ids is not None: + self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask) + input_shape = input_ids.size() + elif inputs_embeds is not None: + input_shape = inputs_embeds.size()[:-1] + else: + raise ValueError("You have to specify either input_ids or inputs_embeds") + + batch_size, seq_length = input_shape + device = input_ids.device if input_ids is not None else inputs_embeds.device + + if attention_mask is None: + attention_mask = torch.ones(((batch_size, seq_length)), device=device) + + # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] + # ourselves in which case we just need to make it broadcastable to all heads. + extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape) + + embedding_output = self.embeddings( + input_ids=input_ids, + position_ids=position_ids, + token_type_ids=token_type_ids, + inputs_embeds=inputs_embeds, + ) + encoder_outputs = self.encoder( + embedding_output, + attention_mask=extended_attention_mask, + **kwargs, + ) + sequence_output = encoder_outputs[0] + pooled_output = self.pooler(sequence_output) if self.pooler is not None else None + + return BaseModelOutputWithPooling( + last_hidden_state=sequence_output, + pooler_output=pooled_output, + ) + + +@auto_docstring +class ClapModel(ClapPreTrainedModel): + config: ClapConfig + + def __init__(self, config: ClapConfig): + super().__init__(config) + + if not isinstance(config.text_config, ClapTextConfig): + raise TypeError( + "config.text_config is expected to be of type ClapTextConfig but is of type" + f" {type(config.text_config)}." + ) + + if not isinstance(config.audio_config, ClapAudioConfig): + raise TypeError( + "config.audio_config is expected to be of type ClapAudioConfig but is of type" + f" {type(config.audio_config)}." + ) + + text_config = config.text_config + audio_config = config.audio_config + + self.logit_scale_a = nn.Parameter(torch.tensor(math.log(config.logit_scale_init_value))) + self.logit_scale_t = nn.Parameter(torch.tensor(math.log(config.logit_scale_init_value))) + + self.projection_dim = config.projection_dim + + self.text_model = ClapTextModel(text_config) + self.text_projection = ClapProjectionLayer(text_config) + + self.audio_model = ClapAudioModel(audio_config) + self.audio_projection = ClapProjectionLayer(audio_config) + + # Initialize weights and apply final processing + self.post_init() + + @can_return_tuple + @auto_docstring + def get_text_features( + self, + input_ids: torch.Tensor, + attention_mask: torch.Tensor | None = None, + position_ids: torch.Tensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | BaseModelOutputWithPooling: + r""" + Examples: + + ```python + >>> import torch + >>> from transformers import AutoTokenizer, ClapModel + + >>> model = ClapModel.from_pretrained("laion/clap-htsat-unfused") + >>> tokenizer = AutoTokenizer.from_pretrained("laion/clap-htsat-unfused") + + >>> inputs = tokenizer(["the sound of a cat", "the sound of a dog"], padding=True, return_tensors="pt") + >>> with torch.inference_mode(): + ... text_features = model.get_text_features(**inputs) + ```""" + text_outputs: BaseModelOutputWithPooling = self.text_model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + **kwargs, + ) + text_features = self.text_projection(text_outputs.pooler_output) + text_outputs.pooler_output = F.normalize(text_features, dim=-1) + + return text_outputs + + @can_return_tuple + @auto_docstring + def get_audio_features( + self, + input_features: torch.Tensor, + is_longer: torch.Tensor | None = None, + attention_mask: torch.Tensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | BaseModelOutputWithPooling: + r""" + is_longer (`torch.FloatTensor`, of shape `(batch_size, 1)`, *optional*): + Whether the audio clip is longer than `max_length`. If `True`, a feature fusion will be enabled to enhance + the features. + + Examples: + + ```python + >>> import torch + >>> from transformers import AutoFeatureExtractor, ClapModel + + >>> model = ClapModel.from_pretrained("laion/clap-htsat-unfused") + >>> feature_extractor = AutoFeatureExtractor.from_pretrained("laion/clap-htsat-unfused") + >>> random_audio = torch.rand((16_000)) + + >>> inputs = feature_extractor(random_audio, return_tensors="pt") + >>> with torch.inference_mode(): + ... audio_features = model.get_audio_features(**inputs) + ```""" + audio_outputs: BaseModelOutputWithPooling = self.audio_model( + input_features=input_features, is_longer=is_longer, **kwargs + ) + audio_features = self.audio_projection(audio_outputs.pooler_output) + audio_outputs.pooler_output = F.normalize(audio_features, dim=-1) + + return audio_outputs + + @can_return_tuple + @auto_docstring + def forward( + self, + input_ids: torch.LongTensor | None = None, + input_features: torch.FloatTensor | None = None, + is_longer: torch.BoolTensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.LongTensor | None = None, + return_loss: bool | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | ClapOutput: + r""" + is_longer (`torch.FloatTensor`, of shape `(batch_size, 1)`, *optional*): + Whether the audio clip is longer than `max_length`. If `True`, a feature fusion will be enabled to enhance + the features. + return_loss (`bool`, *optional*): + Whether or not to return the contrastive loss. + + Examples: + + ```python + >>> from datasets import load_dataset + >>> from transformers import AutoProcessor, ClapModel + + >>> dataset = load_dataset("hf-internal-testing/ashraq-esc50-1-dog-example") + >>> audio_sample = dataset["train"]["audio"][0]["array"] + + >>> model = ClapModel.from_pretrained("laion/clap-htsat-unfused") + >>> processor = AutoProcessor.from_pretrained("laion/clap-htsat-unfused") + + >>> input_text = ["Sound of a dog", "Sound of vacuum cleaner"] + + >>> inputs = processor(text=input_text, audio=audio_sample, return_tensors="pt", padding=True) + + >>> outputs = model(**inputs) + >>> logits_per_audio = outputs.logits_per_audio # this is the audio-text similarity score + >>> probs = logits_per_audio.softmax(dim=-1) # we can take the softmax to get the label probabilities + ```""" + audio_outputs = self.audio_model( + input_features=input_features, + is_longer=is_longer, + **kwargs, + ) + + text_outputs = self.text_model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + **kwargs, + ) + + audio_embeds = audio_outputs.pooler_output + audio_embeds = self.audio_projection(audio_embeds) + + text_embeds = text_outputs.pooler_output + text_embeds = self.text_projection(text_embeds) + + # normalized features + audio_embeds = audio_embeds / audio_embeds.norm(p=2, dim=-1, keepdim=True) + text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True) + + # cosine similarity as logits + logit_scale_text = self.logit_scale_t.exp() + logit_scale_audio = self.logit_scale_a.exp() + logits_per_text = torch.matmul(text_embeds, audio_embeds.t()) * logit_scale_text + logits_per_audio = torch.matmul(audio_embeds, text_embeds.t()) * logit_scale_audio + + loss = None + if return_loss: + caption_loss = contrastive_loss(logits_per_text) + audio_loss = contrastive_loss(logits_per_audio.t()) + loss = (caption_loss + audio_loss) / 2.0 + + return ClapOutput( + loss=loss, + logits_per_audio=logits_per_audio, + logits_per_text=logits_per_text, + text_embeds=text_embeds, + audio_embeds=audio_embeds, + text_model_output=text_outputs, + audio_model_output=audio_outputs, + ) + + +@auto_docstring +class ClapTextModelWithProjection(ClapPreTrainedModel): + config: ClapTextConfig + input_modalities = ("text",) + _can_record_outputs = { + "hidden_states": ClapTextLayer, + "attentions": ClapTextSelfAttention, + } + + def __init__(self, config: ClapTextConfig): + super().__init__(config) + self.text_model = ClapTextModel(config) + self.text_projection = ClapProjectionLayer(config) + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self) -> nn.Module: + return self.text_model.embeddings.word_embeddings + + def set_input_embeddings(self, value): + self.text_model.embeddings.word_embeddings = value + + @can_return_tuple + @auto_docstring + def forward( + self, + input_ids: torch.Tensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.Tensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | ClapTextModelOutput: + r""" + Examples: + + ```python + >>> from transformers import AutoTokenizer, ClapTextModelWithProjection + + >>> model = ClapTextModelWithProjection.from_pretrained("laion/clap-htsat-unfused") + >>> tokenizer = AutoTokenizer.from_pretrained("laion/clap-htsat-unfused") + + >>> inputs = tokenizer(["a sound of a cat", "a sound of a dog"], padding=True, return_tensors="pt") + + >>> outputs = model(**inputs) + >>> text_embeds = outputs.text_embeds + ```""" + text_outputs: BaseModelOutputWithPooling = self.text_model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + **kwargs, + ) + pooled_output = text_outputs.pooler_output + text_embeds = self.text_projection(pooled_output) + + return ClapTextModelOutput( + text_embeds=text_embeds, + last_hidden_state=text_outputs.last_hidden_state, + hidden_states=text_outputs.hidden_states, + attentions=text_outputs.attentions, + ) + + +@auto_docstring +class ClapAudioModelWithProjection(ClapPreTrainedModel): + config: ClapAudioConfig + main_input_name = "input_features" + input_modalities = "audio" + + def __init__(self, config: ClapAudioConfig): + super().__init__(config) + self.audio_model = ClapAudioModel(config) + self.audio_projection = ClapProjectionLayer(config) + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self) -> nn.Module: + return self.audio_model.audio_encoder.patch_embed.proj + + @can_return_tuple + @auto_docstring + def forward( + self, + input_features: torch.FloatTensor | None = None, + is_longer: torch.BoolTensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | ClapAudioModelOutput: + r""" + is_longer (`torch.FloatTensor`, of shape `(batch_size, 1)`, *optional*): + Whether the audio clip is longer than `max_length`. If `True`, a feature fusion will be enabled to enhance + the features. + + Examples: + + ```python + >>> from datasets import load_dataset + >>> from transformers import ClapAudioModelWithProjection, ClapProcessor + + >>> model = ClapAudioModelWithProjection.from_pretrained("laion/clap-htsat-fused") + >>> processor = ClapProcessor.from_pretrained("laion/clap-htsat-fused") + + >>> dataset = load_dataset("hf-internal-testing/ashraq-esc50-1-dog-example") + >>> audio_sample = dataset["train"]["audio"][0]["array"] + + >>> inputs = processor(audio=audio_sample, return_tensors="pt") + >>> outputs = model(**inputs) + >>> audio_embeds = outputs.audio_embeds + ```""" + audio_outputs: BaseModelOutputWithPooling = self.audio_model( + input_features=input_features, + is_longer=is_longer, + **kwargs, + ) + + audio_embeds = self.audio_projection(audio_outputs.pooler_output) + + return ClapAudioModelOutput( + audio_embeds=audio_embeds, + last_hidden_state=audio_outputs.last_hidden_state, + attentions=audio_outputs.attentions, + hidden_states=audio_outputs.hidden_states, + ) + + +__all__ = [ + "ClapModel", + "ClapPreTrainedModel", + "ClapTextModel", + "ClapTextModelWithProjection", + "ClapAudioModel", + "ClapAudioModelWithProjection", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clap/processing_clap.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clap/processing_clap.py new file mode 100644 index 0000000000000000000000000000000000000000..567aa19ce60775e9f14ed220f4edecb910cf1c21 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clap/processing_clap.py @@ -0,0 +1,31 @@ +# Copyright 2023 The HuggingFace Inc. team. +# +# 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. +""" +Audio/Text processor class for CLAP +""" + +from ...processing_utils import ProcessorMixin +from ...utils import auto_docstring, logging + + +logger = logging.get_logger(__name__) + + +@auto_docstring +class ClapProcessor(ProcessorMixin): + def __init__(self, feature_extractor, tokenizer): + super().__init__(feature_extractor, tokenizer) + + +__all__ = ["ClapProcessor"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b3554d4ac39ae7b8316c59457058222f1b38dd42 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/__init__.py @@ -0,0 +1,31 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# 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. +from typing import TYPE_CHECKING + +from ...utils import _LazyModule +from ...utils.import_utils import define_import_structure + + +if TYPE_CHECKING: + from .configuration_clip import * + from .image_processing_clip import * + from .image_processing_pil_clip import * + from .modeling_clip import * + from .processing_clip import * + from .tokenization_clip import * +else: + import sys + + _file = globals()["__file__"] + sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/configuration_clip.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/configuration_clip.py new file mode 100644 index 0000000000000000000000000000000000000000..dec74a2b75c66f177ad7001bcf4ae22b4bfe42c1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/configuration_clip.py @@ -0,0 +1,248 @@ +# Copyright 2021 The HuggingFace Inc. team. All rights reserved. +# +# 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. +"""CLIP model configuration""" + +from huggingface_hub.dataclasses import strict + +from ...configuration_utils import PreTrainedConfig +from ...utils import auto_docstring, logging + + +logger = logging.get_logger(__name__) + + +@auto_docstring(checkpoint="openai/clip-vit-base-patch32") +@strict +class CLIPTextConfig(PreTrainedConfig): + r""" + Example: + + ```python + >>> from transformers import CLIPTextConfig, CLIPTextModel + + >>> # Initializing a CLIPTextConfig with openai/clip-vit-base-patch32 style configuration + >>> configuration = CLIPTextConfig() + + >>> # Initializing a CLIPTextModel (with random weights) from the openai/clip-vit-base-patch32 style configuration + >>> model = CLIPTextModel(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + model_type = "clip_text_model" + base_config_key = "text_config" + + vocab_size: int = 49408 + hidden_size: int = 512 + intermediate_size: int = 2048 + projection_dim: int | None = 512 + num_hidden_layers: int = 12 + num_attention_heads: int = 8 + max_position_embeddings: int = 77 + hidden_act: str = "quick_gelu" + layer_norm_eps: float | None = 1e-5 + attention_dropout: int | float | None = 0.0 + initializer_range: float = 0.02 + initializer_factor: float | None = 1.0 + + # This differs from `CLIPTokenizer`'s default and from openai/clip + # See https://github.com/huggingface/transformers/pull/24773#issuecomment-1632287538 + pad_token_id: int | None = 1 + bos_token_id: int | None = 49406 + eos_token_id: int | list[int] | None = 49407 + + def validate_architecture(self): + """Part of `@strict`-powered validation. Validates the architecture of the config.""" + if self.hidden_size % self.num_attention_heads != 0: + raise ValueError( + f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention " + f"heads ({self.num_attention_heads})." + ) + + +@auto_docstring(checkpoint="openai/clip-vit-base-patch32") +@strict +class CLIPVisionConfig(PreTrainedConfig): + r""" + Example: + + ```python + >>> from transformers import CLIPVisionConfig, CLIPVisionModel + + >>> # Initializing a CLIPVisionConfig with openai/clip-vit-base-patch32 style configuration + >>> configuration = CLIPVisionConfig() + + >>> # Initializing a CLIPVisionModel (with random weights) from the openai/clip-vit-base-patch32 style configuration + >>> model = CLIPVisionModel(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + model_type = "clip_vision_model" + base_config_key = "vision_config" + + hidden_size: int = 768 + intermediate_size: int = 3072 + projection_dim: int = 512 + num_hidden_layers: int = 12 + num_attention_heads: int = 12 + num_channels: int = 3 + image_size: int | list[int] | tuple[int, int] | None = 224 + patch_size: int | list[int] | tuple[int, int] | None = 32 + hidden_act: str = "quick_gelu" + layer_norm_eps: float = 1e-5 + attention_dropout: int | float | None = 0.0 + initializer_range: float = 0.02 + initializer_factor: float = 1.0 + + def validate_architecture(self): + """Part of `@strict`-powered validation. Validates the architecture of the config.""" + if self.hidden_size % self.num_attention_heads != 0: + raise ValueError( + f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention " + f"heads ({self.num_attention_heads})." + ) + + +@auto_docstring(checkpoint="openai/clip-vit-base-patch32") +@strict +class CLIPConfig(PreTrainedConfig): + r""" + text_config (`dict`, *optional*): + Dictionary of configuration options used to initialize [`CLIPTextConfig`]. + vision_config (`dict`, *optional*): + Dictionary of configuration options used to initialize [`CLIPVisionConfig`]. + logit_scale_init_value (`float | int`, *optional*, defaults to 2.6592): + The initial value of the *logit_scale* parameter. Default is used as per the original CLIP implementation. + + Example: + + ```python + >>> from transformers import CLIPConfig, CLIPModel + + >>> # Initializing a CLIPConfig with openai/clip-vit-base-patch32 style configuration + >>> configuration = CLIPConfig() + + >>> # Initializing a CLIPModel (with random weights) from the openai/clip-vit-base-patch32 style configuration + >>> model = CLIPModel(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + + >>> # We can also initialize a CLIPConfig from a CLIPTextConfig and a CLIPVisionConfig + >>> from transformers import CLIPTextConfig, CLIPVisionConfig + + >>> # Initializing a CLIPText and CLIPVision configuration + >>> config_text = CLIPTextConfig() + >>> config_vision = CLIPVisionConfig() + + >>> config = CLIPConfig(text_config=config_text, vision_config=config_vision) + ```""" + + model_type = "clip" + sub_configs = {"text_config": CLIPTextConfig, "vision_config": CLIPVisionConfig} + + text_config: dict | CLIPTextConfig | None = None + vision_config: dict | CLIPVisionConfig | None = None + projection_dim: int | None = 512 + logit_scale_init_value: float | int | None = 2.6592 + initializer_factor: float | None = 1.0 + + def __post_init__(self, **kwargs): + if self.text_config is None: + text_config = {} + logger.info("`text_config` is `None`. Initializing the `CLIPTextConfig` with default values.") + elif isinstance(self.text_config, CLIPTextConfig): + text_config = self.text_config.to_dict() + else: + text_config = self.text_config + + if self.vision_config is None: + vision_config = {} + logger.info("`vision_config` is `None`. initializing the `CLIPVisionConfig` with default values.") + elif isinstance(self.vision_config, CLIPVisionConfig): + vision_config = self.vision_config.to_dict() + else: + vision_config = self.vision_config + + # For backward compatibility check keyword args + # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in + # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most + # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`. + text_config_dict = kwargs.pop("text_config_dict", None) + vision_config_dict = kwargs.pop("vision_config_dict", None) + + if text_config_dict is not None: + # This is the complete result when using `text_config_dict`. + _text_config_dict = CLIPTextConfig(**text_config_dict).to_dict() + + # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different. + for key, value in _text_config_dict.items(): + if key in text_config and value != text_config[key] and key != "transformers_version": + # If specified in `text_config_dict` + if key in text_config_dict: + message = ( + f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. " + f'The value `text_config_dict["{key}"]` will be used instead.' + ) + # If inferred from default argument values (just to be super careful) + else: + message = ( + f"`text_config_dict` is provided which will be used to initialize `CLIPTextConfig`. The " + f'value `text_config["{key}"]` will be overridden.' + ) + logger.info(message) + + # Update all values in `text_config` with the ones in `_text_config_dict`. + text_config.update(_text_config_dict) + + if vision_config_dict is not None: + # This is the complete result when using `vision_config_dict`. + _vision_config_dict = CLIPVisionConfig(**vision_config_dict).to_dict() + # convert keys to string instead of integer + if "id2label" in _vision_config_dict: + _vision_config_dict["id2label"] = { + str(key): value for key, value in _vision_config_dict["id2label"].items() + } + + # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different. + for key, value in _vision_config_dict.items(): + if key in vision_config and value != vision_config[key] and key != "transformers_version": + # If specified in `vision_config_dict` + if key in vision_config_dict: + message = ( + f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different " + f'values. The value `vision_config_dict["{key}"]` will be used instead.' + ) + # If inferred from default argument values (just to be super careful) + else: + message = ( + f"`vision_config_dict` is provided which will be used to initialize `CLIPVisionConfig`. " + f'The value `vision_config["{key}"]` will be overridden.' + ) + logger.info(message) + + # Update all values in `vision_config` with the ones in `_vision_config_dict`. + vision_config.update(_vision_config_dict) + + # Finally we can convert back our unified text/vision configs to `PretrainedConfig` + self.text_config = CLIPTextConfig(**text_config) + self.vision_config = CLIPVisionConfig(**vision_config) + + super().__post_init__(**kwargs) + + +__all__ = ["CLIPConfig", "CLIPTextConfig", "CLIPVisionConfig"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/image_processing_clip.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/image_processing_clip.py new file mode 100644 index 0000000000000000000000000000000000000000..d79b1a716b02e38e94f84e3ae7f89a47062e858d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/image_processing_clip.py @@ -0,0 +1,45 @@ +# Copyright 2021 The HuggingFace Inc. team. All rights reserved. +# +# 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. +"""Image processor class for CLIP.""" + +from ...image_processing_backends import TorchvisionBackend +from ...image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, PILImageResampling +from ...processing_utils import ImagesKwargs, Unpack +from ...utils import auto_docstring + + +@auto_docstring +class CLIPImageProcessor(TorchvisionBackend): + resample = PILImageResampling.BICUBIC + image_mean = OPENAI_CLIP_MEAN + image_std = OPENAI_CLIP_STD + size = {"shortest_edge": 224} + default_to_square = False + crop_size = {"height": 224, "width": 224} + do_resize = True + do_center_crop = True + do_rescale = True + do_normalize = True + do_convert_rgb = True + + def __init__(self, **kwargs: Unpack[ImagesKwargs]): + # for backwards compatibility of KOSMOS-2 + if "use_square_size" in kwargs and kwargs["use_square_size"]: + kwargs["size"] = {"height": self.size["shortest_edge"], "width": self.size["shortest_edge"]} + kwargs.pop("use_square_size") + + super().__init__(**kwargs) + + +__all__ = ["CLIPImageProcessor"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/image_processing_pil_clip.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/image_processing_pil_clip.py new file mode 100644 index 0000000000000000000000000000000000000000..228309ec0557196877d9585ed872bf036dbcc1d1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/image_processing_pil_clip.py @@ -0,0 +1,45 @@ +# Copyright 2021 The HuggingFace Inc. team. All rights reserved. +# +# 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. +"""Image processor class for CLIP.""" + +from ...image_processing_backends import PilBackend +from ...image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, PILImageResampling +from ...processing_utils import ImagesKwargs, Unpack +from ...utils import auto_docstring + + +@auto_docstring +class CLIPImageProcessorPil(PilBackend): + resample = PILImageResampling.BICUBIC + image_mean = OPENAI_CLIP_MEAN + image_std = OPENAI_CLIP_STD + size = {"shortest_edge": 224} + default_to_square = False + crop_size = {"height": 224, "width": 224} + do_resize = True + do_center_crop = True + do_rescale = True + do_normalize = True + do_convert_rgb = True + + def __init__(self, **kwargs: Unpack[ImagesKwargs]): + # for backwards compatibility of KOSMOS-2 + if "use_square_size" in kwargs and kwargs["use_square_size"]: + kwargs["size"] = {"height": self.size["shortest_edge"], "width": self.size["shortest_edge"]} + kwargs.pop("use_square_size") + + super().__init__(**kwargs) + + +__all__ = ["CLIPImageProcessorPil"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/modeling_clip.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/modeling_clip.py new file mode 100644 index 0000000000000000000000000000000000000000..3b2e983c78ba7416a24f2783cfc7cededb6a3533 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/modeling_clip.py @@ -0,0 +1,1035 @@ +# Copyright 2021 The OpenAI Team Authors and The HuggingFace Team. All rights reserved. +# +# 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. +"""PyTorch CLIP model.""" + +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any + +import torch +from torch import nn + +from ... import initialization as init +from ...activations import ACT2FN +from ...masking_utils import create_causal_mask +from ...modeling_layers import GradientCheckpointingLayer +from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, ImageClassifierOutput +from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel +from ...processing_utils import Unpack +from ...utils import ( + ModelOutput, + TransformersKwargs, + auto_docstring, + logging, + torch_int, +) +from ...utils.generic import can_return_tuple, merge_with_config_defaults +from ...utils.output_capturing import capture_outputs +from .configuration_clip import CLIPConfig, CLIPTextConfig, CLIPVisionConfig + + +logger = logging.get_logger(__name__) + + +# contrastive loss function, adapted from +# https://sachinruk.github.io/blog/2021-03-07-clip.html +def contrastive_loss(logits: torch.Tensor) -> torch.Tensor: + return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device)) + + +def image_text_contrastive_loss(similarity: torch.Tensor) -> torch.Tensor: + caption_loss = contrastive_loss(similarity) + image_loss = contrastive_loss(similarity.T) + return (caption_loss + image_loss) / 2.0 + + +def _get_vector_norm(tensor: torch.Tensor) -> torch.Tensor: + """ + This method is equivalent to tensor.norm(p=2, dim=-1, keepdim=True) and used to make + model `executorch` exportable. See issue https://github.com/pytorch/executorch/issues/3566 + """ + square_tensor = torch.pow(tensor, 2) + sum_tensor = torch.sum(square_tensor, dim=-1, keepdim=True) + normed_tensor = torch.pow(sum_tensor, 0.5) + return normed_tensor + + +@auto_docstring( + custom_intro=""" + Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states. + """ +) +@dataclass +class CLIPVisionModelOutput(ModelOutput): + r""" + image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`): + The image embeddings obtained by applying the projection layer to the pooler_output. + """ + + image_embeds: torch.FloatTensor | None = None + last_hidden_state: torch.FloatTensor | None = None + hidden_states: tuple[torch.FloatTensor, ...] | None = None + attentions: tuple[torch.FloatTensor, ...] | None = None + + +@auto_docstring( + custom_intro=""" + Base class for text model's outputs that also contains a pooling of the last hidden states. + """ +) +@dataclass +class CLIPTextModelOutput(ModelOutput): + r""" + text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`): + The text embeddings obtained by applying the projection layer to the pooler_output. + """ + + text_embeds: torch.FloatTensor | None = None + last_hidden_state: torch.FloatTensor | None = None + hidden_states: tuple[torch.FloatTensor, ...] | None = None + attentions: tuple[torch.FloatTensor, ...] | None = None + + +@dataclass +@auto_docstring +class CLIPOutput(ModelOutput): + r""" + loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`): + Contrastive loss for image-text similarity. + logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`): + The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text + similarity scores. + logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`): + The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image + similarity scores. + text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`): + The text embeddings obtained by applying the projection layer to the pooled output of [`CLIPTextModel`]. + image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`): + The image embeddings obtained by applying the projection layer to the pooled output of [`CLIPVisionModel`]. + text_model_output (`BaseModelOutputWithPooling`): + The output of the [`CLIPTextModel`]. + vision_model_output (`BaseModelOutputWithPooling`): + The output of the [`CLIPVisionModel`]. + """ + + loss: torch.FloatTensor | None = None + logits_per_image: torch.FloatTensor | None = None + logits_per_text: torch.FloatTensor | None = None + text_embeds: torch.FloatTensor | None = None + image_embeds: torch.FloatTensor | None = None + text_model_output: BaseModelOutputWithPooling = None + vision_model_output: BaseModelOutputWithPooling = None + + def to_tuple(self) -> tuple[Any]: + return tuple(v.to_tuple() if isinstance(v, ModelOutput) else v for v in self.values()) + + +class CLIPVisionEmbeddings(nn.Module): + def __init__(self, config: CLIPVisionConfig): + super().__init__() + self.config = config + self.embed_dim = config.hidden_size + self.image_size = config.image_size + self.patch_size = config.patch_size + + self.class_embedding = nn.Parameter(torch.randn(self.embed_dim)) + + self.patch_embedding = nn.Conv2d( + in_channels=config.num_channels, + out_channels=self.embed_dim, + kernel_size=self.patch_size, + stride=self.patch_size, + bias=False, + ) + + self.num_patches = (self.image_size // self.patch_size) ** 2 + self.num_positions = self.num_patches + 1 + self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim) + self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False) + + def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor: + """ + This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution + images. This method is also adapted to support torch.jit tracing. + + Adapted from: + - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and + - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211 + """ + + num_patches = embeddings.shape[1] - 1 + position_embedding = self.position_embedding.weight.unsqueeze(0) + num_positions = position_embedding.shape[1] - 1 + + # always interpolate when tracing to ensure the exported model works for dynamic input shapes + if not torch.jit.is_tracing() and num_patches == num_positions and height == width: + return self.position_embedding(self.position_ids) + + class_pos_embed = position_embedding[:, :1] + patch_pos_embed = position_embedding[:, 1:] + + dim = embeddings.shape[-1] + + new_height = height // self.patch_size + new_width = width // self.patch_size + + sqrt_num_positions = torch_int(num_positions**0.5) + patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim) + patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2) + + patch_pos_embed = nn.functional.interpolate( + patch_pos_embed, + size=(new_height, new_width), + mode="bicubic", + align_corners=False, + ) + + patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) + + return torch.cat((class_pos_embed, patch_pos_embed), dim=1) + + def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding=False) -> torch.Tensor: + batch_size, _, height, width = pixel_values.shape + if not interpolate_pos_encoding and (height != self.image_size or width != self.image_size): + raise ValueError( + f"Input image size ({height}*{width}) doesn't match model ({self.image_size}*{self.image_size})." + ) + target_dtype = self.patch_embedding.weight.dtype + patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid] + patch_embeds = patch_embeds.flatten(2).transpose(1, 2) + + class_embeds = self.class_embedding.expand(batch_size, 1, -1) + embeddings = torch.cat([class_embeds, patch_embeds], dim=1) + if interpolate_pos_encoding: + embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width) + else: + embeddings = embeddings + self.position_embedding(self.position_ids) + return embeddings + + +class CLIPTextEmbeddings(nn.Module): + def __init__(self, config: CLIPTextConfig): + super().__init__() + embed_dim = config.hidden_size + + self.token_embedding = nn.Embedding(config.vocab_size, embed_dim) + self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim) + + # position_ids (1, len position emb) is contiguous in memory and exported when serialized + self.register_buffer( + "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False + ) + + def forward( + self, + input_ids: torch.LongTensor | None = None, + position_ids: torch.LongTensor | None = None, + inputs_embeds: torch.FloatTensor | None = None, + ) -> torch.Tensor: + seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2] + max_position_embedding = self.position_embedding.weight.shape[0] + + if seq_length > max_position_embedding: + raise ValueError( + f"Sequence length must be less than max_position_embeddings (got `sequence length`: " + f"{seq_length} and max_position_embeddings: {max_position_embedding}" + ) + + if position_ids is None: + position_ids = self.position_ids[:, :seq_length] + + if inputs_embeds is None: + inputs_embeds = self.token_embedding(input_ids) + + position_embeddings = self.position_embedding(position_ids) + embeddings = inputs_embeds + position_embeddings + + return embeddings + + +def eager_attention_forward( + module: nn.Module, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attention_mask: torch.Tensor | None, + scaling: float, + dropout: float = 0.0, + **kwargs: Unpack[TransformersKwargs], +): + attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling + if attention_mask is not None: + attn_weights = attn_weights + attention_mask + attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) + attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training) + + attn_output = torch.matmul(attn_weights, value) + attn_output = attn_output.transpose(1, 2).contiguous() + return attn_output, attn_weights + + +class CLIPAttention(nn.Module): + """Multi-headed attention from 'Attention Is All You Need' paper""" + + def __init__(self, config: CLIPVisionConfig | CLIPTextConfig): + super().__init__() + self.config = config + self.embed_dim = config.hidden_size + self.num_heads = config.num_attention_heads + self.head_dim = self.embed_dim // self.num_heads + self.scale = self.head_dim**-0.5 + self.dropout = config.attention_dropout + self.is_causal = False + + self.k_proj = nn.Linear(self.embed_dim, self.embed_dim) + self.v_proj = nn.Linear(self.embed_dim, self.embed_dim) + self.q_proj = nn.Linear(self.embed_dim, self.embed_dim) + self.out_proj = nn.Linear(self.embed_dim, self.embed_dim) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: torch.Tensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple[torch.Tensor, torch.Tensor | None]: + """Input shape: Batch x Time x Channel""" + + input_shape = hidden_states.shape[:-1] + + hidden_shape = (*input_shape, -1, self.head_dim) + queries = self.q_proj(hidden_states) + keys = self.k_proj(hidden_states) + values = self.v_proj(hidden_states) + + queries = queries.view(hidden_shape).transpose(1, 2) + keys = keys.view(hidden_shape).transpose(1, 2) + values = values.view(hidden_shape).transpose(1, 2) + + attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( + self.config._attn_implementation, eager_attention_forward + ) + + attn_output, attn_weights = attention_interface( + self, + queries, + keys, + values, + attention_mask, + scaling=self.scale, + dropout=0.0 if not self.training else self.dropout, + **kwargs, + ) + + attn_output = attn_output.reshape(*input_shape, -1).contiguous() + attn_output = self.out_proj(attn_output) + + return attn_output, attn_weights + + +class CLIPMLP(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.activation_fn = ACT2FN[config.hidden_act] + self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size) + self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size) + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + hidden_states = self.fc1(hidden_states) + hidden_states = self.activation_fn(hidden_states) + hidden_states = self.fc2(hidden_states) + return hidden_states + + +class CLIPEncoderLayer(GradientCheckpointingLayer): + def __init__(self, config: CLIPVisionConfig | CLIPTextConfig): + super().__init__() + self.embed_dim = config.hidden_size + self.self_attn = CLIPAttention(config) + self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) + self.mlp = CLIPMLP(config) + self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: torch.Tensor, + **kwargs: Unpack[TransformersKwargs], + ) -> torch.FloatTensor: + residual = hidden_states + + hidden_states = self.layer_norm1(hidden_states) + hidden_states, _ = self.self_attn( + hidden_states=hidden_states, + attention_mask=attention_mask, + **kwargs, + ) + hidden_states = residual + hidden_states + + residual = hidden_states + hidden_states = self.layer_norm2(hidden_states) + hidden_states = self.mlp(hidden_states) + hidden_states = residual + hidden_states + + return hidden_states + + +@auto_docstring +class CLIPPreTrainedModel(PreTrainedModel): + config: CLIPConfig + base_model_prefix = "clip" + input_modalities = ("image", "text") + _no_split_modules = ["CLIPTextEmbeddings", "CLIPEncoderLayer", "CLIPVisionEmbeddings"] + + supports_gradient_checkpointing = True + _supports_sdpa = True + _supports_flash_attn = True + _supports_flex_attn = True + _supports_attention_backend = True + _can_record_outputs = { + "hidden_states": CLIPEncoderLayer, + "attentions": CLIPAttention, + } + + @torch.no_grad() + def _init_weights(self, module): + """Initialize the weights""" + factor = self.config.initializer_factor + if isinstance(module, CLIPTextEmbeddings): + init.normal_(module.token_embedding.weight, mean=0.0, std=factor * 0.02) + init.normal_(module.position_embedding.weight, mean=0.0, std=factor * 0.02) + init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1))) + elif isinstance(module, CLIPVisionEmbeddings): + init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor) + init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor) + init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor) + init.copy_(module.position_ids, torch.arange(module.num_positions).expand((1, -1))) + elif isinstance(module, CLIPAttention): + in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor + out_proj_std = (module.embed_dim**-0.5) * factor + init.normal_(module.q_proj.weight, std=in_proj_std) + init.normal_(module.k_proj.weight, std=in_proj_std) + init.normal_(module.v_proj.weight, std=in_proj_std) + init.normal_(module.out_proj.weight, std=out_proj_std) + elif isinstance(module, CLIPMLP): + in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor + fc_std = (2 * module.config.hidden_size) ** -0.5 * factor + init.normal_(module.fc1.weight, std=fc_std) + init.normal_(module.fc2.weight, std=in_proj_std) + elif isinstance(module, CLIPModel): + init.normal_( + module.text_projection.weight, + std=module.text_embed_dim**-0.5 * factor, + ) + init.normal_( + module.visual_projection.weight, + std=module.vision_embed_dim**-0.5 * factor, + ) + elif isinstance(module, CLIPVisionModelWithProjection): + init.normal_( + module.visual_projection.weight, + std=self.config.hidden_size**-0.5 * factor, + ) + elif isinstance(module, CLIPTextModelWithProjection): + init.normal_( + module.text_projection.weight, + std=self.config.hidden_size**-0.5 * factor, + ) + elif isinstance(module, CLIPForImageClassification): + init.normal_( + module.classifier.weight, + std=self.config.vision_config.hidden_size**-0.5 * factor, + ) + + if isinstance(module, nn.LayerNorm): + init.zeros_(module.bias) + init.ones_(module.weight) + if isinstance(module, nn.Linear) and module.bias is not None: + init.zeros_(module.bias) + + +class CLIPEncoder(nn.Module): + """ + Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a + [`CLIPEncoderLayer`]. + + Args: + config: CLIPConfig + """ + + def __init__(self, config: CLIPConfig): + super().__init__() + self.config = config + self.layers = nn.ModuleList([CLIPEncoderLayer(config) for _ in range(config.num_hidden_layers)]) + self.gradient_checkpointing = False + + def forward( + self, + inputs_embeds, + attention_mask: torch.Tensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> BaseModelOutput: + hidden_states = inputs_embeds + for encoder_layer in self.layers: + hidden_states = encoder_layer( + hidden_states, + attention_mask, + **kwargs, + ) + + return BaseModelOutput( + last_hidden_state=hidden_states, + ) + + +@auto_docstring( + custom_intro=""" + The text model from CLIP without any head or projection on top. + """ +) +class CLIPTextModel(CLIPPreTrainedModel): + config: CLIPTextConfig + input_modalities = ("text",) + _input_embed_layer = "token_embedding" + + def __init__(self, config: CLIPTextConfig): + super().__init__(config) + embed_dim = config.hidden_size + self.embeddings = CLIPTextEmbeddings(config) + self.encoder = CLIPEncoder(config) + self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps) + + # For `pooled_output` computation + self.eos_token_id = config.eos_token_id + self.post_init() + + @merge_with_config_defaults + @capture_outputs(tie_last_hidden_states=False) + @auto_docstring + def forward( + self, + input_ids: torch.Tensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.Tensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> BaseModelOutputWithPooling: + r""" + Examples: + + ```python + >>> from transformers import AutoTokenizer, CLIPTextModel + + >>> model = CLIPTextModel.from_pretrained("openai/clip-vit-base-patch32") + >>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32") + + >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt") + + >>> outputs = model(**inputs) + >>> last_hidden_state = outputs.last_hidden_state + >>> pooled_output = outputs.pooler_output # pooled (EOS token) states + ```""" + if input_ids is None: + raise ValueError("You have to specify input_ids") + + input_shape = input_ids.size() + input_ids = input_ids.view(-1, input_shape[-1]) + + hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids) + + attention_mask = create_causal_mask( + config=self.config, + inputs_embeds=hidden_states, + attention_mask=attention_mask, + past_key_values=None, + ) + + kwargs.pop("is_causal", None) + encoder_outputs: BaseModelOutput = self.encoder( + inputs_embeds=hidden_states, + attention_mask=attention_mask, + is_causal=True, + **kwargs, + ) + + last_hidden_state = encoder_outputs.last_hidden_state + last_hidden_state = self.final_layer_norm(last_hidden_state) + + if self.eos_token_id == 2: + # The `eos_token_id` was incorrect before PR #24773: Let's keep what have been done here. + # A CLIP model with such `eos_token_id` in the config can't work correctly with extra new tokens added + # ------------------------------------------------------------ + # text_embeds.shape = [batch_size, sequence_length, transformer.width] + # take features from the eot embedding (eot_token is the highest number in each sequence) + # casting to torch.int for onnx compatibility: argmax doesn't support int64 inputs with opset 14 + pooled_output = last_hidden_state[ + torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device), + input_ids.to(dtype=torch.int, device=last_hidden_state.device).argmax(dim=-1), + ] + else: + # The config gets updated `eos_token_id` from PR #24773 (so the use of extra new tokens is possible) + pooled_output = last_hidden_state[ + torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device), + # We need to get the first position of `eos_token_id` value (`pad_token_ids` might equal to `eos_token_id`) + # Note: we assume each sequence (along batch dim.) contains an `eos_token_id` (e.g. prepared by the tokenizer) + (input_ids.to(dtype=torch.int, device=last_hidden_state.device) == self.eos_token_id) + .int() + .argmax(dim=-1), + ] + + return BaseModelOutputWithPooling( + last_hidden_state=last_hidden_state, + pooler_output=pooled_output, + ) + + +@auto_docstring( + custom_intro=""" + The vision model from CLIP without any head or projection on top. + """ +) +class CLIPVisionModel(CLIPPreTrainedModel): + config: CLIPVisionConfig + main_input_name = "pixel_values" + input_modalities = ("image",) + _input_embed_layer = "patch_embedding" + + def __init__(self, config: CLIPVisionConfig): + super().__init__(config) + embed_dim = config.hidden_size + + self.embeddings = CLIPVisionEmbeddings(config) + self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps) + self.encoder = CLIPEncoder(config) + self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps) + self.post_init() + + @merge_with_config_defaults + @capture_outputs(tie_last_hidden_states=False) + @auto_docstring + def forward( + self, + pixel_values: torch.FloatTensor | None = None, + interpolate_pos_encoding: bool | None = False, + **kwargs: Unpack[TransformersKwargs], + ) -> BaseModelOutputWithPooling: + r""" + Example: + + ```python + >>> from PIL import Image + >>> import httpx + >>> from io import BytesIO + >>> from transformers import AutoProcessor, CLIPVisionModel + + >>> model = CLIPVisionModel.from_pretrained("openai/clip-vit-base-patch32") + >>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32") + + >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" + >>> with httpx.stream("GET", url) as response: + ... image = Image.open(BytesIO(response.read())) + + >>> inputs = processor(images=image, return_tensors="pt") + + >>> outputs = model(**inputs) + >>> last_hidden_state = outputs.last_hidden_state + >>> pooled_output = outputs.pooler_output # pooled CLS states + ```""" + hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding) + hidden_states = self.pre_layrnorm(hidden_states) + + encoder_outputs: BaseModelOutput = self.encoder( + inputs_embeds=hidden_states, + **kwargs, + ) + + last_hidden_state = encoder_outputs.last_hidden_state + pooled_output = last_hidden_state[:, 0, :] + pooled_output = self.post_layernorm(pooled_output) + + return BaseModelOutputWithPooling( + last_hidden_state=last_hidden_state, + pooler_output=pooled_output, + ) + + +@auto_docstring +class CLIPModel(CLIPPreTrainedModel): + def __init__(self, config: CLIPConfig): + super().__init__(config) + + text_config = config.text_config + vision_config = config.vision_config + + self.projection_dim = config.projection_dim + self.text_embed_dim = text_config.hidden_size + self.vision_embed_dim = vision_config.hidden_size + + self.text_model = CLIPTextModel._from_config(text_config) + self.vision_model = CLIPVisionModel._from_config(vision_config) + + self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False) + self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False) + self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value)) + + # Initialize weights and apply final processing + self.post_init() + + @can_return_tuple + @auto_docstring + def get_text_features( + self, + input_ids: torch.Tensor, + attention_mask: torch.Tensor | None = None, + position_ids: torch.Tensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | BaseModelOutputWithPooling: + r""" + Examples: + + ```python + >>> import torch + >>> from transformers import AutoTokenizer, CLIPModel + + >>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32") + >>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32") + + >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt") + + >>> with torch.inference_mode(): + ... text_features = model.get_text_features(**inputs) + ```""" + text_outputs: BaseModelOutputWithPooling = self.text_model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + return_dict=True, + **kwargs, + ) + pooled_output = text_outputs.pooler_output + text_outputs.pooler_output = self.text_projection(pooled_output) + + return text_outputs + + @can_return_tuple + @auto_docstring + def get_image_features( + self, + pixel_values: torch.FloatTensor, + interpolate_pos_encoding: bool = False, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | BaseModelOutputWithPooling: + r""" + Examples: + + ```python + >>> import torch + >>> from transformers import AutoProcessor, CLIPModel + >>> from transformers.image_utils import load_image + + >>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32") + >>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32") + + >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" + >>> image = load_image(url) + + >>> inputs = processor(images=image, return_tensors="pt") + + >>> with torch.inference_mode(): + ... image_features = model.get_image_features(**inputs) + ```""" + vision_outputs: BaseModelOutputWithPooling = self.vision_model( + pixel_values=pixel_values, + interpolate_pos_encoding=interpolate_pos_encoding, + return_dict=True, + **kwargs, + ) + pooled_output = vision_outputs.pooler_output + vision_outputs.pooler_output = self.visual_projection(pooled_output) + + return vision_outputs + + @can_return_tuple + @auto_docstring + def forward( + self, + input_ids: torch.LongTensor | None = None, + pixel_values: torch.FloatTensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.LongTensor | None = None, + return_loss: bool | None = None, + interpolate_pos_encoding: bool = False, + **kwargs: Unpack[TransformersKwargs], + ) -> CLIPOutput: + r""" + return_loss (`bool`, *optional*): + Whether or not to return the contrastive loss. + + Examples: + + ```python + >>> import torch + >>> from transformers import AutoProcessor, CLIPModel + >>> from transformers.image_utils import load_image + + >>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32") + >>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32") + + >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" + >>> image = load_image(url) + + >>> inputs = processor( + ... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True + ... ) + + >>> with torch.inference_mode(): + ... outputs = model(**inputs) + >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score + >>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities + ```""" + vision_outputs: BaseModelOutputWithPooling = self.get_image_features( + pixel_values=pixel_values, + interpolate_pos_encoding=interpolate_pos_encoding, + **kwargs, + ) + + text_outputs: BaseModelOutputWithPooling = self.get_text_features( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + **kwargs, + ) + + image_embeds = vision_outputs.pooler_output + text_embeds = text_outputs.pooler_output + + # normalized features + image_embeds = image_embeds / _get_vector_norm(image_embeds) + text_embeds = text_embeds / _get_vector_norm(text_embeds) + + # cosine similarity as logits + logits_per_text = torch.matmul(text_embeds, image_embeds.t().to(text_embeds.device)) + logits_per_text = logits_per_text * self.logit_scale.exp().to(text_embeds.device) + + logits_per_image = logits_per_text.t() + + loss = None + if return_loss: + loss = image_text_contrastive_loss(logits_per_text) + + return CLIPOutput( + loss=loss, + logits_per_image=logits_per_image, + logits_per_text=logits_per_text, + text_embeds=text_embeds, + image_embeds=image_embeds, + text_model_output=text_outputs, + vision_model_output=vision_outputs, + ) + + +@auto_docstring +class CLIPTextModelWithProjection(CLIPPreTrainedModel): + config: CLIPTextConfig + input_modalities = ("text",) + + def __init__(self, config: CLIPTextConfig): + super().__init__(config) + + self.text_model = CLIPTextModel._from_config(config) + self.text_projection = nn.Linear(config.hidden_size, config.projection_dim, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self) -> nn.Module: + return self.text_model.embeddings.token_embedding + + def set_input_embeddings(self, value): + self.text_model.embeddings.token_embedding = value + + @can_return_tuple + @auto_docstring + def forward( + self, + input_ids: torch.Tensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.Tensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> CLIPTextModelOutput: + r""" + Examples: + + ```python + >>> import torch + >>> from transformers import AutoTokenizer, CLIPTextModelWithProjection + + >>> model = CLIPTextModelWithProjection.from_pretrained("openai/clip-vit-base-patch32") + >>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32") + + >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt") + + >>> with torch.inference_mode(): + ... outputs = model(**inputs) + >>> text_embeds = outputs.text_embeds + ```""" + + text_outputs: BaseModelOutputWithPooling = self.text_model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + **kwargs, + ) + pooled_output = text_outputs.pooler_output + text_embeds = self.text_projection(pooled_output) + + return CLIPTextModelOutput( + text_embeds=text_embeds, + last_hidden_state=text_outputs.last_hidden_state, + hidden_states=text_outputs.hidden_states, + attentions=text_outputs.attentions, + ) + + +@auto_docstring +class CLIPVisionModelWithProjection(CLIPPreTrainedModel): + config: CLIPVisionConfig + main_input_name = "pixel_values" + input_modalities = ("image",) + + def __init__(self, config: CLIPVisionConfig): + super().__init__(config) + + self.vision_model = CLIPVisionModel._from_config(config) + self.visual_projection = nn.Linear(config.hidden_size, config.projection_dim, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self) -> nn.Module: + return self.vision_model.embeddings.patch_embedding + + @can_return_tuple + @auto_docstring + def forward( + self, + pixel_values: torch.FloatTensor | None = None, + interpolate_pos_encoding: bool = False, + **kwargs: Unpack[TransformersKwargs], + ) -> CLIPVisionModelOutput: + r""" + Examples: + + ```python + >>> import torch + >>> from transformers import AutoProcessor, CLIPVisionModelWithProjection + >>> from transformers.image_utils import load_image + + >>> model = CLIPVisionModelWithProjection.from_pretrained("openai/clip-vit-base-patch32") + >>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32") + + >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" + >>> image = load_image(url) + + >>> inputs = processor(images=image, return_tensors="pt") + + >>> with torch.inference_mode(): + ... outputs = model(**inputs) + >>> image_embeds = outputs.image_embeds + ```""" + + vision_outputs: BaseModelOutputWithPooling = self.vision_model( + pixel_values=pixel_values, + interpolate_pos_encoding=interpolate_pos_encoding, + **kwargs, + ) + pooled_output = vision_outputs.pooler_output + image_embeds = self.visual_projection(pooled_output) + + return CLIPVisionModelOutput( + image_embeds=image_embeds, + last_hidden_state=vision_outputs.last_hidden_state, + hidden_states=vision_outputs.hidden_states, + attentions=vision_outputs.attentions, + ) + + +@auto_docstring( + custom_intro=""" + CLIP vision encoder with an image classification head on top (a linear layer on top of the pooled final hidden states of + the patch tokens) e.g. for ImageNet. + """ +) +class CLIPForImageClassification(CLIPPreTrainedModel): + main_input_name = "pixel_values" + input_modalities = ("image",) + + def __init__(self, config: CLIPConfig) -> None: + super().__init__(config) + + self.num_labels = config.num_labels + self.vision_model = CLIPVisionModel._from_config(config.vision_config) + + # Classifier head + self.classifier = ( + nn.Linear(config.vision_config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity() + ) + + # Initialize weights and apply final processing + self.post_init() + + @can_return_tuple + @auto_docstring + def forward( + self, + pixel_values: torch.Tensor | None = None, + labels: torch.Tensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> ImageClassifierOutput: + r""" + labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for computing the image classification/regression loss. Indices should be in `[0, ..., + config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If + `config.num_labels > 1` a classification loss is computed (Cross-Entropy). + """ + outputs: BaseModelOutputWithPooling = self.vision_model( + pixel_values, + **kwargs, + ) + + sequence_output = outputs.last_hidden_state + + sequence_output = torch.mean(sequence_output[:, 1:, :], dim=1) + logits = self.classifier(sequence_output) + + loss = None + if labels is not None: + loss = self.loss_function(labels, logits, self.config) + + return ImageClassifierOutput( + loss=loss, + logits=logits, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +__all__ = [ + "CLIPModel", + "CLIPPreTrainedModel", + "CLIPTextModel", + "CLIPTextModelWithProjection", + "CLIPVisionModel", + "CLIPVisionModelWithProjection", + "CLIPForImageClassification", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/processing_clip.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/processing_clip.py new file mode 100644 index 0000000000000000000000000000000000000000..f69b275c48b248f1e35419ba4f174f5a75d04f21 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/processing_clip.py @@ -0,0 +1,28 @@ +# Copyright 2021 The HuggingFace Inc. team. +# +# 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. +""" +Image/Text processor class for CLIP +""" + +from ...processing_utils import ProcessorMixin +from ...utils import auto_docstring + + +@auto_docstring +class CLIPProcessor(ProcessorMixin): + def __init__(self, image_processor=None, tokenizer=None, **kwargs): + super().__init__(image_processor, tokenizer) + + +__all__ = ["CLIPProcessor"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/tokenization_clip.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/tokenization_clip.py new file mode 100644 index 0000000000000000000000000000000000000000..018c630afbce1cc439477a94779044a2e724a7c5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/tokenization_clip.py @@ -0,0 +1,142 @@ +# Copyright 2021 The Open AI Team Authors and The HuggingFace Inc. team. +# +# 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. +"""Tokenization classes for CLIP.""" + +from tokenizers import Regex, Tokenizer, decoders, normalizers, pre_tokenizers, processors +from tokenizers.models import BPE + +from ...tokenization_utils_tokenizers import TokenizersBackend +from ...utils import logging + + +logger = logging.get_logger(__name__) + +VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} + + +class CLIPTokenizer(TokenizersBackend): + """ + Construct a CLIP tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level + Byte-Pair-Encoding. + + This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should + refer to this superclass for more information regarding those methods. + + Args: + vocab (`str`, `dict` or `list`, *optional*): + Vocabulary dict to use for the tokenizer. + merges (`str` or `list`, *optional*): + Merges list to use for the BPE tokenizer. + unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`): + The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this + token instead. + bos_token (`str`, *optional*, defaults to `"<|startoftext|>"`): + The beginning of sequence token. + eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`): + The end of sequence token. + pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`): + The token used for padding, for example when batching sequences of different lengths. + """ + + vocab_files_names = VOCAB_FILES_NAMES + model_input_names = ["input_ids", "attention_mask"] + model = BPE + + def __init__( + self, + vocab: str | dict[str, int] | None = None, + merges: str | list[str] | None = None, + unk_token: str = "<|endoftext|>", + bos_token: str = "<|startoftext|>", + eos_token: str = "<|endoftext|>", + pad_token: str = "<|endoftext|>", + **kwargs, + ): + _vocab = ( + vocab + if vocab is not None + else { + str(bos_token): 0, + str(eos_token): 1, + str(pad_token): 2, + } + ) + + self._merges = merges or [] + + self._tokenizer = Tokenizer( + BPE( + vocab=_vocab, + merges=self._merges, + dropout=None, + continuing_subword_prefix="", + end_of_word_suffix="", + fuse_unk=False, + unk_token=str(unk_token), + ) + ) + + self._tokenizer.normalizer = normalizers.Sequence( + [normalizers.NFC(), normalizers.Replace(Regex(r"\s+"), " "), normalizers.Lowercase()] + ) + + self._tokenizer.pre_tokenizer = pre_tokenizers.Sequence( + [ + pre_tokenizers.Split( + Regex( + r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""" + ), + behavior="removed", + invert=True, + ), + pre_tokenizers.ByteLevel(add_prefix_space=False), + ] + ) + + self._tokenizer.decoder = decoders.ByteLevel() + + super().__init__( + unk_token=unk_token, + bos_token=bos_token, + eos_token=eos_token, + pad_token=pad_token, + **kwargs, + ) + + self._tokenizer.post_processor = processors.RobertaProcessing( + sep=(str(eos_token), self.eos_token_id), + cls=(str(bos_token), self.bos_token_id), + add_prefix_space=False, + trim_offsets=False, + ) + + # Very ugly hack to enable padding to have a correct decoding see https://github.com/huggingface/tokenizers/issues/872 + self._wrap_decode_method_backend_tokenizer() + + def _wrap_decode_method_backend_tokenizer(self): + orig_decode_method = self.backend_tokenizer.decode + + ## define this as a local variable to avoid circular reference + ## See: https://github.com/huggingface/transformers/issues/30930 + end_of_word_suffix = self.backend_tokenizer.model.end_of_word_suffix + + def new_decode_method(*args, **kwargs): + text = orig_decode_method(*args, **kwargs) + text = text.replace(end_of_word_suffix, " ").strip() + return text + + self.backend_tokenizer.decode = new_decode_method + + +__all__ = ["CLIPTokenizer"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..55b38987fd0a3e443b8ae94ffbdd6f73c79ba619 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/__init__.py @@ -0,0 +1,28 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# 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. +from typing import TYPE_CHECKING + +from ...utils import _LazyModule +from ...utils.import_utils import define_import_structure + + +if TYPE_CHECKING: + from .configuration_clipseg import * + from .modeling_clipseg import * + from .processing_clipseg import * +else: + import sys + + _file = globals()["__file__"] + sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/configuration_clipseg.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/configuration_clipseg.py new file mode 100644 index 0000000000000000000000000000000000000000..8964ab511d1091f6a18118fba31485c2ab2a403f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/configuration_clipseg.py @@ -0,0 +1,262 @@ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from src/transformers/models/clipseg/modular_clipseg.py. +# Do NOT edit this file manually as any edits will be overwritten by the generation of +# the file from the modular. If any change should be done, please apply the change to the +# modular_clipseg.py file directly. One of our CI enforces this. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# Copyright 2022 The OpenAI Team Authors and The HuggingFace Team. All rights reserved. +# +# 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. +from huggingface_hub.dataclasses import strict + +from ...configuration_utils import PreTrainedConfig +from ...utils import auto_docstring, logging + + +logger = logging.get_logger(__name__) + + +@auto_docstring(checkpoint="CIDAS/clipseg-rd64") +@strict +class CLIPSegTextConfig(PreTrainedConfig): + r""" + Example: + + ```python + >>> from transformers import CLIPSegTextConfig, CLIPSegTextModel + + >>> # Initializing a CLIPSegTextConfig with CIDAS/clipseg-rd64 style configuration + >>> configuration = CLIPSegTextConfig() + + >>> # Initializing a CLIPSegTextModel (with random weights) from the CIDAS/clipseg-rd64 style configuration + >>> model = CLIPSegTextModel(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + model_type = "clipseg_text_model" + base_config_key = "text_config" + + vocab_size: int = 49408 + hidden_size: int = 512 + intermediate_size: int = 2048 + num_hidden_layers: int = 12 + num_attention_heads: int = 8 + max_position_embeddings: int = 77 + hidden_act: str = "quick_gelu" + layer_norm_eps: float | None = 1e-5 + attention_dropout: int | float | None = 0.0 + initializer_range: float = 0.02 + initializer_factor: float | None = 1.0 + + # This differs from `CLIPSegTokenizer`'s default and from openai/clipseg + # See https://github.com/huggingface/transformers/pull/24773#issuecomment-1632287538 + pad_token_id: int | None = 1 + bos_token_id: int | None = 49406 + eos_token_id: int | list[int] | None = 49407 + + def validate_architecture(self): + """Part of `@strict`-powered validation. Validates the architecture of the config.""" + if self.hidden_size % self.num_attention_heads != 0: + raise ValueError( + f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention " + f"heads ({self.num_attention_heads})." + ) + + +@auto_docstring(checkpoint="CIDAS/clipseg-rd64") +@strict +class CLIPSegVisionConfig(PreTrainedConfig): + r""" + Example: + + ```python + >>> from transformers import CLIPSegVisionConfig, CLIPSegVisionModel + + >>> # Initializing a CLIPSegVisionConfig with CIDAS/clipseg-rd64 style configuration + >>> configuration = CLIPSegVisionConfig() + + >>> # Initializing a CLIPSegVisionModel (with random weights) from the CIDAS/clipseg-rd64 style configuration + >>> model = CLIPSegVisionModel(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + model_type = "clipseg_vision_model" + base_config_key = "vision_config" + + hidden_size: int = 768 + intermediate_size: int = 3072 + num_hidden_layers: int = 12 + num_attention_heads: int = 12 + num_channels: int = 3 + image_size: int | list[int] | tuple[int, int] | None = 224 + patch_size: int | list[int] | tuple[int, int] | None = 32 + hidden_act: str = "quick_gelu" + layer_norm_eps: float = 1e-5 + attention_dropout: int | float | None = 0.0 + initializer_range: float = 0.02 + initializer_factor: float = 1.0 + + def validate_architecture(self): + """Part of `@strict`-powered validation. Validates the architecture of the config.""" + if self.hidden_size % self.num_attention_heads != 0: + raise ValueError( + f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention " + f"heads ({self.num_attention_heads})." + ) + + +@auto_docstring(checkpoint="CIDAS/clipseg-rd64") +@strict +class CLIPSegConfig(PreTrainedConfig): + r""" + extract_layers (`list[int]`, *optional*, defaults to `[3, 6, 9]`): + Layers to extract when forwarding the query image through the frozen visual backbone of CLIP. + reduce_dim (`int`, *optional*, defaults to 64): + Dimensionality to reduce the CLIP vision embedding. + conditional_layer (`int`, *optional*, defaults to 0): + The layer to use of the Transformer encoder whose activations will be combined with the condition + embeddings using FiLM (Feature-wise Linear Modulation). If 0, the last layer is used. + use_complex_transposed_convolution (`bool`, *optional*, defaults to `False`): + Whether to use a more complex transposed convolution in the decoder, enabling more fine-grained + segmentation.. + + Example: + + ```python + >>> from transformers import CLIPSegConfig, CLIPSegModel + + >>> # Initializing a CLIPSegConfig with CIDAS/clipseg-rd64 style configuration + >>> configuration = CLIPSegConfig() + + >>> # Initializing a CLIPSegModel (with random weights) from the CIDAS/clipseg-rd64 style configuration + >>> model = CLIPSegModel(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + + >>> # We can also initialize a CLIPSegConfig from a CLIPSegTextConfig and a CLIPSegVisionConfig + + >>> # Initializing a CLIPSegText and CLIPSegVision configuration + >>> config_text = CLIPSegTextConfig() + >>> config_vision = CLIPSegVisionConfig() + + >>> config = CLIPSegConfig(text_config=config_text, vision_config=config_vision) + ```""" + + model_type = "clipseg" + sub_configs = {"text_config": CLIPSegTextConfig, "vision_config": CLIPSegVisionConfig} + + text_config: dict | CLIPSegTextConfig | None = None + vision_config: dict | CLIPSegVisionConfig | None = None + projection_dim: int | None = 512 + logit_scale_init_value: float | int | None = 2.6592 + initializer_factor: float | None = 1.0 + + extract_layers: list[int] | tuple[int, ...] = (3, 6, 9) + reduce_dim: int = 64 + decoder_num_attention_heads: int = 4 + decoder_attention_dropout: float | int = 0.0 + decoder_hidden_act: str = "quick_gelu" + decoder_intermediate_size: int = 2048 + conditional_layer: int = 0 + use_complex_transposed_convolution: bool = False + + def __post_init__(self, **kwargs): + if self.text_config is None: + text_config = {} + logger.info("`text_config` is `None`. Initializing the `CLIPSegTextConfig` with default values.") + elif isinstance(self.text_config, CLIPSegTextConfig): + text_config = self.text_config.to_dict() + else: + text_config = self.text_config + + if self.vision_config is None: + vision_config = {} + logger.info("`vision_config` is `None`. initializing the `CLIPSegVisionConfig` with default values.") + elif isinstance(self.vision_config, CLIPSegVisionConfig): + vision_config = self.vision_config.to_dict() + else: + vision_config = self.vision_config + + # For backward compatibility check keyword args + # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in + # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most + # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`. + text_config_dict = kwargs.pop("text_config_dict", None) + vision_config_dict = kwargs.pop("vision_config_dict", None) + + if text_config_dict is not None: + # This is the complete result when using `text_config_dict`. + _text_config_dict = CLIPSegTextConfig(**text_config_dict).to_dict() + + # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different. + for key, value in _text_config_dict.items(): + if key in text_config and value != text_config[key] and key != "transformers_version": + # If specified in `text_config_dict` + if key in text_config_dict: + message = ( + f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. " + f'The value `text_config_dict["{key}"]` will be used instead.' + ) + # If inferred from default argument values (just to be super careful) + else: + message = ( + f"`text_config_dict` is provided which will be used to initialize `CLIPTextConfig`. The " + f'value `text_config["{key}"]` will be overridden.' + ) + logger.info(message) + + # Update all values in `text_config` with the ones in `_text_config_dict`. + text_config.update(_text_config_dict) + + if vision_config_dict is not None: + # This is the complete result when using `vision_config_dict`. + _vision_config_dict = CLIPSegVisionConfig(**vision_config_dict).to_dict() + # convert keys to string instead of integer + if "id2label" in _vision_config_dict: + _vision_config_dict["id2label"] = { + str(key): value for key, value in _vision_config_dict["id2label"].items() + } + + # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different. + for key, value in _vision_config_dict.items(): + if key in vision_config and value != vision_config[key] and key != "transformers_version": + # If specified in `vision_config_dict` + if key in vision_config_dict: + message = ( + f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different " + f'values. The value `vision_config_dict["{key}"]` will be used instead.' + ) + # If inferred from default argument values (just to be super careful) + else: + message = ( + f"`vision_config_dict` is provided which will be used to initialize `CLIPVisionConfig`. " + f'The value `vision_config["{key}"]` will be overridden.' + ) + logger.info(message) + + # Update all values in `vision_config` with the ones in `_vision_config_dict`. + vision_config.update(_vision_config_dict) + + # Finally we can convert back our unified text/vision configs to `PretrainedConfig` + self.text_config = CLIPSegTextConfig(**text_config) + self.vision_config = CLIPSegVisionConfig(**vision_config) + + super().__post_init__(**kwargs) + + +__all__ = ["CLIPSegConfig", "CLIPSegTextConfig", "CLIPSegVisionConfig"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/modeling_clipseg.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/modeling_clipseg.py new file mode 100644 index 0000000000000000000000000000000000000000..cf17b44b00c20cd687a5dac2462930fa8d312104 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/modeling_clipseg.py @@ -0,0 +1,1128 @@ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from src/transformers/models/clipseg/modular_clipseg.py. +# Do NOT edit this file manually as any edits will be overwritten by the generation of +# the file from the modular. If any change should be done, please apply the change to the +# modular_clipseg.py file directly. One of our CI enforces this. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# Copyright 2022 The OpenAI Team Authors and The HuggingFace Team. All rights reserved. +# +# 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. + +import copy +import math +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any + +import torch +from torch import nn + +from ... import initialization as init +from ...activations import ACT2FN +from ...masking_utils import create_causal_mask +from ...modeling_layers import GradientCheckpointingLayer +from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling +from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel +from ...processing_utils import Unpack +from ...utils import ModelOutput, TransformersKwargs, auto_docstring, torch_int +from ...utils.generic import can_return_tuple, merge_with_config_defaults +from ...utils.output_capturing import capture_outputs +from .configuration_clipseg import CLIPSegConfig, CLIPSegTextConfig, CLIPSegVisionConfig + + +@dataclass +@auto_docstring +class CLIPSegOutput(ModelOutput): + r""" + loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`): + Contrastive loss for image-text similarity. + logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`): + The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text + similarity scores. + logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`): + The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image + similarity scores. + text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`): + The text embeddings obtained by applying the projection layer to the pooled output of [`CLIPSegTextModel`]. + image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`): + The image embeddings obtained by applying the projection layer to the pooled output of [`CLIPSegVisionModel`]. + text_model_output (`BaseModelOutputWithPooling`): + The output of the [`CLIPSegTextModel`]. + vision_model_output (`BaseModelOutputWithPooling`): + The output of the [`CLIPSegVisionModel`]. + """ + + loss: torch.FloatTensor | None = None + logits_per_image: torch.FloatTensor | None = None + logits_per_text: torch.FloatTensor | None = None + text_embeds: torch.FloatTensor | None = None + image_embeds: torch.FloatTensor | None = None + text_model_output: BaseModelOutputWithPooling = None + vision_model_output: BaseModelOutputWithPooling = None + + def to_tuple(self) -> tuple[Any]: + return tuple(v.to_tuple() if isinstance(v, ModelOutput) else v for v in self.values()) + + +@dataclass +@auto_docstring +class CLIPSegDecoderOutput(ModelOutput): + r""" + logits (`torch.FloatTensor` of shape `(batch_size, height, width)`): + Classification scores for each pixel. + hidden_states (`tuple(torch.FloatTensor)`, *optional*,): + Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. + Rreturned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True` + attentions (`tuple(torch.FloatTensor)`, *optional*): + Attentions weights after the attention softmax, used to compute the weighted average in the self-attention + heads. Returned when `output_attentions=True` is passed or when `config.output_attentions=True` + """ + + logits: torch.FloatTensor | None = None + hidden_states: tuple[torch.FloatTensor, ...] | None = None + attentions: tuple[torch.FloatTensor, ...] | None = None + + +@dataclass +@auto_docstring +class CLIPSegImageSegmentationOutput(ModelOutput): + r""" + loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): + Binary cross entropy loss for segmentation. + logits (`torch.FloatTensor` of shape `(batch_size, height, width)`): + Classification scores for each pixel. + conditional_embeddings (`torch.FloatTensor` of shape `(batch_size, projection_dim)`): + Conditional embeddings used for segmentation. + pooled_output (`torch.FloatTensor` of shape `(batch_size, embed_dim)`): + Pooled output of the [`CLIPSegVisionModel`]. + vision_model_output (`BaseModelOutputWithPooling`): + The output of the [`CLIPSegVisionModel`]. + decoder_output (`CLIPSegDecoderOutput`): + The output of the [`CLIPSegDecoder`]. + """ + + loss: torch.FloatTensor | None = None + logits: torch.FloatTensor | None = None + conditional_embeddings: torch.FloatTensor | None = None + pooled_output: torch.FloatTensor | None = None + vision_model_output: BaseModelOutputWithPooling = None + decoder_output: CLIPSegDecoderOutput = None + + def to_tuple(self) -> tuple[Any]: + return tuple(v.to_tuple() if isinstance(v, ModelOutput) else v for v in self.values()) + + +class CLIPSegVisionEmbeddings(nn.Module): + def __init__(self, config: CLIPSegVisionConfig): + super().__init__() + self.config = config + self.embed_dim = config.hidden_size + self.image_size = config.image_size + self.patch_size = config.patch_size + + self.class_embedding = nn.Parameter(torch.randn(self.embed_dim)) + + self.patch_embedding = nn.Conv2d( + in_channels=config.num_channels, + out_channels=self.embed_dim, + kernel_size=self.patch_size, + stride=self.patch_size, + bias=False, + ) + + self.num_patches = (self.image_size // self.patch_size) ** 2 + self.num_positions = self.num_patches + 1 + self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim) + self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False) + + def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor: + """ + This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution + images. This method is also adapted to support torch.jit tracing. + + Adapted from: + - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and + - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211 + """ + + num_patches = embeddings.shape[1] - 1 + position_embedding = self.position_embedding.weight.unsqueeze(0) + num_positions = position_embedding.shape[1] - 1 + + # always interpolate when tracing to ensure the exported model works for dynamic input shapes + if not torch.jit.is_tracing() and num_patches == num_positions and height == width: + return self.position_embedding(self.position_ids) + + class_pos_embed = position_embedding[:, :1] + patch_pos_embed = position_embedding[:, 1:] + + dim = embeddings.shape[-1] + + new_height = height // self.patch_size + new_width = width // self.patch_size + + sqrt_num_positions = torch_int(num_positions**0.5) + patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim) + patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2) + + patch_pos_embed = nn.functional.interpolate( + patch_pos_embed, + size=(new_height, new_width), + mode="bicubic", + align_corners=False, + ) + + patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) + + return torch.cat((class_pos_embed, patch_pos_embed), dim=1) + + def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding=True) -> torch.Tensor: + batch_size, _, height, width = pixel_values.shape + if not interpolate_pos_encoding and (height != self.image_size or width != self.image_size): + raise ValueError( + f"Input image size ({height}*{width}) doesn't match model ({self.image_size}*{self.image_size})." + ) + target_dtype = self.patch_embedding.weight.dtype + patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid] + patch_embeds = patch_embeds.flatten(2).transpose(1, 2) + + class_embeds = self.class_embedding.expand(batch_size, 1, -1) + embeddings = torch.cat([class_embeds, patch_embeds], dim=1) + if interpolate_pos_encoding: + embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width) + else: + embeddings = embeddings + self.position_embedding(self.position_ids) + return embeddings + + +class CLIPSegTextEmbeddings(nn.Module): + def __init__(self, config: CLIPSegTextConfig): + super().__init__() + embed_dim = config.hidden_size + + self.token_embedding = nn.Embedding(config.vocab_size, embed_dim) + self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim) + + # position_ids (1, len position emb) is contiguous in memory and exported when serialized + self.register_buffer( + "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False + ) + + def forward( + self, + input_ids: torch.LongTensor | None = None, + position_ids: torch.LongTensor | None = None, + inputs_embeds: torch.FloatTensor | None = None, + ) -> torch.Tensor: + seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2] + max_position_embedding = self.position_embedding.weight.shape[0] + + if seq_length > max_position_embedding: + raise ValueError( + f"Sequence length must be less than max_position_embeddings (got `sequence length`: " + f"{seq_length} and max_position_embeddings: {max_position_embedding}" + ) + + if position_ids is None: + position_ids = self.position_ids[:, :seq_length] + + if inputs_embeds is None: + inputs_embeds = self.token_embedding(input_ids) + + position_embeddings = self.position_embedding(position_ids) + embeddings = inputs_embeds + position_embeddings + + return embeddings + + +def eager_attention_forward( + module: nn.Module, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attention_mask: torch.Tensor | None, + scaling: float, + dropout: float = 0.0, + **kwargs: Unpack[TransformersKwargs], +): + attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling + if attention_mask is not None: + attn_weights = attn_weights + attention_mask + attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) + attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training) + + attn_output = torch.matmul(attn_weights, value) + attn_output = attn_output.transpose(1, 2).contiguous() + return attn_output, attn_weights + + +class CLIPSegAttention(nn.Module): + """Multi-headed attention from 'Attention Is All You Need' paper""" + + def __init__(self, config: CLIPSegVisionConfig | CLIPSegTextConfig): + super().__init__() + self.config = config + self.embed_dim = config.hidden_size + self.num_heads = config.num_attention_heads + self.head_dim = self.embed_dim // self.num_heads + self.scale = self.head_dim**-0.5 + self.dropout = config.attention_dropout + self.is_causal = False + + self.k_proj = nn.Linear(self.embed_dim, self.embed_dim) + self.v_proj = nn.Linear(self.embed_dim, self.embed_dim) + self.q_proj = nn.Linear(self.embed_dim, self.embed_dim) + self.out_proj = nn.Linear(self.embed_dim, self.embed_dim) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: torch.Tensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple[torch.Tensor, torch.Tensor | None]: + """Input shape: Batch x Time x Channel""" + + input_shape = hidden_states.shape[:-1] + + hidden_shape = (*input_shape, -1, self.head_dim) + queries = self.q_proj(hidden_states) + keys = self.k_proj(hidden_states) + values = self.v_proj(hidden_states) + + queries = queries.view(hidden_shape).transpose(1, 2) + keys = keys.view(hidden_shape).transpose(1, 2) + values = values.view(hidden_shape).transpose(1, 2) + + attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( + self.config._attn_implementation, eager_attention_forward + ) + + attn_output, attn_weights = attention_interface( + self, + queries, + keys, + values, + attention_mask, + scaling=self.scale, + dropout=0.0 if not self.training else self.dropout, + **kwargs, + ) + + attn_output = attn_output.reshape(*input_shape, -1).contiguous() + attn_output = self.out_proj(attn_output) + + return attn_output, attn_weights + + +class CLIPSegMLP(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.activation_fn = ACT2FN[config.hidden_act] + self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size) + self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size) + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + hidden_states = self.fc1(hidden_states) + hidden_states = self.activation_fn(hidden_states) + hidden_states = self.fc2(hidden_states) + return hidden_states + + +class CLIPSegEncoderLayer(GradientCheckpointingLayer): + def __init__(self, config: CLIPSegVisionConfig | CLIPSegTextConfig): + super().__init__() + self.embed_dim = config.hidden_size + self.self_attn = CLIPSegAttention(config) + self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) + self.mlp = CLIPSegMLP(config) + self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: torch.Tensor, + **kwargs: Unpack[TransformersKwargs], + ) -> torch.FloatTensor: + residual = hidden_states + + hidden_states = self.layer_norm1(hidden_states) + hidden_states, _ = self.self_attn( + hidden_states=hidden_states, + attention_mask=attention_mask, + **kwargs, + ) + hidden_states = residual + hidden_states + + residual = hidden_states + hidden_states = self.layer_norm2(hidden_states) + hidden_states = self.mlp(hidden_states) + hidden_states = residual + hidden_states + + return hidden_states + + +class CLIPSegDecoderLayer(GradientCheckpointingLayer): + """ + CLIPSeg decoder layer, which is identical to `CLIPSegEncoderLayer`, except that normalization is applied after + self-attention/MLP, rather than before. + """ + + def __init__(self, config: CLIPSegVisionConfig | CLIPSegTextConfig): + super().__init__() + self.embed_dim = config.hidden_size + self.self_attn = CLIPSegAttention(config) + self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) + self.mlp = CLIPSegMLP(config) + self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: torch.Tensor, + **kwargs, + ) -> tuple[torch.FloatTensor]: + residual = hidden_states + + hidden_states, _ = self.self_attn( + hidden_states=hidden_states, + attention_mask=attention_mask, + **kwargs, + ) + + hidden_states = residual + hidden_states + hidden_states = self.layer_norm1(hidden_states) + + residual = hidden_states + hidden_states = self.mlp(hidden_states) + hidden_states = residual + hidden_states + hidden_states = self.layer_norm2(hidden_states) + + return hidden_states + + +@auto_docstring +class CLIPSegPreTrainedModel(PreTrainedModel): + config: CLIPSegConfig + base_model_prefix = "clipseg" + input_modalities = ("image", "text") + _no_split_modules = ["CLIPSegTextEmbeddings", "CLIPSegEncoderLayer", "CLIPSegVisionEmbeddings"] + + supports_gradient_checkpointing = True + _supports_sdpa = True + _supports_flash_attn = True + _supports_flex_attn = True + _supports_attention_backend = True + _can_record_outputs = { + "hidden_states": [CLIPSegEncoderLayer, CLIPSegDecoderLayer], + "attentions": CLIPSegAttention, + } + + @torch.no_grad() + def _init_weights(self, module): + """Initialize the weights""" + factor = self.config.initializer_factor + if isinstance(module, CLIPSegTextEmbeddings): + init.normal_(module.token_embedding.weight, mean=0.0, std=factor * 0.02) + init.normal_(module.position_embedding.weight, mean=0.0, std=factor * 0.02) + init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1))) + elif isinstance(module, CLIPSegVisionEmbeddings): + init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor) + init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor) + init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor) + init.copy_(module.position_ids, torch.arange(module.num_positions).expand((1, -1))) + elif isinstance(module, CLIPSegAttention): + in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor + out_proj_std = (module.embed_dim**-0.5) * factor + init.normal_(module.q_proj.weight, std=in_proj_std) + init.normal_(module.k_proj.weight, std=in_proj_std) + init.normal_(module.v_proj.weight, std=in_proj_std) + init.normal_(module.out_proj.weight, std=out_proj_std) + elif isinstance(module, CLIPSegMLP): + in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor + fc_std = (2 * module.config.hidden_size) ** -0.5 * factor + init.normal_(module.fc1.weight, std=fc_std) + init.normal_(module.fc2.weight, std=in_proj_std) + elif isinstance(module, CLIPSegModel): + init.normal_( + module.text_projection.weight, + std=module.text_embed_dim**-0.5 * factor, + ) + init.normal_( + module.visual_projection.weight, + std=module.vision_embed_dim**-0.5 * factor, + ) + + if isinstance(module, nn.LayerNorm): + init.zeros_(module.bias) + init.ones_(module.weight) + if isinstance(module, nn.Linear) and module.bias is not None: + init.zeros_(module.bias) + + +class CLIPSegEncoder(nn.Module): + """ + Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a + [`CLIPSegEncoderLayer`]. + + Args: + config: CLIPSegConfig + """ + + def __init__(self, config: CLIPSegConfig): + super().__init__() + self.config = config + self.layers = nn.ModuleList([CLIPSegEncoderLayer(config) for _ in range(config.num_hidden_layers)]) + self.gradient_checkpointing = False + + def forward( + self, + inputs_embeds, + attention_mask: torch.Tensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> BaseModelOutput: + hidden_states = inputs_embeds + for encoder_layer in self.layers: + hidden_states = encoder_layer( + hidden_states, + attention_mask, + **kwargs, + ) + + return BaseModelOutput( + last_hidden_state=hidden_states, + ) + + +class CLIPSegDecoder(CLIPSegPreTrainedModel): + def __init__(self, config: CLIPSegConfig): + super().__init__(config) + + self.conditional_layer = config.conditional_layer + + self.film_mul = nn.Linear(config.projection_dim, config.reduce_dim) + self.film_add = nn.Linear(config.projection_dim, config.reduce_dim) + + if config.use_complex_transposed_convolution: + transposed_kernels = (config.vision_config.patch_size // 4, config.vision_config.patch_size // 4) + + self.transposed_convolution = nn.Sequential( + nn.Conv2d(config.reduce_dim, config.reduce_dim, kernel_size=3, padding=1), + nn.ReLU(), + nn.ConvTranspose2d( + config.reduce_dim, + config.reduce_dim // 2, + kernel_size=transposed_kernels[0], + stride=transposed_kernels[0], + ), + nn.ReLU(), + nn.ConvTranspose2d( + config.reduce_dim // 2, 1, kernel_size=transposed_kernels[1], stride=transposed_kernels[1] + ), + ) + else: + self.transposed_convolution = nn.ConvTranspose2d( + config.reduce_dim, 1, config.vision_config.patch_size, stride=config.vision_config.patch_size + ) + + depth = len(config.extract_layers) + self.reduces = nn.ModuleList( + [nn.Linear(config.vision_config.hidden_size, config.reduce_dim) for _ in range(depth)] + ) + + decoder_config = copy.deepcopy(config.vision_config) + decoder_config.hidden_size = config.reduce_dim + decoder_config.num_attention_heads = config.decoder_num_attention_heads + decoder_config.intermediate_size = config.decoder_intermediate_size + decoder_config.hidden_act = "relu" + self.layers = nn.ModuleList([CLIPSegDecoderLayer(decoder_config) for _ in range(len(config.extract_layers))]) + + self.post_init() + + @merge_with_config_defaults + @capture_outputs + @auto_docstring + def forward( + self, + hidden_states: tuple[torch.Tensor], + conditional_embeddings: torch.Tensor, + **kwargs: Unpack[TransformersKwargs], + ) -> CLIPSegDecoderOutput: + r""" + conditional_embeddings (`torch.FloatTensor` of shape `(batch_size, config.projection_dim)`, *optional*): + The conditional embeddings for the query images. If provided, the model will use this instead of computing + the embeddings from the conditional_pixel_values. + """ + activations = hidden_states[::-1] + + output = None + for i, (activation, layer, reduce) in enumerate(zip(activations, self.layers, self.reduces)): + if output is not None: + output = reduce(activation) + output + else: + output = reduce(activation) + + if i == self.conditional_layer: + output = self.film_mul(conditional_embeddings) * output.permute(1, 0, 2) + self.film_add( + conditional_embeddings + ) + output = output.permute(1, 0, 2) + + output = layer(output, attention_mask=None, **kwargs) + + output = output[:, 1:, :].transpose(1, 2) # remove cls token and reshape to [batch_size, reduce_dim, seq_len] + + size = int(math.sqrt(output.shape[2])) + + batch_size = conditional_embeddings.shape[0] + output = output.view(batch_size, output.shape[1], size, size) + + logits = self.transposed_convolution(output).squeeze(1) + + return CLIPSegDecoderOutput(logits=logits) + + +@auto_docstring( + custom_intro=""" + The text model from CLIPSEG without any head or projection on top. + """ +) +class CLIPSegTextModel(CLIPSegPreTrainedModel): + config: CLIPSegTextConfig + input_modalities = ("text",) + _input_embed_layer = "token_embedding" + + def __init__(self, config: CLIPSegTextConfig): + super().__init__(config) + embed_dim = config.hidden_size + self.embeddings = CLIPSegTextEmbeddings(config) + self.encoder = CLIPSegEncoder(config) + self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps) + + # For `pooled_output` computation + self.eos_token_id = config.eos_token_id + self.post_init() + + @merge_with_config_defaults + @capture_outputs(tie_last_hidden_states=False) + @auto_docstring + def forward( + self, + input_ids: torch.Tensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.Tensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | BaseModelOutputWithPooling: + r""" + Examples: + + ```python + >>> from transformers import AutoTokenizer, CLIPSegTextModel + + >>> tokenizer = AutoTokenizer.from_pretrained("CIDAS/clipseg-rd64-refined") + >>> model = CLIPSegTextModel.from_pretrained("CIDAS/clipseg-rd64-refined") + + >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt") + + >>> outputs = model(**inputs) + >>> last_hidden_state = outputs.last_hidden_state + >>> pooled_output = outputs.pooler_output # pooled (EOS token) states + ```""" + if input_ids is None: + raise ValueError("You have to specify input_ids") + + input_shape = input_ids.size() + input_ids = input_ids.view(-1, input_shape[-1]) + + hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids) + + attention_mask = create_causal_mask( + config=self.config, + inputs_embeds=hidden_states, + attention_mask=attention_mask, + past_key_values=None, + ) + + kwargs.pop("is_causal", None) + encoder_outputs: BaseModelOutput = self.encoder( + inputs_embeds=hidden_states, + attention_mask=attention_mask, + is_causal=True, + **kwargs, + ) + + last_hidden_state = encoder_outputs.last_hidden_state + last_hidden_state = self.final_layer_norm(last_hidden_state) + + if self.eos_token_id == 2: + # The `eos_token_id` was incorrect before PR #24773: Let's keep what have been done here. + # A CLIPSEG model with such `eos_token_id` in the config can't work correctly with extra new tokens added + # ------------------------------------------------------------ + # text_embeds.shape = [batch_size, sequence_length, transformer.width] + # take features from the eot embedding (eot_token is the highest number in each sequence) + # casting to torch.int for onnx compatibility: argmax doesn't support int64 inputs with opset 14 + pooled_output = last_hidden_state[ + torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device), + input_ids.to(dtype=torch.int, device=last_hidden_state.device).argmax(dim=-1), + ] + else: + # The config gets updated `eos_token_id` from PR #24773 (so the use of extra new tokens is possible) + pooled_output = last_hidden_state[ + torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device), + # We need to get the first position of `eos_token_id` value (`pad_token_ids` might equal to `eos_token_id`) + # Note: we assume each sequence (along batch dim.) contains an `eos_token_id` (e.g. prepared by the tokenizer) + (input_ids.to(dtype=torch.int, device=last_hidden_state.device) == self.eos_token_id) + .int() + .argmax(dim=-1), + ] + + return BaseModelOutputWithPooling( + last_hidden_state=last_hidden_state, + pooler_output=pooled_output, + ) + + +@auto_docstring( + custom_intro=""" + The vision model from CLIPSEG without any head or projection on top. + """ +) +class CLIPSegVisionModel(CLIPSegPreTrainedModel): + config: CLIPSegVisionConfig + main_input_name = "pixel_values" + input_modalities = ("image",) + _input_embed_layer = "patch_embedding" + + def __init__(self, config: CLIPSegVisionConfig): + super().__init__(config) + embed_dim = config.hidden_size + + self.embeddings = CLIPSegVisionEmbeddings(config) + self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps) + self.encoder = CLIPSegEncoder(config) + self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps) + self.post_init() + + @merge_with_config_defaults + @capture_outputs(tie_last_hidden_states=False) + @auto_docstring + def forward( + self, + pixel_values: torch.FloatTensor | None, + interpolate_pos_encoding: bool | None = True, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | BaseModelOutputWithPooling: + r""" + Examples: + + ```python + >>> import httpx + >>> from io import BytesIO + >>> from PIL import Image + >>> from transformers import AutoProcessor, CLIPSegVisionModel + + >>> processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined") + >>> model = CLIPSegVisionModel.from_pretrained("CIDAS/clipseg-rd64-refined") + + >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" + >>> with httpx.stream("GET", url) as response: + ... image = Image.open(BytesIO(response.read())) + + >>> inputs = processor(images=image, return_tensors="pt") + + >>> outputs = model(**inputs) + >>> last_hidden_state = outputs.last_hidden_state + >>> pooled_output = outputs.pooler_output # pooled CLS states + ```""" + hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding) + hidden_states = self.pre_layrnorm(hidden_states) + + encoder_outputs: BaseModelOutput = self.encoder( + inputs_embeds=hidden_states, + **kwargs, + ) + + last_hidden_state = encoder_outputs.last_hidden_state + pooled_output = last_hidden_state[:, 0, :] + pooled_output = self.post_layernorm(pooled_output) + + return BaseModelOutputWithPooling( + last_hidden_state=last_hidden_state, + pooler_output=pooled_output, + ) + + +# contrastive loss function, adapted from +# https://sachinruk.github.io/blog/2021-03-07-clipseg.html +def contrastive_loss(logits: torch.Tensor) -> torch.Tensor: + return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device)) + + +def image_text_contrastive_loss(similarity: torch.Tensor) -> torch.Tensor: + caption_loss = contrastive_loss(similarity) + image_loss = contrastive_loss(similarity.T) + return (caption_loss + image_loss) / 2.0 + + +def _get_vector_norm(tensor: torch.Tensor) -> torch.Tensor: + """ + This method is equivalent to tensor.norm(p=2, dim=-1, keepdim=True) and used to make + model `executorch` exportable. See issue https://github.com/pytorch/executorch/issues/3566 + """ + square_tensor = torch.pow(tensor, 2) + sum_tensor = torch.sum(square_tensor, dim=-1, keepdim=True) + normed_tensor = torch.pow(sum_tensor, 0.5) + return normed_tensor + + +@auto_docstring +class CLIPSegModel(CLIPSegPreTrainedModel): + def __init__(self, config: CLIPSegConfig): + super().__init__(config) + + text_config = config.text_config + vision_config = config.vision_config + + self.projection_dim = config.projection_dim + self.text_embed_dim = text_config.hidden_size + self.vision_embed_dim = vision_config.hidden_size + + self.text_model = CLIPSegTextModel._from_config(text_config) + self.vision_model = CLIPSegVisionModel._from_config(vision_config) + + self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False) + self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False) + self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value)) + + # Initialize weights and apply final processing + self.post_init() + + @can_return_tuple + @auto_docstring + def get_text_features( + self, + input_ids: torch.Tensor, + attention_mask: torch.Tensor | None = None, + position_ids: torch.Tensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | BaseModelOutputWithPooling: + r""" + Examples: + + ```python + >>> import torch + >>> from transformers import AutoTokenizer, CLIPSegModel + + >>> tokenizer = AutoTokenizer.from_pretrained("CIDAS/clipseg-rd64-refined") + >>> model = CLIPSegModel.from_pretrained("CIDAS/clipseg-rd64-refined") + + >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt") + >>> with torch.inference_mode(): + ... text_features = model.get_text_features(**inputs) + ```""" + text_outputs: BaseModelOutputWithPooling = self.text_model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + return_dict=True, + **kwargs, + ) + pooled_output = text_outputs.pooler_output + text_outputs.pooler_output = self.text_projection(pooled_output) + + return text_outputs + + @can_return_tuple + @auto_docstring + def get_image_features( + self, + pixel_values: torch.FloatTensor, + interpolate_pos_encoding: bool = True, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | BaseModelOutputWithPooling: + r""" + Examples: + + ```python + >>> import torch + >>> from transformers import AutoProcessor, CLIPSegModel + >>> from transformers.image_utils import load_image + + >>> processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined") + >>> model = CLIPSegModel.from_pretrained("CIDAS/clipseg-rd64-refined") + + >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" + >>> image = load_image(url) + + >>> inputs = processor(images=image, return_tensors="pt") + + >>> with torch.inference_mode(): + ... image_features = model.get_image_features(**inputs) + ```""" + vision_outputs: BaseModelOutputWithPooling = self.vision_model( + pixel_values=pixel_values, + interpolate_pos_encoding=interpolate_pos_encoding, + return_dict=True, + **kwargs, + ) + pooled_output = vision_outputs.pooler_output + vision_outputs.pooler_output = self.visual_projection(pooled_output) + + return vision_outputs + + @can_return_tuple + @auto_docstring + def forward( + self, + input_ids: torch.LongTensor | None = None, + pixel_values: torch.FloatTensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.LongTensor | None = None, + return_loss: bool | None = None, + interpolate_pos_encoding: bool = True, + **kwargs: Unpack[TransformersKwargs], + ) -> CLIPSegOutput: + r""" + return_loss (`bool`, *optional*): + Whether or not to return the contrastive loss. + + Examples: + + ```python + >>> import torch + >>> from transformers import AutoProcessor, CLIPSegModel + >>> from transformers.image_utils import load_image + + >>> processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined") + >>> model = CLIPSegModel.from_pretrained("CIDAS/clipseg-rd64-refined") + + >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" + >>> image = load_image(url) + + >>> inputs = processor( + ... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True + ... ) + + >>> with torch.inference_mode(): + ... outputs = model(**inputs) + >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score + >>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities + ```""" + vision_outputs: BaseModelOutputWithPooling = self.get_image_features( + pixel_values=pixel_values, + interpolate_pos_encoding=interpolate_pos_encoding, + **kwargs, + ) + + text_outputs: BaseModelOutputWithPooling = self.get_text_features( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + **kwargs, + ) + + image_embeds = vision_outputs.pooler_output + text_embeds = text_outputs.pooler_output + + # normalized features + image_embeds = image_embeds / _get_vector_norm(image_embeds) + text_embeds = text_embeds / _get_vector_norm(text_embeds) + + # cosine similarity as logits + logits_per_text = torch.matmul(text_embeds, image_embeds.t().to(text_embeds.device)) + logits_per_text = logits_per_text * self.logit_scale.exp().to(text_embeds.device) + + logits_per_image = logits_per_text.t() + + loss = None + if return_loss: + loss = image_text_contrastive_loss(logits_per_text) + + return CLIPSegOutput( + loss=loss, + logits_per_image=logits_per_image, + logits_per_text=logits_per_text, + text_embeds=text_embeds, + image_embeds=image_embeds, + text_model_output=text_outputs, + vision_model_output=vision_outputs, + ) + + +@auto_docstring( + custom_intro=""" + CLIPSeg model with a Transformer-based decoder on top for zero-shot and one-shot image segmentation. + """ +) +class CLIPSegForImageSegmentation(CLIPSegPreTrainedModel): + config: CLIPSegConfig + + def __init__(self, config: CLIPSegConfig): + super().__init__(config) + self.clip = CLIPSegModel(config) + self.extract_layers = config.extract_layers + self.decoder = CLIPSegDecoder(config) + + self.post_init() + + def get_conditional_embeddings( + self, + batch_size: int | None = None, + input_ids: torch.Tensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.Tensor | None = None, + conditional_pixel_values: torch.Tensor | None = None, + ) -> torch.FloatTensor: + if input_ids is not None: + # compute conditional embeddings from texts + if len(input_ids) != batch_size: + raise ValueError("Make sure to pass as many prompt texts as there are query images") + with torch.no_grad(): + conditional_embeddings = self.clip.get_text_features( + input_ids, attention_mask=attention_mask, position_ids=position_ids + ).pooler_output + elif conditional_pixel_values is not None: + # compute conditional embeddings from images + if len(conditional_pixel_values) != batch_size: + raise ValueError("Make sure to pass as many prompt images as there are query images") + with torch.no_grad(): + conditional_embeddings = self.clip.get_image_features(conditional_pixel_values).pooler_output + else: + raise ValueError( + "Invalid conditional, should be either provided as `input_ids` or `conditional_pixel_values`" + ) + + return conditional_embeddings + + @can_return_tuple + @auto_docstring + def forward( + self, + input_ids: torch.FloatTensor | None = None, + pixel_values: torch.FloatTensor | None = None, + conditional_pixel_values: torch.FloatTensor | None = None, + conditional_embeddings: torch.FloatTensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.LongTensor | None = None, + labels: torch.LongTensor | None = None, + interpolate_pos_encoding: bool = True, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | CLIPSegOutput: + r""" + conditional_pixel_values (`torch.FloatTensor`, *optional*): + The pixel values of the conditional images. + conditional_embeddings (`torch.FloatTensor` of shape `(batch_size, config.projection_dim)`, *optional*): + The conditional embeddings for the query images. If provided, the model will use this instead of computing + the embeddings from the conditional_pixel_values. + labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., + config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If + `config.num_labels > 1` a classification loss is computed (Cross-Entropy). + + Examples: + + ```python + >>> import torch + >>> from transformers import AutoProcessor, CLIPSegForImageSegmentation + >>> from transformers.image_utils import load_image + + >>> processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined") + >>> model = CLIPSegForImageSegmentation.from_pretrained("CIDAS/clipseg-rd64-refined") + + >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" + >>> image = load_image(url) + + >>> texts = ["a cat", "a remote", "a blanket"] + >>> inputs = processor(text=texts, images=[image] * len(texts), padding=True, return_tensors="pt") + + >>> with torch.inference_mode(): + ... outputs = model(**inputs) + + >>> logits = outputs.logits + >>> print(logits.shape) + torch.Size([3, 352, 352]) + ```""" + # step 1: forward the query images through the frozen CLIP vision encoder + with torch.no_grad(): + kwargs["output_hidden_states"] = True # required to extract layers for the stages + vision_outputs = self.clip.get_image_features( + pixel_values=pixel_values, + interpolate_pos_encoding=interpolate_pos_encoding, + **kwargs, + ) + pooled_output = vision_outputs.pooler_output + + hidden_states = vision_outputs.hidden_states + # we add +1 here as the hidden states also include the initial embeddings + activations = [hidden_states[i + 1] for i in self.extract_layers] + + # update vision_outputs + vision_outputs = BaseModelOutputWithPooling( + last_hidden_state=vision_outputs.last_hidden_state, + pooler_output=vision_outputs.pooler_output, + hidden_states=vision_outputs.hidden_states, + attentions=vision_outputs.attentions, + ) + + # step 2: compute conditional embeddings, either from text, images or an own provided embedding + if conditional_embeddings is None: + conditional_embeddings = self.get_conditional_embeddings( + batch_size=pixel_values.shape[0], + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + conditional_pixel_values=conditional_pixel_values, + ) + else: + if conditional_embeddings.shape[0] != pixel_values.shape[0]: + raise ValueError( + "Make sure to pass as many conditional embeddings as there are query images in the batch" + ) + if conditional_embeddings.shape[1] != self.config.projection_dim: + raise ValueError( + "Make sure that the feature dimension of the conditional embeddings matches" + " `config.projection_dim`." + ) + + # step 3: forward both the pooled output and the activations through the lightweight decoder to predict masks + decoder_outputs = self.decoder( + activations, + conditional_embeddings, + **kwargs, + ) + logits = decoder_outputs.logits + + loss = None + if labels is not None: + # move labels to the correct device to enable PP + labels = labels.to(logits.device) + loss_fn = nn.BCEWithLogitsLoss() + loss = loss_fn(logits, labels) + + return CLIPSegImageSegmentationOutput( + loss=loss, + logits=logits, + conditional_embeddings=conditional_embeddings, + pooled_output=pooled_output, + vision_model_output=vision_outputs, + decoder_output=decoder_outputs, + ) + + +__all__ = [ + "CLIPSegModel", + "CLIPSegPreTrainedModel", + "CLIPSegTextModel", + "CLIPSegVisionModel", + "CLIPSegForImageSegmentation", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/modular_clipseg.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/modular_clipseg.py new file mode 100644 index 0000000000000000000000000000000000000000..d84e916c33753219846d6954a039a42be9499a3c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/modular_clipseg.py @@ -0,0 +1,681 @@ +# Copyright 2022 The OpenAI Team Authors and The HuggingFace Team. All rights reserved. +# +# 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. +"""PyTorch CLIPSeg model.""" + +import copy +import math +from dataclasses import dataclass +from typing import Any + +import torch +from huggingface_hub.dataclasses import strict +from torch import nn + +from ... import initialization as init +from ...modeling_outputs import BaseModelOutputWithPooling +from ...processing_utils import Unpack +from ...utils import ModelOutput, TransformersKwargs, auto_docstring +from ...utils.generic import can_return_tuple, merge_with_config_defaults +from ...utils.output_capturing import capture_outputs +from ..clip.configuration_clip import CLIPConfig, CLIPTextConfig, CLIPVisionConfig +from ..clip.modeling_clip import ( + CLIPMLP, + CLIPAttention, + CLIPEncoder, + CLIPEncoderLayer, + CLIPModel, + CLIPOutput, + CLIPPreTrainedModel, + CLIPTextEmbeddings, + CLIPTextModel, + CLIPVisionEmbeddings, + CLIPVisionModel, +) + + +@auto_docstring(checkpoint="CIDAS/clipseg-rd64") +@strict +class CLIPSegTextConfig(CLIPTextConfig): + r""" + Example: + + ```python + >>> from transformers import CLIPSegTextConfig, CLIPSegTextModel + + >>> # Initializing a CLIPSegTextConfig with CIDAS/clipseg-rd64 style configuration + >>> configuration = CLIPSegTextConfig() + + >>> # Initializing a CLIPSegTextModel (with random weights) from the CIDAS/clipseg-rd64 style configuration + >>> model = CLIPSegTextModel(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + projection_dim = AttributeError() + + +@auto_docstring(checkpoint="CIDAS/clipseg-rd64") +@strict +class CLIPSegVisionConfig(CLIPVisionConfig): + r""" + Example: + + ```python + >>> from transformers import CLIPSegVisionConfig, CLIPSegVisionModel + + >>> # Initializing a CLIPSegVisionConfig with CIDAS/clipseg-rd64 style configuration + >>> configuration = CLIPSegVisionConfig() + + >>> # Initializing a CLIPSegVisionModel (with random weights) from the CIDAS/clipseg-rd64 style configuration + >>> model = CLIPSegVisionModel(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + projection_dim = AttributeError() + + +@auto_docstring(checkpoint="CIDAS/clipseg-rd64") +@strict +class CLIPSegConfig(CLIPConfig): + r""" + extract_layers (`list[int]`, *optional*, defaults to `[3, 6, 9]`): + Layers to extract when forwarding the query image through the frozen visual backbone of CLIP. + reduce_dim (`int`, *optional*, defaults to 64): + Dimensionality to reduce the CLIP vision embedding. + conditional_layer (`int`, *optional*, defaults to 0): + The layer to use of the Transformer encoder whose activations will be combined with the condition + embeddings using FiLM (Feature-wise Linear Modulation). If 0, the last layer is used. + use_complex_transposed_convolution (`bool`, *optional*, defaults to `False`): + Whether to use a more complex transposed convolution in the decoder, enabling more fine-grained + segmentation.. + + Example: + + ```python + >>> from transformers import CLIPSegConfig, CLIPSegModel + + >>> # Initializing a CLIPSegConfig with CIDAS/clipseg-rd64 style configuration + >>> configuration = CLIPSegConfig() + + >>> # Initializing a CLIPSegModel (with random weights) from the CIDAS/clipseg-rd64 style configuration + >>> model = CLIPSegModel(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + + >>> # We can also initialize a CLIPSegConfig from a CLIPSegTextConfig and a CLIPSegVisionConfig + + >>> # Initializing a CLIPSegText and CLIPSegVision configuration + >>> config_text = CLIPSegTextConfig() + >>> config_vision = CLIPSegVisionConfig() + + >>> config = CLIPSegConfig(text_config=config_text, vision_config=config_vision) + ```""" + + extract_layers: list[int] | tuple[int, ...] = (3, 6, 9) + reduce_dim: int = 64 + decoder_num_attention_heads: int = 4 + decoder_attention_dropout: float | int = 0.0 + decoder_hidden_act: str = "quick_gelu" + decoder_intermediate_size: int = 2048 + conditional_layer: int = 0 + use_complex_transposed_convolution: bool = False + + +class CLIPSegOutput(CLIPOutput): + pass + + +@dataclass +@auto_docstring +class CLIPSegDecoderOutput(ModelOutput): + r""" + logits (`torch.FloatTensor` of shape `(batch_size, height, width)`): + Classification scores for each pixel. + hidden_states (`tuple(torch.FloatTensor)`, *optional*,): + Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. + Rreturned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True` + attentions (`tuple(torch.FloatTensor)`, *optional*): + Attentions weights after the attention softmax, used to compute the weighted average in the self-attention + heads. Returned when `output_attentions=True` is passed or when `config.output_attentions=True` + """ + + logits: torch.FloatTensor | None = None + hidden_states: tuple[torch.FloatTensor, ...] | None = None + attentions: tuple[torch.FloatTensor, ...] | None = None + + +@dataclass +@auto_docstring +class CLIPSegImageSegmentationOutput(ModelOutput): + r""" + loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): + Binary cross entropy loss for segmentation. + logits (`torch.FloatTensor` of shape `(batch_size, height, width)`): + Classification scores for each pixel. + conditional_embeddings (`torch.FloatTensor` of shape `(batch_size, projection_dim)`): + Conditional embeddings used for segmentation. + pooled_output (`torch.FloatTensor` of shape `(batch_size, embed_dim)`): + Pooled output of the [`CLIPSegVisionModel`]. + vision_model_output (`BaseModelOutputWithPooling`): + The output of the [`CLIPSegVisionModel`]. + decoder_output (`CLIPSegDecoderOutput`): + The output of the [`CLIPSegDecoder`]. + """ + + loss: torch.FloatTensor | None = None + logits: torch.FloatTensor | None = None + conditional_embeddings: torch.FloatTensor | None = None + pooled_output: torch.FloatTensor | None = None + vision_model_output: BaseModelOutputWithPooling = None + decoder_output: CLIPSegDecoderOutput = None + + def to_tuple(self) -> tuple[Any]: + return tuple(v.to_tuple() if isinstance(v, ModelOutput) else v for v in self.values()) + + +class CLIPSegVisionEmbeddings(CLIPVisionEmbeddings): + # Different default for `interpolate_pos_encoding` from CLIP + def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding=True) -> torch.Tensor: + super().forward(pixel_values, interpolate_pos_encoding) + + +class CLIPSegTextEmbeddings(CLIPTextEmbeddings): + pass + + +class CLIPSegAttention(CLIPAttention): + pass + + +class CLIPSegMLP(CLIPMLP): + pass + + +class CLIPSegEncoderLayer(CLIPEncoderLayer): + pass + + +class CLIPSegDecoderLayer(CLIPEncoderLayer): + """ + CLIPSeg decoder layer, which is identical to `CLIPSegEncoderLayer`, except that normalization is applied after + self-attention/MLP, rather than before. + """ + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: torch.Tensor, + **kwargs, + ) -> tuple[torch.FloatTensor]: + residual = hidden_states + + hidden_states, _ = self.self_attn( + hidden_states=hidden_states, + attention_mask=attention_mask, + **kwargs, + ) + + hidden_states = residual + hidden_states + hidden_states = self.layer_norm1(hidden_states) + + residual = hidden_states + hidden_states = self.mlp(hidden_states) + hidden_states = residual + hidden_states + hidden_states = self.layer_norm2(hidden_states) + + return hidden_states + + +@auto_docstring +class CLIPSegPreTrainedModel(CLIPPreTrainedModel): + _can_record_outputs = { + "hidden_states": [CLIPSegEncoderLayer, CLIPSegDecoderLayer], + "attentions": CLIPSegAttention, + } + + @torch.no_grad() + def _init_weights(self, module): + """Initialize the weights""" + factor = self.config.initializer_factor + if isinstance(module, CLIPSegTextEmbeddings): + init.normal_(module.token_embedding.weight, mean=0.0, std=factor * 0.02) + init.normal_(module.position_embedding.weight, mean=0.0, std=factor * 0.02) + init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1))) + elif isinstance(module, CLIPSegVisionEmbeddings): + init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor) + init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor) + init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor) + init.copy_(module.position_ids, torch.arange(module.num_positions).expand((1, -1))) + elif isinstance(module, CLIPSegAttention): + in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor + out_proj_std = (module.embed_dim**-0.5) * factor + init.normal_(module.q_proj.weight, std=in_proj_std) + init.normal_(module.k_proj.weight, std=in_proj_std) + init.normal_(module.v_proj.weight, std=in_proj_std) + init.normal_(module.out_proj.weight, std=out_proj_std) + elif isinstance(module, CLIPSegMLP): + in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor + fc_std = (2 * module.config.hidden_size) ** -0.5 * factor + init.normal_(module.fc1.weight, std=fc_std) + init.normal_(module.fc2.weight, std=in_proj_std) + elif isinstance(module, CLIPSegModel): + init.normal_( + module.text_projection.weight, + std=module.text_embed_dim**-0.5 * factor, + ) + init.normal_( + module.visual_projection.weight, + std=module.vision_embed_dim**-0.5 * factor, + ) + + if isinstance(module, nn.LayerNorm): + init.zeros_(module.bias) + init.ones_(module.weight) + if isinstance(module, nn.Linear) and module.bias is not None: + init.zeros_(module.bias) + + +class CLIPSegEncoder(CLIPEncoder): + pass + + +class CLIPSegDecoder(CLIPSegPreTrainedModel): + def __init__(self, config: CLIPSegConfig): + super().__init__(config) + + self.conditional_layer = config.conditional_layer + + self.film_mul = nn.Linear(config.projection_dim, config.reduce_dim) + self.film_add = nn.Linear(config.projection_dim, config.reduce_dim) + + if config.use_complex_transposed_convolution: + transposed_kernels = (config.vision_config.patch_size // 4, config.vision_config.patch_size // 4) + + self.transposed_convolution = nn.Sequential( + nn.Conv2d(config.reduce_dim, config.reduce_dim, kernel_size=3, padding=1), + nn.ReLU(), + nn.ConvTranspose2d( + config.reduce_dim, + config.reduce_dim // 2, + kernel_size=transposed_kernels[0], + stride=transposed_kernels[0], + ), + nn.ReLU(), + nn.ConvTranspose2d( + config.reduce_dim // 2, 1, kernel_size=transposed_kernels[1], stride=transposed_kernels[1] + ), + ) + else: + self.transposed_convolution = nn.ConvTranspose2d( + config.reduce_dim, 1, config.vision_config.patch_size, stride=config.vision_config.patch_size + ) + + depth = len(config.extract_layers) + self.reduces = nn.ModuleList( + [nn.Linear(config.vision_config.hidden_size, config.reduce_dim) for _ in range(depth)] + ) + + decoder_config = copy.deepcopy(config.vision_config) + decoder_config.hidden_size = config.reduce_dim + decoder_config.num_attention_heads = config.decoder_num_attention_heads + decoder_config.intermediate_size = config.decoder_intermediate_size + decoder_config.hidden_act = "relu" + self.layers = nn.ModuleList([CLIPSegDecoderLayer(decoder_config) for _ in range(len(config.extract_layers))]) + + self.post_init() + + @merge_with_config_defaults + @capture_outputs + @auto_docstring + def forward( + self, + hidden_states: tuple[torch.Tensor], + conditional_embeddings: torch.Tensor, + **kwargs: Unpack[TransformersKwargs], + ) -> CLIPSegDecoderOutput: + r""" + conditional_embeddings (`torch.FloatTensor` of shape `(batch_size, config.projection_dim)`, *optional*): + The conditional embeddings for the query images. If provided, the model will use this instead of computing + the embeddings from the conditional_pixel_values. + """ + activations = hidden_states[::-1] + + output = None + for i, (activation, layer, reduce) in enumerate(zip(activations, self.layers, self.reduces)): + if output is not None: + output = reduce(activation) + output + else: + output = reduce(activation) + + if i == self.conditional_layer: + output = self.film_mul(conditional_embeddings) * output.permute(1, 0, 2) + self.film_add( + conditional_embeddings + ) + output = output.permute(1, 0, 2) + + output = layer(output, attention_mask=None, **kwargs) + + output = output[:, 1:, :].transpose(1, 2) # remove cls token and reshape to [batch_size, reduce_dim, seq_len] + + size = int(math.sqrt(output.shape[2])) + + batch_size = conditional_embeddings.shape[0] + output = output.view(batch_size, output.shape[1], size, size) + + logits = self.transposed_convolution(output).squeeze(1) + + return CLIPSegDecoderOutput(logits=logits) + + +class CLIPSegTextModel(CLIPTextModel): + def forward(self, **super_kwargs) -> tuple | BaseModelOutputWithPooling: + r""" + Examples: + + ```python + >>> from transformers import AutoTokenizer, CLIPSegTextModel + + >>> tokenizer = AutoTokenizer.from_pretrained("CIDAS/clipseg-rd64-refined") + >>> model = CLIPSegTextModel.from_pretrained("CIDAS/clipseg-rd64-refined") + + >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt") + + >>> outputs = model(**inputs) + >>> last_hidden_state = outputs.last_hidden_state + >>> pooled_output = outputs.pooler_output # pooled (EOS token) states + ```""" + return super().forward(**super_kwargs) + + +class CLIPSegVisionModel(CLIPVisionModel): + def forward( + self, + pixel_values: torch.FloatTensor | None, + interpolate_pos_encoding: bool | None = True, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | BaseModelOutputWithPooling: + r""" + Examples: + + ```python + >>> import httpx + >>> from io import BytesIO + >>> from PIL import Image + >>> from transformers import AutoProcessor, CLIPSegVisionModel + + >>> processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined") + >>> model = CLIPSegVisionModel.from_pretrained("CIDAS/clipseg-rd64-refined") + + >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" + >>> with httpx.stream("GET", url) as response: + ... image = Image.open(BytesIO(response.read())) + + >>> inputs = processor(images=image, return_tensors="pt") + + >>> outputs = model(**inputs) + >>> last_hidden_state = outputs.last_hidden_state + >>> pooled_output = outputs.pooler_output # pooled CLS states + ```""" + return super().forward(pixel_values, interpolate_pos_encoding, **kwargs) + + +class CLIPSegModel(CLIPModel): + def get_text_features(self, **super_kwargs): + r""" + Examples: + + ```python + >>> import torch + >>> from transformers import AutoTokenizer, CLIPSegModel + + >>> tokenizer = AutoTokenizer.from_pretrained("CIDAS/clipseg-rd64-refined") + >>> model = CLIPSegModel.from_pretrained("CIDAS/clipseg-rd64-refined") + + >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt") + >>> with torch.inference_mode(): + ... text_features = model.get_text_features(**inputs) + ```""" + return super().get_text_features(**super_kwargs) + + def get_image_features( + self, + pixel_values: torch.FloatTensor, + interpolate_pos_encoding: bool = True, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | BaseModelOutputWithPooling: + r""" + Examples: + + ```python + >>> import torch + >>> from transformers import AutoProcessor, CLIPSegModel + >>> from transformers.image_utils import load_image + + >>> processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined") + >>> model = CLIPSegModel.from_pretrained("CIDAS/clipseg-rd64-refined") + + >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" + >>> image = load_image(url) + + >>> inputs = processor(images=image, return_tensors="pt") + + >>> with torch.inference_mode(): + ... image_features = model.get_image_features(**inputs) + ```""" + return super().get_image_features(pixel_values, interpolate_pos_encoding, **kwargs) + + def forward(self, interpolate_pos_encoding: bool = True, **super_kwargs): + r""" + return_loss (`bool`, *optional*): + Whether or not to return the contrastive loss. + + Examples: + + ```python + >>> import torch + >>> from transformers import AutoProcessor, CLIPSegModel + >>> from transformers.image_utils import load_image + + >>> processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined") + >>> model = CLIPSegModel.from_pretrained("CIDAS/clipseg-rd64-refined") + + >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" + >>> image = load_image(url) + + >>> inputs = processor( + ... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True + ... ) + + >>> with torch.inference_mode(): + ... outputs = model(**inputs) + >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score + >>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities + ```""" + super().forward(interpolate_pos_encoding=interpolate_pos_encoding, **super_kwargs) + + +@auto_docstring( + custom_intro=""" + CLIPSeg model with a Transformer-based decoder on top for zero-shot and one-shot image segmentation. + """ +) +class CLIPSegForImageSegmentation(CLIPSegPreTrainedModel): + config: CLIPSegConfig + + def __init__(self, config: CLIPSegConfig): + super().__init__(config) + self.clip = CLIPSegModel(config) + self.extract_layers = config.extract_layers + self.decoder = CLIPSegDecoder(config) + + self.post_init() + + def get_conditional_embeddings( + self, + batch_size: int | None = None, + input_ids: torch.Tensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.Tensor | None = None, + conditional_pixel_values: torch.Tensor | None = None, + ) -> torch.FloatTensor: + if input_ids is not None: + # compute conditional embeddings from texts + if len(input_ids) != batch_size: + raise ValueError("Make sure to pass as many prompt texts as there are query images") + with torch.no_grad(): + conditional_embeddings = self.clip.get_text_features( + input_ids, attention_mask=attention_mask, position_ids=position_ids + ).pooler_output + elif conditional_pixel_values is not None: + # compute conditional embeddings from images + if len(conditional_pixel_values) != batch_size: + raise ValueError("Make sure to pass as many prompt images as there are query images") + with torch.no_grad(): + conditional_embeddings = self.clip.get_image_features(conditional_pixel_values).pooler_output + else: + raise ValueError( + "Invalid conditional, should be either provided as `input_ids` or `conditional_pixel_values`" + ) + + return conditional_embeddings + + @can_return_tuple + @auto_docstring + def forward( + self, + input_ids: torch.FloatTensor | None = None, + pixel_values: torch.FloatTensor | None = None, + conditional_pixel_values: torch.FloatTensor | None = None, + conditional_embeddings: torch.FloatTensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.LongTensor | None = None, + labels: torch.LongTensor | None = None, + interpolate_pos_encoding: bool = True, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | CLIPSegOutput: + r""" + conditional_pixel_values (`torch.FloatTensor`, *optional*): + The pixel values of the conditional images. + conditional_embeddings (`torch.FloatTensor` of shape `(batch_size, config.projection_dim)`, *optional*): + The conditional embeddings for the query images. If provided, the model will use this instead of computing + the embeddings from the conditional_pixel_values. + labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., + config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If + `config.num_labels > 1` a classification loss is computed (Cross-Entropy). + + Examples: + + ```python + >>> import torch + >>> from transformers import AutoProcessor, CLIPSegForImageSegmentation + >>> from transformers.image_utils import load_image + + >>> processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined") + >>> model = CLIPSegForImageSegmentation.from_pretrained("CIDAS/clipseg-rd64-refined") + + >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" + >>> image = load_image(url) + + >>> texts = ["a cat", "a remote", "a blanket"] + >>> inputs = processor(text=texts, images=[image] * len(texts), padding=True, return_tensors="pt") + + >>> with torch.inference_mode(): + ... outputs = model(**inputs) + + >>> logits = outputs.logits + >>> print(logits.shape) + torch.Size([3, 352, 352]) + ```""" + # step 1: forward the query images through the frozen CLIP vision encoder + with torch.no_grad(): + kwargs["output_hidden_states"] = True # required to extract layers for the stages + vision_outputs = self.clip.get_image_features( + pixel_values=pixel_values, + interpolate_pos_encoding=interpolate_pos_encoding, + **kwargs, + ) + pooled_output = vision_outputs.pooler_output + + hidden_states = vision_outputs.hidden_states + # we add +1 here as the hidden states also include the initial embeddings + activations = [hidden_states[i + 1] for i in self.extract_layers] + + # update vision_outputs + vision_outputs = BaseModelOutputWithPooling( + last_hidden_state=vision_outputs.last_hidden_state, + pooler_output=vision_outputs.pooler_output, + hidden_states=vision_outputs.hidden_states, + attentions=vision_outputs.attentions, + ) + + # step 2: compute conditional embeddings, either from text, images or an own provided embedding + if conditional_embeddings is None: + conditional_embeddings = self.get_conditional_embeddings( + batch_size=pixel_values.shape[0], + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + conditional_pixel_values=conditional_pixel_values, + ) + else: + if conditional_embeddings.shape[0] != pixel_values.shape[0]: + raise ValueError( + "Make sure to pass as many conditional embeddings as there are query images in the batch" + ) + if conditional_embeddings.shape[1] != self.config.projection_dim: + raise ValueError( + "Make sure that the feature dimension of the conditional embeddings matches" + " `config.projection_dim`." + ) + + # step 3: forward both the pooled output and the activations through the lightweight decoder to predict masks + decoder_outputs = self.decoder( + activations, + conditional_embeddings, + **kwargs, + ) + logits = decoder_outputs.logits + + loss = None + if labels is not None: + # move labels to the correct device to enable PP + labels = labels.to(logits.device) + loss_fn = nn.BCEWithLogitsLoss() + loss = loss_fn(logits, labels) + + return CLIPSegImageSegmentationOutput( + loss=loss, + logits=logits, + conditional_embeddings=conditional_embeddings, + pooled_output=pooled_output, + vision_model_output=vision_outputs, + decoder_output=decoder_outputs, + ) + + +__all__ = [ + "CLIPSegConfig", + "CLIPSegTextConfig", + "CLIPSegVisionConfig", + "CLIPSegModel", + "CLIPSegPreTrainedModel", + "CLIPSegTextModel", + "CLIPSegVisionModel", + "CLIPSegForImageSegmentation", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/processing_clipseg.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/processing_clipseg.py new file mode 100644 index 0000000000000000000000000000000000000000..9d2e0538401a4679540c386a42a6660907e4d956 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/processing_clipseg.py @@ -0,0 +1,88 @@ +# Copyright 2022 The HuggingFace Inc. team. +# +# 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. +""" +Image/Text processor class for CLIPSeg +""" + +from ...processing_utils import ProcessorMixin +from ...tokenization_utils_base import BatchEncoding +from ...utils import auto_docstring + + +@auto_docstring +class CLIPSegProcessor(ProcessorMixin): + def __init__(self, image_processor=None, tokenizer=None, **kwargs): + super().__init__(image_processor, tokenizer) + + @auto_docstring + def __call__(self, text=None, images=None, visual_prompt=None, return_tensors=None, **kwargs): + r""" + visual_prompt (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`): + The visual prompt image or batch of images to be prepared. Each visual prompt image can be a PIL image, + NumPy array or PyTorch tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape + (C, H, W), where C is a number of channels, H and W are image height and width. + + Returns: + [`BatchEncoding`]: A [`BatchEncoding`] with the following fields: + + - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`. + - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when + `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not + `None`). + - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`. + """ + if text is None and visual_prompt is None and images is None: + raise ValueError("You have to specify either text, visual prompt or images.") + + if text is not None and visual_prompt is not None: + raise ValueError("You have to specify exactly one type of prompt. Either text or visual prompt.") + + output_kwargs = self._merge_kwargs( + self.valid_processor_kwargs, tokenizer_init_kwargs=self.tokenizer.init_kwargs, **kwargs + ) + + if text is not None: + encoding = self.tokenizer(text, return_tensors=return_tensors, **output_kwargs["text_kwargs"]) + + if visual_prompt is not None: + prompt_features = self.image_processor( + visual_prompt, return_tensors=return_tensors, **output_kwargs["images_kwargs"] + ) + + if images is not None: + image_features = self.image_processor( + images, return_tensors=return_tensors, **output_kwargs["images_kwargs"] + ) + + if visual_prompt is not None and images is not None: + encoding = { + "pixel_values": image_features.pixel_values, + "conditional_pixel_values": prompt_features.pixel_values, + } + return encoding + elif text is not None and images is not None: + encoding["pixel_values"] = image_features.pixel_values + return encoding + elif text is not None: + return encoding + elif visual_prompt is not None: + encoding = { + "conditional_pixel_values": prompt_features.pixel_values, + } + return encoding + else: + return BatchEncoding(data=dict(**image_features), tensor_type=return_tensors) + + +__all__ = ["CLIPSegProcessor"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clvp/configuration_clvp.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clvp/configuration_clvp.py new file mode 100644 index 0000000000000000000000000000000000000000..008ef26c3a18f898851bd8ef7f6c147db4e4f932 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clvp/configuration_clvp.py @@ -0,0 +1,253 @@ +# Copyright 2023 The HuggingFace Inc. team. All rights reserved. +# +# 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. +"""CLVP model configuration""" + +import os + +from huggingface_hub.dataclasses import strict + +from ...configuration_utils import PreTrainedConfig +from ...utils import auto_docstring, logging + + +logger = logging.get_logger(__name__) + + +@auto_docstring(checkpoint="susnato/clvp_dev") +@strict +class ClvpEncoderConfig(PreTrainedConfig): + r""" + use_rotary_embedding (`bool`, *optional*, defaults to `True`): + Whether to use rotary_embedding or not. + use_attention_bias (`bool`, *optional*, defaults to `False`): + Whether to use bias in Query, Key and Value layers during self attention. + summary_type (`str`, *optional*, defaults to `"mean"`): + What strategy to use to get pooler_output from the last_hidden_state. `"last"`, `"first"`, `"mean"` and + `"cls_index"` are supported. + + Example: + + ```python + >>> from transformers import ClvpEncoderConfig, ClvpEncoder + + >>> # Initializing a ClvpEncoderConfig with susnato/clvp_dev style configuration + >>> encoder_configuration = ClvpEncoderConfig() + + >>> # Initializing a ClvpEncoder (with random weights) from the susnato/clvp_dev style configuration + >>> model = ClvpEncoder(encoder_configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + model_type = "clvp_encoder" + base_config_key = ["text_config", "speech_config"] + + vocab_size: int = 256 + hidden_size: int = 768 + intermediate_size: int = 1536 + projection_dim: int = 768 + num_hidden_layers: int = 20 + num_attention_heads: int = 12 + hidden_act: str = "gelu" + layer_norm_eps: float = 1e-5 + attention_dropout: float | int = 0.1 + dropout: float | int = 0.1 + use_rotary_embedding: bool = True + use_attention_bias: bool = False + summary_type: str = "mean" + initializer_factor: float = 1.0 + bos_token_id: int | None = 255 + eos_token_id: int | list[int] | None = 0 + pad_token_id: int | None = None + + @classmethod + def from_pretrained( + cls, pretrained_model_name_or_path: str | os.PathLike, config_type: str = "text_config", **kwargs + ): + config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs) + + # make sure to have the config_type be either "text_config" or "speech_config" + # this is to make sure that we can load only text or speech configs from the nested ClvpConfig. + if config_type not in cls.base_config_key: + raise ValueError( + f"We can only load either 'text_config' or 'speech_config' but you are trying to load{config_type}" + ) + + # get the text config dict if we are loading from ClvpConfig + if config_dict.get("model_type") == "clvp": + config_dict = config_dict[config_type] + + if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type: + logger.warning( + f"You are using a model of type {config_dict['model_type']} to instantiate a model of type " + f"{cls.model_type}. This is not supported for all configurations of models and can yield errors." + ) + + return cls.from_dict(config_dict, **kwargs) + + +@auto_docstring(checkpoint="susnato/clvp_dev") +@strict +class ClvpDecoderConfig(PreTrainedConfig): + r""" + max_text_tokens (`int`, *optional*, defaults to 404): + The maximum sequence length of text tokens that this model might ever be used with. Similar to + `n_positions` in `GPT2Config`. + n_inner (`int`, *optional*): + Dimensionality of the inner feed-forward layers. `None` will set it to 4 times `hidden_size`. + num_mel_attn_blocks (`int`, *optional*, defaults to 6): + Denotes the number of self attention layers in [`ClvpConditioningEncoder`]. + summary_type (`string`, *optional*, defaults to `"cls_index"`): + Argument used when doing sequence summary. + Has to be one of the following options: + - `"last"`: Take the last token hidden state (like XLNet). + - `"first"`: Take the first token hidden state (like BERT). + - `"mean"`: Take the mean of all tokens hidden states. + - `"cls_index"`: Supply a Tensor of classification token position (like GPT/GPT-2). + - `"attn"`: Not implemented now, use multi-head attention. + summary_use_proj (`bool`, *optional*, defaults to `True`): + Whether or not to add a projection after the vector extraction. + summary_activation (`str`, *optional*): + Pass `"tanh"` for a tanh activation to the output, any other value will result in no activation. + summary_proj_to_labels (`bool`, *optional*, defaults to `True`): + Whether the projection outputs should have `config.num_labels` or `config.hidden_size` classes. + summary_first_dropout (`float`, *optional*, defaults to 0.1): + The dropout ratio to be used after the projection and activation. + feature_size (`int`, *optional*, defaults to 80): + The feature dimension of the extracted mel features. This value is used in [`ClvpConditioningEncoder`]. + use_attention_bias (`bool`, *optional*, defaults to `True`): + Whether to use bias in Query, Key and Value layers during self attention. + decoder_fixing_codes (`list`, *optional*, defaults to `[83, 45, 45, 248]`): + These values are used in the method `fix_speech_decoder_output` to fix decoder generated outputs. + + Example: + + ```python + >>> from transformers import ClvpDecoderConfig, ClvpDecoder + + >>> # Initializing a ClvpDecoderConfig with susnato/clvp_dev style configuration + >>> decoder_configuration = ClvpDecoderConfig() + + >>> # Initializing a ClvpDecoder (with random weights) from the susnato/clvp_dev style configuration + >>> model = ClvpDecoder(decoder_configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + model_type = "clvp_decoder" + base_config_key = "decoder_config" + + vocab_size: int = 8194 + max_position_embeddings: int = 608 + max_text_tokens: int = 404 + hidden_size: int = 1024 + num_hidden_layers: int = 30 + num_attention_heads: int = 16 + n_inner: int | None = None + num_mel_attn_blocks: int = 6 + activation_function: str = "gelu_new" + resid_pdrop: float | int = 0.1 + embd_pdrop: float | int = 0.1 + attention_dropout: float | int = 0.1 + layer_norm_epsilon: float = 1e-5 + initializer_range: float = 0.02 + summary_type: str = "cls_index" + summary_use_proj: bool = True + summary_activation: str | None = None + summary_proj_to_labels: bool = True + summary_first_dropout: float | int = 0.1 + use_cache: bool = True + bos_token_id: int | None = 8192 + eos_token_id: int | list[int] | None = 8193 + pad_token_id: int | None = None + feature_size: int = 80 + use_attention_bias: bool = True + initializer_factor: float = 1.0 + decoder_fixing_codes: list[int] | tuple[int, ...] = (83, 45, 45, 248) + add_cross_attention: bool = False + + +@auto_docstring(checkpoint="susnato/clvp_dev") +@strict +class ClvpConfig(PreTrainedConfig): + r""" + speech_config (`dict`, *optional*): + Dictionary of configuration options used to initialize CLVP speech encoder. + decoder_config (`dict`, *optional*): + Dictionary of configuration options used to initialize [`ClvpDecoderConfig`]. + + Example: + + ```python + >>> from transformers import ClvpConfig, ClvpModelForConditionalGeneration + + >>> # Initializing a ClvpConfig with susnato/clvp_dev style configuration + >>> configuration = ClvpConfig() + + >>> # Initializing a ClvpModelForConditionalGeneration (with random weights) from the susnato/clvp_dev style configuration + >>> model = ClvpModelForConditionalGeneration(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + + >>> # We can also initialize a CLVPConfig from a CLVPTextConfig, CLVPSpeechConfig and a CLVPAutoRegressiveConfig + >>> from transformers import ClvpEncoderConfig, ClvpDecoderConfig + + >>> # Initializing a CLVP text, CLVP speech and CLVP decoder configuration + >>> config_text = ClvpEncoderConfig() + >>> config_speech = ClvpEncoderConfig() + >>> decoder_config = ClvpDecoderConfig() + + >>> config = ClvpConfig(config_text, config_speech, decoder_config) + ```""" + + model_type = "clvp" + sub_configs = { + "text_config": ClvpEncoderConfig, + "speech_config": ClvpEncoderConfig, + "decoder_config": ClvpDecoderConfig, + } + + text_config: dict | PreTrainedConfig | None = None + speech_config: dict | PreTrainedConfig | None = None + decoder_config: dict | PreTrainedConfig | None = None + projection_dim: int = 768 + logit_scale_init_value: float = 2.6592 + initializer_factor: float = 1.0 + + def __post_init__(self, **kwargs): + if self.text_config is None: + self.text_config = ClvpEncoderConfig() + logger.info("`text_config` is `None`. initializing the `ClvpEncoderConfig` with default values.") + elif isinstance(self.text_config, dict): + self.text_config = ClvpEncoderConfig(**self.text_config) + + if self.speech_config is None: + self.speech_config = ClvpEncoderConfig() + logger.info("`speech_config` is `None`. initializing the `ClvpEncoderConfig` with default values.") + elif isinstance(self.speech_config, dict): + self.speech_config = ClvpEncoderConfig(**self.speech_config) + + if self.decoder_config is None: + self.decoder_config = ClvpDecoderConfig() + logger.info("`image_config` is `None`. initializing the `ClvpDecoderConfig` with default values.") + elif isinstance(self.decoder_config, dict): + self.decoder_config = ClvpDecoderConfig(**self.decoder_config) + + super().__post_init__(**kwargs) + + +__all__ = ["ClvpConfig", "ClvpDecoderConfig", "ClvpEncoderConfig"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6d11e00115142686de011a8a0243ac7be6be0683 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__init__.py @@ -0,0 +1,1080 @@ +# Copyright 2018 The HuggingFace Inc. team. +# +# 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. +from __future__ import annotations + +import json +import os +import warnings +from pathlib import Path +from typing import TYPE_CHECKING, Any, Optional, Union + +from huggingface_hub import is_offline_mode, model_info + +from ..configuration_utils import PreTrainedConfig +from ..dynamic_module_utils import get_class_from_dynamic_module +from ..feature_extraction_utils import FeatureExtractionMixin +from ..image_processing_utils import BaseImageProcessor +from ..models.auto.configuration_auto import AutoConfig +from ..models.auto.feature_extraction_auto import FEATURE_EXTRACTOR_MAPPING, AutoFeatureExtractor +from ..models.auto.image_processing_auto import IMAGE_PROCESSOR_MAPPING, AutoImageProcessor +from ..models.auto.modeling_auto import AutoModelForDepthEstimation, AutoModelForImageToImage +from ..models.auto.processing_auto import PROCESSOR_MAPPING, AutoProcessor +from ..models.auto.tokenization_auto import TOKENIZER_MAPPING, AutoTokenizer +from ..processing_utils import ProcessorMixin +from ..tokenization_python import PreTrainedTokenizer +from ..utils import ( + CONFIG_NAME, + cached_file, + extract_commit_hash, + find_adapter_config_file, + is_kenlm_available, + is_peft_available, + is_pyctcdecode_available, + is_torch_available, + logging, +) +from .any_to_any import AnyToAnyPipeline +from .audio_classification import AudioClassificationPipeline +from .automatic_speech_recognition import AutomaticSpeechRecognitionPipeline +from .base import ( + ArgumentHandler, + CsvPipelineDataFormat, + JsonPipelineDataFormat, + PipedPipelineDataFormat, + Pipeline, + PipelineDataFormat, + PipelineException, + PipelineRegistry, + get_default_model_and_revision, + load_model, +) +from .depth_estimation import DepthEstimationPipeline +from .document_question_answering import DocumentQuestionAnsweringPipeline +from .feature_extraction import FeatureExtractionPipeline +from .fill_mask import FillMaskPipeline +from .image_classification import ImageClassificationPipeline +from .image_feature_extraction import ImageFeatureExtractionPipeline +from .image_segmentation import ImageSegmentationPipeline +from .image_text_to_text import ImageTextToTextPipeline +from .keypoint_matching import KeypointMatchingPipeline +from .mask_generation import MaskGenerationPipeline +from .object_detection import ObjectDetectionPipeline +from .table_question_answering import TableQuestionAnsweringArgumentHandler, TableQuestionAnsweringPipeline +from .text_classification import TextClassificationPipeline +from .text_generation import TextGenerationPipeline +from .text_to_audio import TextToAudioPipeline +from .token_classification import ( + AggregationStrategy, + NerPipeline, + TokenClassificationArgumentHandler, + TokenClassificationPipeline, +) +from .video_classification import VideoClassificationPipeline +from .zero_shot_audio_classification import ZeroShotAudioClassificationPipeline +from .zero_shot_classification import ZeroShotClassificationArgumentHandler, ZeroShotClassificationPipeline +from .zero_shot_image_classification import ZeroShotImageClassificationPipeline +from .zero_shot_object_detection import ZeroShotObjectDetectionPipeline + + +if is_torch_available(): + import torch + + from ..models.auto.modeling_auto import ( + AutoModel, + AutoModelForAudioClassification, + AutoModelForCausalLM, + AutoModelForCTC, + AutoModelForDocumentQuestionAnswering, + AutoModelForImageClassification, + AutoModelForImageSegmentation, + AutoModelForImageTextToText, + AutoModelForKeypointMatching, + AutoModelForMaskedLM, + AutoModelForMaskGeneration, + AutoModelForMultimodalLM, + AutoModelForObjectDetection, + AutoModelForQuestionAnswering, + AutoModelForSemanticSegmentation, + AutoModelForSeq2SeqLM, + AutoModelForSequenceClassification, + AutoModelForSpeechSeq2Seq, + AutoModelForTableQuestionAnswering, + AutoModelForTextToSpectrogram, + AutoModelForTextToWaveform, + AutoModelForTokenClassification, + AutoModelForVideoClassification, + AutoModelForVisualQuestionAnswering, + AutoModelForZeroShotImageClassification, + AutoModelForZeroShotObjectDetection, + ) + + +if TYPE_CHECKING: + from ..modeling_utils import PreTrainedModel + from ..tokenization_utils_tokenizers import PreTrainedTokenizerFast + + +logger = logging.get_logger(__name__) + + +# Register all the supported tasks here +TASK_ALIASES = { + "sentiment-analysis": "text-classification", + "ner": "token-classification", + "text-to-speech": "text-to-audio", +} +SUPPORTED_TASKS = { + "audio-classification": { + "impl": AudioClassificationPipeline, + "pt": (AutoModelForAudioClassification,) if is_torch_available() else (), + "default": {"model": ("superb/wav2vec2-base-superb-ks", "372e048")}, + "type": "audio", + }, + "automatic-speech-recognition": { + "impl": AutomaticSpeechRecognitionPipeline, + "pt": (AutoModelForCTC, AutoModelForSpeechSeq2Seq) if is_torch_available() else (), + "default": {"model": ("facebook/wav2vec2-base-960h", "22aad52")}, + "type": "multimodal", + }, + "text-to-audio": { + "impl": TextToAudioPipeline, + "pt": (AutoModelForTextToWaveform, AutoModelForTextToSpectrogram) if is_torch_available() else (), + "default": {"model": ("suno/bark-small", "1dbd7a1")}, + "type": "text", + }, + "feature-extraction": { + "impl": FeatureExtractionPipeline, + "pt": (AutoModel,) if is_torch_available() else (), + "default": {"model": ("distilbert/distilbert-base-cased", "6ea8117")}, + "type": "text", + }, + "text-classification": { + "impl": TextClassificationPipeline, + "pt": (AutoModelForSequenceClassification,) if is_torch_available() else (), + "default": {"model": ("distilbert/distilbert-base-uncased-finetuned-sst-2-english", "714eb0f")}, + "type": "text", + }, + "token-classification": { + "impl": TokenClassificationPipeline, + "pt": (AutoModelForTokenClassification,) if is_torch_available() else (), + "default": {"model": ("dbmdz/bert-large-cased-finetuned-conll03-english", "4c53496")}, + "type": "text", + }, + "table-question-answering": { + "impl": TableQuestionAnsweringPipeline, + "pt": (AutoModelForTableQuestionAnswering,) if is_torch_available() else (), + "default": {"model": ("google/tapas-base-finetuned-wtq", "e3dde19")}, + "type": "text", + }, + "document-question-answering": { + "impl": DocumentQuestionAnsweringPipeline, + "pt": (AutoModelForDocumentQuestionAnswering,) if is_torch_available() else (), + "default": {"model": ("impira/layoutlm-document-qa", "beed3c4")}, + "type": "multimodal", + }, + "fill-mask": { + "impl": FillMaskPipeline, + "pt": (AutoModelForMaskedLM,) if is_torch_available() else (), + "default": {"model": ("distilbert/distilroberta-base", "fb53ab8")}, + "type": "text", + }, + "text-generation": { + "impl": TextGenerationPipeline, + "pt": (AutoModelForCausalLM,) if is_torch_available() else (), + "default": {"model": ("HuggingFaceTB/SmolLM3-3B", "a07cc9a")}, + "type": "text", + }, + "zero-shot-classification": { + "impl": ZeroShotClassificationPipeline, + "pt": (AutoModelForSequenceClassification,) if is_torch_available() else (), + "default": { + "model": ("facebook/bart-large-mnli", "d7645e1"), + "config": ("facebook/bart-large-mnli", "d7645e1"), + }, + "type": "text", + }, + "zero-shot-image-classification": { + "impl": ZeroShotImageClassificationPipeline, + "pt": (AutoModelForZeroShotImageClassification,) if is_torch_available() else (), + "default": {"model": ("openai/clip-vit-base-patch32", "3d74acf")}, + "type": "multimodal", + }, + "zero-shot-audio-classification": { + "impl": ZeroShotAudioClassificationPipeline, + "pt": (AutoModel,) if is_torch_available() else (), + "default": {"model": ("laion/clap-htsat-fused", "cca9e28")}, + "type": "multimodal", + }, + "image-classification": { + "impl": ImageClassificationPipeline, + "pt": (AutoModelForImageClassification,) if is_torch_available() else (), + "default": {"model": ("google/vit-base-patch16-224", "3f49326")}, + "type": "image", + }, + "image-feature-extraction": { + "impl": ImageFeatureExtractionPipeline, + "pt": (AutoModel,) if is_torch_available() else (), + "default": {"model": ("google/vit-base-patch16-224", "3f49326")}, + "type": "image", + }, + "image-segmentation": { + "impl": ImageSegmentationPipeline, + "pt": (AutoModelForImageSegmentation, AutoModelForSemanticSegmentation) if is_torch_available() else (), + "default": {"model": ("facebook/detr-resnet-50-panoptic", "d53b52a")}, + "type": "multimodal", + }, + "image-text-to-text": { + "impl": ImageTextToTextPipeline, + "pt": (AutoModelForImageTextToText,) if is_torch_available() else (), + "default": {"model": ("Qwen/Qwen3-VL-2B-Instruct", "8964489")}, + "type": "multimodal", + }, + "object-detection": { + "impl": ObjectDetectionPipeline, + "pt": (AutoModelForObjectDetection,) if is_torch_available() else (), + "default": {"model": ("facebook/detr-resnet-50", "1d5f47b")}, + "type": "multimodal", + }, + "zero-shot-object-detection": { + "impl": ZeroShotObjectDetectionPipeline, + "pt": (AutoModelForZeroShotObjectDetection,) if is_torch_available() else (), + "default": {"model": ("google/owlvit-base-patch32", "cbc355f")}, + "type": "multimodal", + }, + "depth-estimation": { + "impl": DepthEstimationPipeline, + "pt": (AutoModelForDepthEstimation,) if is_torch_available() else (), + "default": {"model": ("Intel/dpt-large", "bc15f29")}, + "type": "image", + }, + "video-classification": { + "impl": VideoClassificationPipeline, + "pt": (AutoModelForVideoClassification,) if is_torch_available() else (), + "default": {"model": ("MCG-NJU/videomae-base-finetuned-kinetics", "488eb9a")}, + "type": "video", + }, + "mask-generation": { + "impl": MaskGenerationPipeline, + "pt": (AutoModelForMaskGeneration,) if is_torch_available() else (), + "default": {"model": ("facebook/sam-vit-huge", "87aecf0")}, + "type": "multimodal", + }, + "keypoint-matching": { + "impl": KeypointMatchingPipeline, + "pt": (AutoModelForKeypointMatching,) if is_torch_available() else (), + "default": {"model": ("magic-leap-community/superglue_outdoor", "f4041f8")}, + "type": "image", + }, + "any-to-any": { + "impl": AnyToAnyPipeline, + "tf": (), + "pt": (AutoModelForMultimodalLM,) if is_torch_available() else (), + "default": { + "model": { + "pt": ("google/gemma-3n-E4B-it", "c1221e9"), + } + }, + "type": "multimodal", + }, +} + +PIPELINE_REGISTRY = PipelineRegistry(supported_tasks=SUPPORTED_TASKS, task_aliases=TASK_ALIASES) + + +def get_supported_tasks() -> list[str]: + """ + Returns a list of supported task strings. + """ + return PIPELINE_REGISTRY.get_supported_tasks() + + +def get_task(model: str, token: str | None = None, **deprecated_kwargs) -> str: + if is_offline_mode(): + raise RuntimeError("You cannot infer task automatically within `pipeline` when using offline mode") + try: + info = model_info(model, token=token) + except Exception as e: + raise RuntimeError(f"Instantiating a pipeline without a task set raised an error: {e}") + if not info.pipeline_tag: + raise RuntimeError( + f"The model {model} does not seem to have a correct `pipeline_tag` set to infer the task automatically" + ) + if getattr(info, "library_name", "transformers") not in {"transformers", "timm"}: + raise RuntimeError(f"This model is meant to be used with {info.library_name} not with transformers") + task = info.pipeline_tag + return task + + +def check_task(task: str) -> tuple[str, dict, Any]: + """ + Checks an incoming task string, to validate it's correct and return the default Pipeline and Model classes, and + default models if they exist. + + Args: + task (`str`): + The task defining which pipeline will be returned. Currently accepted tasks are: + - `"audio-classification"` + - `"automatic-speech-recognition"` + - `"conversational"` + - `"depth-estimation"` + - `"document-question-answering"` + - `"feature-extraction"` + - `"fill-mask"` + - `"image-classification"` + - `"image-feature-extraction"` + - `"image-segmentation"` + - `"keypoint-matching"` + - `"object-detection"` + - `"table-question-answering"` + - `"text-classification"` (alias `"sentiment-analysis"` available) + - `"text-generation"` + - `"text-to-audio"` (alias `"text-to-speech"` available) + - `"token-classification"` (alias `"ner"` available) + - `"video-classification"` + - `"zero-shot-classification"` + - `"zero-shot-image-classification"` + - `"zero-shot-object-detection"` + + Returns: + (normalized_task: `str`, task_defaults: `dict`, task_options: (`tuple`, None)) The normalized task name + (removed alias and options). + + + """ + return PIPELINE_REGISTRY.check_task(task) + + +def clean_custom_task(task_info): + import transformers + + if "impl" not in task_info: + raise RuntimeError("This model introduces a custom pipeline without specifying its implementation.") + pt_class_names = task_info.get("pt", ()) + if isinstance(pt_class_names, str): + pt_class_names = [pt_class_names] + task_info["pt"] = tuple(getattr(transformers, c) for c in pt_class_names) + return task_info, None + + +# +# fmt: off +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# The part of the file below was automatically generated from the code. +# Do NOT edit this part of the file manually as any edits will be overwritten by the generation +# of the file. If any change should be done, please apply the changes to the `pipeline` function +# below and run `python utils/check_pipeline_typing.py --fix_and_overwrite` to update the file. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 + +from typing import Literal, overload + + +@overload +def pipeline(task: Literal[None], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> Pipeline: ... +@overload +def pipeline(task: Literal["any-to-any"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> AnyToAnyPipeline: ... +@overload +def pipeline(task: Literal["audio-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> AudioClassificationPipeline: ... +@overload +def pipeline(task: Literal["automatic-speech-recognition"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> AutomaticSpeechRecognitionPipeline: ... +@overload +def pipeline(task: Literal["depth-estimation"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> DepthEstimationPipeline: ... +@overload +def pipeline(task: Literal["document-question-answering"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> DocumentQuestionAnsweringPipeline: ... +@overload +def pipeline(task: Literal["feature-extraction"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> FeatureExtractionPipeline: ... +@overload +def pipeline(task: Literal["fill-mask"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> FillMaskPipeline: ... +@overload +def pipeline(task: Literal["image-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ImageClassificationPipeline: ... +@overload +def pipeline(task: Literal["image-feature-extraction"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ImageFeatureExtractionPipeline: ... +@overload +def pipeline(task: Literal["image-segmentation"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ImageSegmentationPipeline: ... +@overload +def pipeline(task: Literal["image-text-to-text"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ImageTextToTextPipeline: ... +@overload +def pipeline(task: Literal["keypoint-matching"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> KeypointMatchingPipeline: ... +@overload +def pipeline(task: Literal["mask-generation"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> MaskGenerationPipeline: ... +@overload +def pipeline(task: Literal["object-detection"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ObjectDetectionPipeline: ... +@overload +def pipeline(task: Literal["table-question-answering"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> TableQuestionAnsweringPipeline: ... +@overload +def pipeline(task: Literal["text-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> TextClassificationPipeline: ... +@overload +def pipeline(task: Literal["text-generation"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> TextGenerationPipeline: ... +@overload +def pipeline(task: Literal["text-to-audio"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> TextToAudioPipeline: ... +@overload +def pipeline(task: Literal["token-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> TokenClassificationPipeline: ... +@overload +def pipeline(task: Literal["video-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> VideoClassificationPipeline: ... +@overload +def pipeline(task: Literal["zero-shot-audio-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ZeroShotAudioClassificationPipeline: ... +@overload +def pipeline(task: Literal["zero-shot-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ZeroShotClassificationPipeline: ... +@overload +def pipeline(task: Literal["zero-shot-image-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ZeroShotImageClassificationPipeline: ... +@overload +def pipeline(task: Literal["zero-shot-object-detection"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ZeroShotObjectDetectionPipeline: ... + +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# The part of the file above was automatically generated from the code. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# fmt: on +# + + +def _load_pipeline_component(load_flag, component, loader): + """Load an optional pipeline component, preserving the original soft-failure behavior.""" + if not (load_flag or load_flag is None): + return component + + try: + return loader(component) + except Exception: + if load_flag: + raise + return None + + +def _infer_pipeline_component( + component, + model_name, + config, + error_message, + fallback_component=None, +): + """Infer a component identifier from explicit input, then model/config fallbacks.""" + if component is not None: + return component + if isinstance(model_name, str): + return model_name + if isinstance(config, str): + return config + if fallback_component is not None: + return fallback_component + raise Exception(error_message) + + +def _get_tokenizer_loading_kwargs(tokenizer, use_fast, model_kwargs): + """Normalize tokenizer tuple/string inputs into `AutoTokenizer.from_pretrained` kwargs.""" + if isinstance(tokenizer, tuple): + tokenizer_identifier = tokenizer[0] + tokenizer_kwargs = tokenizer[1].copy() + tokenizer_use_fast = tokenizer_kwargs.pop("use_fast", use_fast) + else: + tokenizer_identifier = tokenizer + tokenizer_kwargs = model_kwargs.copy() + tokenizer_kwargs.pop("torch_dtype", None) + tokenizer_kwargs.pop("dtype", None) + tokenizer_use_fast = use_fast + + return tokenizer_identifier, tokenizer_kwargs, tokenizer_use_fast + + +def _resolve_tokenizer(tokenizer, load_tokenizer, use_fast, model_name, config, task, hub_kwargs, model_kwargs): + """Resolve and optionally load the tokenizer required by the pipeline class.""" + + def load(tokenizer): + tokenizer = _infer_pipeline_component( + tokenizer, + model_name, + config, + "Impossible to guess which tokenizer to use. " + "Please provide a PreTrainedTokenizer class or a path/identifier to a pretrained tokenizer.", + ) + + if not isinstance(tokenizer, (str, tuple)): + return tokenizer + + tokenizer_identifier, tokenizer_kwargs, tokenizer_use_fast = _get_tokenizer_loading_kwargs( + tokenizer, use_fast, model_kwargs + ) + return AutoTokenizer.from_pretrained( + tokenizer_identifier, + use_fast=tokenizer_use_fast, + _from_pipeline=task, + **hub_kwargs, + **tokenizer_kwargs, + ) + + return _load_pipeline_component(load_tokenizer, tokenizer, load) + + +def _resolve_image_processor( + image_processor, + feature_extractor, + load_image_processor, + model_name, + config, + task, + hub_kwargs, + model_kwargs, +): + """Resolve and optionally load the image processor for vision-capable pipelines.""" + + def load(image_processor): + image_processor = _infer_pipeline_component( + image_processor, + model_name, + config, + "Impossible to guess which image processor to use. " + "Please provide a PreTrainedImageProcessor class or a path/identifier to a pretrained image processor.", + fallback_component=feature_extractor if isinstance(feature_extractor, BaseImageProcessor) else None, + ) + + if not isinstance(image_processor, (str, tuple)): + return image_processor + + return AutoImageProcessor.from_pretrained(image_processor, _from_pipeline=task, **hub_kwargs, **model_kwargs) + + return _load_pipeline_component(load_image_processor, image_processor, load) + + +def _maybe_load_ctc_decoder(model_name, hub_kwargs, kwargs, pretrained_model_name_or_path): + """Attach a pyctcdecode decoder when the loaded feature extractor declares an LM-backed processor.""" + config_dict, _ = FeatureExtractionMixin.get_feature_extractor_dict( + pretrained_model_name_or_path or model_name, + **hub_kwargs, + ) + processor_class = config_dict.get("processor_class", None) + + if processor_class is None or not processor_class.endswith("WithLM") or not isinstance(model_name, str): + return + + try: + import kenlm # to trigger `ImportError` if not installed + from pyctcdecode import BeamSearchDecoderCTC + + if os.path.isdir(model_name) or os.path.isfile(model_name): + decoder = BeamSearchDecoderCTC.load_from_dir(model_name) + else: + language_model_glob = os.path.join(BeamSearchDecoderCTC._LANGUAGE_MODEL_SERIALIZED_DIRECTORY, "*") + alphabet_filename = BeamSearchDecoderCTC._ALPHABET_SERIALIZED_FILENAME + allow_patterns = [language_model_glob, alphabet_filename] + decoder = BeamSearchDecoderCTC.load_from_hf_hub(model_name, allow_patterns=allow_patterns) + + kwargs["decoder"] = decoder + except ImportError as error: + logger.warning(f"Could not load the `decoder` for {model_name}. Defaulting to raw CTC. Error: {error}") + if not is_kenlm_available(): + logger.warning("Try to install `kenlm`: `pip install kenlm") + + if not is_pyctcdecode_available(): + logger.warning("Try to install `pyctcdecode`: `pip install pyctcdecode") + + +def _resolve_feature_extractor( + feature_extractor, + load_feature_extractor, + model_name, + config, + task, + hub_kwargs, + model_kwargs, + kwargs, + pretrained_model_name_or_path, +): + """Resolve and optionally load the feature extractor, including CTC decoder side-loading.""" + + def load(feature_extractor): + feature_extractor = _infer_pipeline_component( + feature_extractor, + model_name, + config, + "Impossible to guess which feature extractor to use. " + "Please provide a PreTrainedFeatureExtractor class or a path/identifier to a pretrained feature extractor.", + ) + + if not isinstance(feature_extractor, (str, tuple)): + return feature_extractor + + feature_extractor = AutoFeatureExtractor.from_pretrained( + feature_extractor, _from_pipeline=task, **hub_kwargs, **model_kwargs + ) + _maybe_load_ctc_decoder(model_name, hub_kwargs, kwargs, pretrained_model_name_or_path) + return feature_extractor + + return _load_pipeline_component(load_feature_extractor, feature_extractor, load) + + +def _resolve_processor(processor, load_processor, model_name, config, task, hub_kwargs, model_kwargs): + """Resolve and optionally load a multimodal processor.""" + + def load(processor): + processor = _infer_pipeline_component( + processor, + model_name, + config, + "Impossible to guess which processor to use. " + "Please provide a processor instance or a path/identifier to a processor.", + ) + + if not isinstance(processor, (str, tuple)): + return processor + + processor = AutoProcessor.from_pretrained(processor, _from_pipeline=task, **hub_kwargs, **model_kwargs) + if not isinstance(processor, ProcessorMixin): + raise TypeError( + "Processor was loaded, but it is not an instance of `ProcessorMixin`. " + f"Got type `{type(processor)}` instead. Please check that you specified " + "correct pipeline task for the model and model has processor implemented and saved." + ) + return processor + + return _load_pipeline_component(load_processor, processor, load) + + +def pipeline( + task: str | None = None, + model: str | PreTrainedModel | None = None, + config: str | PreTrainedConfig | None = None, + tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, + feature_extractor: str | FeatureExtractionMixin | None = None, + image_processor: str | BaseImageProcessor | None = None, + processor: str | ProcessorMixin | None = None, + revision: str | None = None, + use_fast: bool = True, + token: str | bool | None = None, + device: int | str | torch.device | None = None, + device_map: str | dict[str, int | str] | None = None, + dtype: str | torch.dtype | None = "auto", + trust_remote_code: bool | None = None, + model_kwargs: dict[str, Any] | None = None, + pipeline_class: Any | None = None, + **kwargs: Any, +) -> Pipeline: + """ + Utility factory method to build a [`Pipeline`]. + + A pipeline consists of: + + - One or more components for pre-processing model inputs, such as a [tokenizer](tokenizer), + [image_processor](image_processor), [feature_extractor](feature_extractor), or [processor](processors). + - A [model](model) that generates predictions from the inputs. + - Optional post-processing steps to refine the model's output, which can also be handled by processors. + + + While there are such optional arguments as `tokenizer`, `feature_extractor`, `image_processor`, and `processor`, + they shouldn't be specified all at once. If these components are not provided, `pipeline` will try to load + required ones automatically. In case you want to provide these components explicitly, please refer to a + specific pipeline in order to get more details regarding what components are required. + + + Args: + task (`str`): + The task defining which pipeline will be returned. Currently accepted tasks are: + + - `"audio-classification"`: will return a [`AudioClassificationPipeline`]. + - `"automatic-speech-recognition"`: will return a [`AutomaticSpeechRecognitionPipeline`]. + - `"depth-estimation"`: will return a [`DepthEstimationPipeline`]. + - `"document-question-answering"`: will return a [`DocumentQuestionAnsweringPipeline`]. + - `"feature-extraction"`: will return a [`FeatureExtractionPipeline`]. + - `"fill-mask"`: will return a [`FillMaskPipeline`]:. + - `"image-classification"`: will return a [`ImageClassificationPipeline`]. + - `"image-feature-extraction"`: will return an [`ImageFeatureExtractionPipeline`]. + - `"image-segmentation"`: will return a [`ImageSegmentationPipeline`]. + - `"image-text-to-text"`: will return a [`ImageTextToTextPipeline`]. + - `"keypoint-matching"`: will return a [`KeypointMatchingPipeline`]. + - `"mask-generation"`: will return a [`MaskGenerationPipeline`]. + - `"object-detection"`: will return a [`ObjectDetectionPipeline`]. + - `"table-question-answering"`: will return a [`TableQuestionAnsweringPipeline`]. + - `"text-classification"` (alias `"sentiment-analysis"` available): will return a + [`TextClassificationPipeline`]. + - `"text-generation"`: will return a [`TextGenerationPipeline`]:. + - `"text-to-audio"` (alias `"text-to-speech"` available): will return a [`TextToAudioPipeline`]:. + - `"token-classification"` (alias `"ner"` available): will return a [`TokenClassificationPipeline`]. + - `"video-classification"`: will return a [`VideoClassificationPipeline`]. + - `"zero-shot-classification"`: will return a [`ZeroShotClassificationPipeline`]. + - `"zero-shot-image-classification"`: will return a [`ZeroShotImageClassificationPipeline`]. + - `"zero-shot-audio-classification"`: will return a [`ZeroShotAudioClassificationPipeline`]. + - `"zero-shot-object-detection"`: will return a [`ZeroShotObjectDetectionPipeline`]. + + model (`str` or [`PreTrainedModel`], *optional*): + The model that will be used by the pipeline to make predictions. This can be a model identifier or an + actual instance of a pretrained model inheriting from [`PreTrainedModel`]. + + If not provided, the default for the `task` will be loaded. + config (`str` or [`PreTrainedConfig`], *optional*): + The configuration that will be used by the pipeline to instantiate the model. This can be a model + identifier or an actual pretrained model configuration inheriting from [`PreTrainedConfig`]. + + If not provided, the default configuration file for the requested model will be used. That means that if + `model` is given, its default configuration will be used. However, if `model` is not supplied, this + `task`'s default model's config is used instead. + tokenizer (`str` or [`PreTrainedTokenizer`], *optional*): + The tokenizer that will be used by the pipeline to encode data for the model. This can be a model + identifier or an actual pretrained tokenizer inheriting from [`PreTrainedTokenizer`]. + + If not provided, the default tokenizer for the given `model` will be loaded (if it is a string). If `model` + is not specified or not a string, then the default tokenizer for `config` is loaded (if it is a string). + However, if `config` is also not given or not a string, then the default tokenizer for the given `task` + will be loaded. + feature_extractor (`str` or [`FeatureExtractionMixin`], *optional*): + The feature extractor that will be used by the pipeline to encode data for the model. This can be a model + identifier or an actual pretrained feature extractor inheriting from [`FeatureExtractionMixin`]. + + Feature extractors are used for non-NLP models, such as Speech or Vision models as well as multi-modal + models. Multi-modal models will also require a tokenizer to be passed. + + If not provided, the default feature extractor for the given `model` will be loaded (if it is a string). If + `model` is not specified or not a string, then the default feature extractor for `config` is loaded (if it + is a string). However, if `config` is also not given or not a string, then the default feature extractor + for the given `task` will be loaded. + image_processor (`str` or [`BaseImageProcessor`], *optional*): + The image processor that will be used by the pipeline to preprocess images for the model. This can be a + model identifier or an actual image processor inheriting from [`BaseImageProcessor`]. + + Image processors are used for Vision models and multi-modal models that require image inputs. Multi-modal + models will also require a tokenizer to be passed. + + If not provided, the default image processor for the given `model` will be loaded (if it is a string). If + `model` is not specified or not a string, then the default image processor for `config` is loaded (if it is + a string). + processor (`str` or [`ProcessorMixin`], *optional*): + The processor that will be used by the pipeline to preprocess data for the model. This can be a model + identifier or an actual processor inheriting from [`ProcessorMixin`]. + + Processors are used for multi-modal models that require multi-modal inputs, for example, a model that + requires both text and image inputs. + + If not provided, the default processor for the given `model` will be loaded (if it is a string). If `model` + is not specified or not a string, then the default processor for `config` is loaded (if it is a string). + revision (`str`, *optional*, defaults to `"main"`): + When passing a task name or a string model identifier: The specific model version to use. It can be a + branch name, a tag name, or a commit id, since we use a git-based system for storing models and other + artifacts on huggingface.co, so `revision` can be any identifier allowed by git. + use_fast (`bool`, *optional*, defaults to `True`): + Whether or not to use a Fast tokenizer if possible (a [`PreTrainedTokenizerFast`]). + token (`str` or *bool*, *optional*): + The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated + when running `hf auth login`. + device (`int` or `str` or `torch.device`): + Defines the device (*e.g.*, `"cpu"`, `"cuda:1"`, `"mps"`, or a GPU ordinal rank like `1`) on which this + pipeline will be allocated. + device_map (`str` or `dict[str, Union[int, str, torch.device]`, *optional*): + Sent directly as `model_kwargs` (just a simpler shortcut). When `accelerate` library is present, set + `device_map="auto"` to compute the most optimized `device_map` automatically (see + [here](https://huggingface.co/docs/accelerate/main/en/package_reference/big_modeling#accelerate.cpu_offload) + for more information). + + + + Do not use `device_map` AND `device` at the same time as they will conflict + + + + dtype (`str` or `torch.dtype`, *optional*): + Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model + (`torch.float16`, `torch.bfloat16`, ... or `"auto"`). + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether or not to allow for custom code defined on the Hub in their own modeling, configuration, + tokenization or even pipeline files. This option should only be set to `True` for repositories you trust + and in which you have read the code, as it will execute code present on the Hub on your local machine. + model_kwargs (`dict[str, Any]`, *optional*): + Additional dictionary of keyword arguments passed along to the model's `from_pretrained(..., + **model_kwargs)` function. + kwargs (`dict[str, Any]`, *optional*): + Additional keyword arguments passed along to the specific pipeline init (see the documentation for the + corresponding pipeline class for possible values). + + Returns: + [`Pipeline`]: A suitable pipeline for the task. + + Examples: + + ```python + >>> from transformers import pipeline, AutoModelForTokenClassification, AutoTokenizer + + >>> # Sentiment analysis pipeline + >>> analyzer = pipeline("sentiment-analysis") + + >>> # Named entity recognition pipeline, passing in a specific model and tokenizer + >>> model = AutoModelForTokenClassification.from_pretrained("dbmdz/bert-large-cased-finetuned-conll03-english") + >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased") + >>> recognizer = pipeline("ner", model=model, tokenizer=tokenizer) + ```""" + if model_kwargs is None: + model_kwargs = {} + + code_revision = kwargs.pop("code_revision", None) + commit_hash = kwargs.pop("_commit_hash", None) + local_files_only = kwargs.get("local_files_only", False) + + hub_kwargs = { + "revision": revision, + "token": token, + "trust_remote_code": trust_remote_code, + "_commit_hash": commit_hash, + "local_files_only": local_files_only, + } + + if task is None and model is None: + raise RuntimeError( + "Impossible to instantiate a pipeline without either a task or a model " + "being specified. " + "Please provide a task class or a model" + ) + + if model is None and tokenizer is not None: + raise RuntimeError( + "Impossible to instantiate a pipeline with tokenizer specified but not the model as the provided tokenizer" + " may not be compatible with the default model. Please provide a PreTrainedModel class or a" + " path/identifier to a pretrained model when providing tokenizer." + ) + if model is None and feature_extractor is not None: + raise RuntimeError( + "Impossible to instantiate a pipeline with feature_extractor specified but not the model as the provided" + " feature_extractor may not be compatible with the default model. Please provide a PreTrainedModel class" + " or a path/identifier to a pretrained model when providing feature_extractor." + ) + if isinstance(model, Path): + model = str(model) + + pretrained_model_name_or_path = None + if commit_hash is None: + if isinstance(config, str): + pretrained_model_name_or_path = config + elif config is None and isinstance(model, str): + pretrained_model_name_or_path = model + + if not isinstance(config, PreTrainedConfig) and pretrained_model_name_or_path is not None: + # We make a call to the config file first (which may be absent) to get the commit hash as soon as possible + resolved_config_file = cached_file( + pretrained_model_name_or_path, + CONFIG_NAME, + _raise_exceptions_for_gated_repo=False, + _raise_exceptions_for_missing_entries=False, + _raise_exceptions_for_connection_errors=False, + cache_dir=model_kwargs.get("cache_dir"), + **hub_kwargs, + ) + hub_kwargs["_commit_hash"] = extract_commit_hash(resolved_config_file, commit_hash) + else: + hub_kwargs["_commit_hash"] = getattr(config, "_commit_hash", None) + + # Config is the primordial information item. + # Instantiate config if needed + adapter_path = None + if isinstance(config, str): + config = AutoConfig.from_pretrained( + config, _from_pipeline=task, code_revision=code_revision, **hub_kwargs, **model_kwargs + ) + hub_kwargs["_commit_hash"] = config._commit_hash + elif config is None and isinstance(model, str): + # Check for an adapter file in the model path if PEFT is available + if is_peft_available(): + # `find_adapter_config_file` doesn't accept `trust_remote_code` + _hub_kwargs = {k: v for k, v in hub_kwargs.items() if k != "trust_remote_code"} + maybe_adapter_path = find_adapter_config_file( + model, + token=hub_kwargs["token"], + revision=hub_kwargs["revision"], + _commit_hash=hub_kwargs["_commit_hash"], + ) + + if maybe_adapter_path is not None: + with open(maybe_adapter_path, "r", encoding="utf-8") as f: + adapter_config = json.load(f) + adapter_path = model + # Only override the model name/path if the current value doesn't point to a + # complete model with an embedded adapter so that local models with embedded + # adapters will load from the local base model rather than pull the base + # model named in the adapter's config from the hub. + if not os.path.exists(model) or not os.path.exists(os.path.join(model, CONFIG_NAME)): + model = adapter_config["base_model_name_or_path"] + + config = AutoConfig.from_pretrained( + model, _from_pipeline=task, code_revision=code_revision, **hub_kwargs, **model_kwargs + ) + hub_kwargs["_commit_hash"] = config._commit_hash + + custom_tasks = {} + if config is not None and len(getattr(config, "custom_pipelines", {})) > 0: + custom_tasks = config.custom_pipelines + if task is None and trust_remote_code is not False: + if len(custom_tasks) == 1: + task = list(custom_tasks.keys())[0] + else: + raise RuntimeError( + "We can't infer the task automatically for this model as there are multiple tasks available. Pick " + f"one in {', '.join(custom_tasks.keys())}" + ) + + if task is None and model is not None: + if not isinstance(model, str): + raise RuntimeError( + "Inferring the task automatically requires to check the hub with a model_id defined as a `str`. " + f"{model} is not a valid model_id." + ) + task = get_task(model, token) + + # Retrieve the task + if task in custom_tasks: + targeted_task, task_options = clean_custom_task(custom_tasks[task]) + if pipeline_class is None: + if not trust_remote_code: + raise ValueError( + "Loading this pipeline requires you to execute the code in the pipeline file in that" + " repo on your local machine. Make sure you have read the code there to avoid malicious use, then" + " set the option `trust_remote_code=True` to remove this error." + ) + class_ref = targeted_task["impl"] + pipeline_class = get_class_from_dynamic_module( + class_ref, + model, + code_revision=code_revision, + **hub_kwargs, + ) + else: + normalized_task, targeted_task, task_options = check_task(task) + if pipeline_class is None: + pipeline_class = targeted_task["impl"] + + # Use default model/config/tokenizer for the task if no model is provided + if model is None: + model, default_revision = get_default_model_and_revision(targeted_task, task_options) + revision = revision if revision is not None else default_revision + logger.warning( + f"No model was supplied, defaulted to {model} and revision {revision}.\n" + "Using a pipeline without specifying a model name and revision in production is not recommended." + ) + hub_kwargs["revision"] = revision + if config is None and isinstance(model, str): + config = AutoConfig.from_pretrained(model, _from_pipeline=task, **hub_kwargs, **model_kwargs) + hub_kwargs["_commit_hash"] = config._commit_hash + + if device_map is not None: + if "device_map" in model_kwargs: + raise ValueError( + 'You cannot use both `pipeline(... device_map=..., model_kwargs={"device_map":...})` as those' + " arguments might conflict, use only one.)" + ) + if device is not None: + logger.warning( + "Both `device` and `device_map` are specified. `device` will override `device_map`. You" + " will most likely encounter unexpected behavior. Please remove `device` and keep `device_map`." + ) + model_kwargs["device_map"] = device_map + + # BC for the `torch_dtype` argument + if (torch_dtype := kwargs.get("torch_dtype")) is not None: + logger.warning_once("`torch_dtype` is deprecated! Use `dtype` instead!") + # If both are provided, keep `dtype` + dtype = torch_dtype if dtype == "auto" else dtype + if "torch_dtype" in model_kwargs or "dtype" in model_kwargs: + if "torch_dtype" in model_kwargs: + logger.warning_once("`torch_dtype` is deprecated! Use `dtype` instead!") + # If the user did not explicitly provide `dtype` (i.e. the function default "auto" is still + # present) but a value is supplied inside `model_kwargs`, we silently defer to the latter instead of + # raising. This prevents false positives like providing `dtype` only via `model_kwargs` while the + # top-level argument keeps its default value "auto". + if dtype == "auto": + dtype = None + else: + raise ValueError( + 'You cannot use both `pipeline(... dtype=..., model_kwargs={"dtype":...})` as those' + " arguments might conflict, use only one.)" + ) + if dtype is not None: + if isinstance(dtype, str) and hasattr(torch, dtype): + dtype = getattr(torch, dtype) + model_kwargs["dtype"] = dtype + + model_name = model if isinstance(model, str) else None + + # Load the correct model if possible + if isinstance(model, str): + model_classes = targeted_task["pt"] + model = load_model( + adapter_path if adapter_path is not None else model, + model_classes=model_classes, + config=config, + task=task, + **hub_kwargs, + **model_kwargs, + ) + + hub_kwargs["_commit_hash"] = model.config._commit_hash + + if pipeline_class is None: + raise RuntimeError("Failed to resolve a pipeline class.") + + load_tokenizer = getattr(pipeline_class, "_load_tokenizer") + load_image_processor = getattr(pipeline_class, "_load_image_processor") + load_feature_extractor = getattr(pipeline_class, "_load_feature_extractor") + load_processor = getattr(pipeline_class, "_load_processor") + + tokenizer = _resolve_tokenizer( + tokenizer=tokenizer, + load_tokenizer=load_tokenizer, + use_fast=use_fast, + model_name=model_name, + config=config, + task=task, + hub_kwargs=hub_kwargs, + model_kwargs=model_kwargs, + ) + image_processor = _resolve_image_processor( + image_processor=image_processor, + feature_extractor=feature_extractor, + load_image_processor=load_image_processor, + model_name=model_name, + config=config, + task=task, + hub_kwargs=hub_kwargs, + model_kwargs=model_kwargs, + ) + feature_extractor = _resolve_feature_extractor( + feature_extractor=feature_extractor, + load_feature_extractor=load_feature_extractor, + model_name=model_name, + config=config, + task=task, + hub_kwargs=hub_kwargs, + model_kwargs=model_kwargs, + kwargs=kwargs, + pretrained_model_name_or_path=pretrained_model_name_or_path, + ) + processor = _resolve_processor( + processor=processor, + load_processor=load_processor, + model_name=model_name, + config=config, + task=task, + hub_kwargs=hub_kwargs, + model_kwargs=model_kwargs, + ) + + if tokenizer is not None: + kwargs["tokenizer"] = tokenizer + + if feature_extractor is not None: + kwargs["feature_extractor"] = feature_extractor + + if dtype is not None: + kwargs["dtype"] = dtype + + if image_processor is not None: + kwargs["image_processor"] = image_processor + + if device is not None: + kwargs["device"] = device + + if processor is not None: + kwargs["processor"] = processor + + return pipeline_class(model=model, task=task, **kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01929afaeaf7aede65517e1f6c485b3a1cee4dd1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/any_to_any.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/any_to_any.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d347f3454d8861d95f6dac87f4871261d4564902 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/any_to_any.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/audio_classification.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/audio_classification.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..666ea5b746119eb78e715a5e9313f668c312ab0c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/audio_classification.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/audio_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/audio_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f087d148a7815a18df82784ee40ee847ed569448 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/audio_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/automatic_speech_recognition.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/automatic_speech_recognition.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..023cd4177dd49c5de1750ec5f7c6886c4145f4cc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/automatic_speech_recognition.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05e9715d0607fd8c7666732d1230c38fd7cb24ca Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/base.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/depth_estimation.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/depth_estimation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..acdbc91f61af36dfbda623259235125fc64b0703 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/depth_estimation.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/document_question_answering.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/document_question_answering.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2730e05fd58d962001085f758ec384f1cb6e8924 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/document_question_answering.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/feature_extraction.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/feature_extraction.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb940b6ff9da980e390b8d66f24fd515a4fb61ac Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/feature_extraction.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/fill_mask.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/fill_mask.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cc065e8dbfd20b5519cc14a9051d30f2d7ac408 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/fill_mask.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/image_classification.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/image_classification.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3213747d97ce92f73d822475539a511e4835b8dd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/image_classification.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/image_feature_extraction.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/image_feature_extraction.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea35d30200b20a6ecf47b8ed668201c6f1e553ab Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/image_feature_extraction.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/image_segmentation.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/image_segmentation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3852c4906b6d28dc4e4fc023e2eafebc9b89b05d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/image_segmentation.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/image_text_to_text.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/image_text_to_text.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db863adac1ee0992ef2e3a1790dc8cdd01f61302 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/image_text_to_text.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/keypoint_matching.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/keypoint_matching.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64ae278b9c23c146442650c5e38f10cacbc72cd9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/keypoint_matching.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/mask_generation.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/mask_generation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc3c90e62c5b8c0e3dae85250868894f23474c80 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/mask_generation.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/object_detection.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/object_detection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35214486817589ea0221240622c31216c130b565 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/object_detection.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/pt_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/pt_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e52e76c4af5d50bdb5511c451754baaddd99b5ce Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/pt_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/table_question_answering.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/table_question_answering.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b68bf45c5b147558fbe2ff19fd014827c7bf3ac Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/table_question_answering.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/text_classification.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/text_classification.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8296b911a02141facbdeebda7e41a6bbbb87c1ed Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/text_classification.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/text_generation.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/text_generation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b319d4c98576f0a70870656374818352ce108102 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/text_generation.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/text_to_audio.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/text_to_audio.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5e8a96d9cdfa259c9a717a6c2d359906bca6990 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/text_to_audio.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/token_classification.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/token_classification.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6de4183c30da6532994fc2517541b9b049a77667 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/token_classification.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/video_classification.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/video_classification.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4825e2ac9c7134ebfdf7ec28205e2c913f75ef13 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/video_classification.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/zero_shot_audio_classification.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/zero_shot_audio_classification.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91904324c1b8f77a56d47d54524e0c4893eddb24 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/zero_shot_audio_classification.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/zero_shot_classification.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/zero_shot_classification.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c76b213eba1726716713988d6552f6163bc16a41 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/zero_shot_classification.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/zero_shot_image_classification.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/zero_shot_image_classification.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..467a3785df558244a9103f5675eae1ef2acc892e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/zero_shot_image_classification.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/zero_shot_object_detection.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/zero_shot_object_detection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24acf6d4394d8bf6b3e517395d410aad5086d394 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/zero_shot_object_detection.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/any_to_any.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/any_to_any.py new file mode 100644 index 0000000000000000000000000000000000000000..4ae91d5a176f19ab0aec3ab042be1d8c45030c47 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/any_to_any.py @@ -0,0 +1,514 @@ +# Copyright 2025 The HuggingFace Inc. team. All rights reserved. +# +# 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. + +import enum +import re +from typing import Any, Union, overload + +import numpy as np + +from ..audio_utils import AudioInput +from ..generation import GenerationConfig +from ..image_utils import ImageInput +from ..processing_utils import ProcessingKwargs, Unpack +from ..utils import ( + add_end_docstrings, + is_torch_available, + is_vision_available, + logging, + requires_backends, +) +from ..video_utils import VideoInput +from .base import Pipeline, build_pipeline_init_args + + +if is_torch_available(): + import torch + + from ..models.auto.modeling_auto import MODEL_FOR_MULTIMODAL_LM_MAPPING_NAMES + from .pt_utils import KeyDataset + +if is_vision_available(): + from PIL import Image + +logger = logging.get_logger(__name__) + + +class ReturnType(enum.Enum): + TENSORS = 0 + NEW_TEXT = 1 + FULL_TEXT = 2 + + +class Chat: + """This class is intended to just be used internally in this pipeline and not exposed to users. We convert chats + to this format because the rest of the pipeline code tends to assume that lists of messages are + actually a batch of samples rather than messages in the same conversation.""" + + def __init__(self, messages: list[dict]): + for message in messages: + if not ("role" in message and "content" in message): + raise ValueError("When passing chat dicts as input, each dict must have a 'role' and 'content' key.") + self.messages = messages + + +@add_end_docstrings(build_pipeline_init_args(has_processor=True)) +class AnyToAnyPipeline(Pipeline): + """ + Multimodal Generation pipeline using an `AutoModelForMultimodalLM`. This pipeline generates text given any + combination of multimodal data and text.When the underlying model is a conversational model, it can also + accept one or more chats, in which case the pipeline will operate in chat mode and will continue the + chat(s) by adding its response(s). Each chat takes the form of a list of dicts, where each dict contains + "role" and "content" keys. + + Unless the model you're using explicitly sets these generation parameters in its configuration files + (`generation_config.json`), the following default values will be used: + - max_new_tokens: 256 + + Example: + + ```python + >>> from transformers import pipeline + + >>> pipe = pipeline(task="any-to-any", model="google/gemma-3n-E4B-it") + >>> pipe("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", text="A photo of") + [{'generated_text': 'a photo of two birds'}] + ``` + + ```python + >>> from transformers import pipeline + + >>> pipe = pipeline("any-to-any", model="google/gemma-3n-E4B-it") + >>> messages = [ + >>> { + >>> "role": "user", + >>> "content": [ + >>> { + >>> "type": "image", + >>> "url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg", + >>> }, + >>> {"type": "text", "text": "Describe this image."}, + >>> ], + >>> }, + >>> { + >>> "role": "assistant", + >>> "content": [ + >>> {"type": "text", "text": "There is a dog and"}, + >>> ], + >>> }, + >>> ] + >>> pipe(text=messages, max_new_tokens=20, return_full_text=False) + [{'input_text': [{'role': 'user', + 'content': [{'type': 'image', + 'url': 'https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg'}, + {'type': 'text', 'text': 'Describe this image.'}]}, + {'role': 'assistant', + 'content': [{'type': 'text', 'text': 'There is a dog and'}]}], + 'generated_text': ' a person in the image. The dog is sitting on the sand, and the person is sitting on'}] + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) + + This multimodal pipeline can currently be loaded from pipeline() using the following task identifier: + "any-to-any". + + See the list of available models on + [huggingface.co/models](https://huggingface.co/models?pipeline_tag=any-to-any). + """ + + _load_processor = True + _load_image_processor = False + _load_feature_extractor = False + _load_tokenizer = False + + _pipeline_calls_generate = True + # Make sure the docstring is updated when the default generation config is changed + _default_generation_config = GenerationConfig( + max_new_tokens=256, + ) + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if "image" in self.model.input_modalities or "video" in self.model.input_modalities: + requires_backends(self, "vision") + requires_backends(self, "torchvision") + if "audio" in self.model.input_modalities: + requires_backends(self, "librosa") + self.check_model_type(MODEL_FOR_MULTIMODAL_LM_MAPPING_NAMES) + + def _sanitize_parameters( + self, + max_new_tokens=None, + generate_kwargs=None, + timeout=None, + return_full_text=None, + return_tensors=None, + return_type=None, + clean_up_tokenization_spaces=None, + stop_sequence=None, + continue_final_message=None, + skip_special_tokens=None, + generation_mode=None, + processor_kwargs=None, + **kwargs: Unpack[ProcessingKwargs], + ): + forward_kwargs = {} + preprocess_params = {} + postprocess_params = {} + + # Preprocess params + preprocess_params.update(kwargs) + if timeout is not None: + preprocess_params["timeout"] = timeout + if continue_final_message is not None: + preprocess_params["continue_final_message"] = continue_final_message + if processor_kwargs is not None: + preprocess_params["processor_kwargs"] = processor_kwargs + + # Forward kwargs + forward_kwargs["generate_kwargs"] = generate_kwargs or {} + if generation_mode is not None and generation_mode != "text": + forward_kwargs["generate_kwargs"]["generation_mode"] = generation_mode + # Qwen-Omni models need to know the origin of audio, to align mm position ids + if kwargs.get("load_audio_from_video") and re.search(r"qwen\domni", self.model.__class__.__name__.lower()): + forward_kwargs["generate_kwargs"]["use_audio_in_video"] = True + if stop_sequence is not None: + if isinstance(stop_sequence, str): + stop_sequence = [stop_sequence] + forward_kwargs["generate_kwargs"]["stop_strings"] = stop_sequence + forward_kwargs["generate_kwargs"]["tokenizer"] = self.processor.tokenizer + + if max_new_tokens is not None: + if generate_kwargs is not None and "max_new_tokens" in generate_kwargs: + raise ValueError( + "'max_new_tokens' is defined twice, once in 'generate_kwargs' and " + "once as a direct argument. Please use only one." + ) + forward_kwargs["generate_kwargs"]["max_new_tokens"] = max_new_tokens + + if return_full_text is not None and return_type is None: + if return_tensors is not None: + raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`") + return_type = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT + elif return_tensors is not None and return_type is None: + return_type = ReturnType.TENSORS + # We don't want to set the global default to FULLTEXT at init time. That is why + # `_postprocess_params` is checked before setting the default value + elif return_type is None and generation_mode in [None, "text"] and hasattr(self, "_postprocess_params"): + return_type = ReturnType.FULL_TEXT + + # Postprocess params + if generation_mode not in [None, "text"] and return_type is not None: + raise ValueError( + f"`return_type` cannot be set to {return_type} when generation_mode={generation_mode}. " + "Set `return_type=None` or generation_mode='text'" + ) + if generation_mode not in [None, "text", "image", "audio"]: + raise ValueError( + f"`generation_mode` can be only one of the `text`, `audio`, `image` but got generation_mode[={generation_mode}]" + ) + elif generation_mode is not None and generation_mode not in self.model.output_modalities: + raise ValueError( + f"`generation_mode={generation_mode}` is not supported for {self.model.__class__.__name__}. " + f"The model can only output the following modalities: {self.model.output_modalities}" + ) + + if return_type is not None: + postprocess_params["return_type"] = return_type + if continue_final_message is not None: + postprocess_params["continue_final_message"] = continue_final_message + if clean_up_tokenization_spaces is not None: + postprocess_params["clean_up_tokenization_spaces"] = clean_up_tokenization_spaces + if skip_special_tokens is not None: + postprocess_params["skip_special_tokens"] = skip_special_tokens + postprocess_params["generation_mode"] = generation_mode + return preprocess_params, forward_kwargs, postprocess_params + + @overload + def __call__( + self, + text: str | None = None, + images: Union[str, "Image.Image"] | None = None, + videos: Union[str, "np.ndarray", "torch.Tensor"] | None = None, + audio: Union[str, "np.ndarray"] | None = None, + **kwargs: Any, + ) -> list[dict[str, Any]]: ... + + @overload + def __call__( + self, + text: list[str] | None = None, + images: list[str] | list["Image.Image"] | None = None, + videos: list[str] | list["np.ndarray"] | list["torch.Tensor"] | None = None, + audio: list[str] | list["np.ndarray"] | None = None, + **kwargs: Any, + ) -> list[list[dict[str, Any]]]: ... + + def __call__( + self, + text: str | list[str] | list[dict], + images: str | list[str] | list[list[str]] | ImageInput | None = None, + videos: str | list[str] | VideoInput | None = None, + audio: str | list[str] | AudioInput | None = None, + **kwargs, + ) -> list[dict[str, Any]] | list[list[dict[str, Any]]]: + """ + Generate a text given text and optionally multimodal data passed as inputs. + + Args: + text (`str`, `list[str]`, `list[dict]`): + The text to be used for generation. If a list of strings is passed, the length of the list should be + the same as the number of images. Text can also follow the chat format: a list of dictionaries where + each dictionary represents a message in a conversation. Each dictionary should have two keys: 'role' + and 'content'. 'role' should be one of 'user', 'system' or 'assistant'. 'content' should be a list of + dictionary containing the text of the message and the type of the message. + images (`str`, `list[str]`, `ImageInput`): + The pipeline handles three types of images: + + - A string containing a HTTP(s) link pointing to an image + - A string containing a local path to an image + - An image loaded in PIL directly + + The pipeline accepts either a single image or a batch of images. Finally, this pipeline also supports + the chat format (see `text`) containing images and text in this argument. + videos (`str`, `list[str]`, `VideoInput`): + The pipeline handles three types of videos: + + - A string containing a HTTP(s) link pointing to a video + - A string containing a local path to a video + - A video loaded and decoded to array format + + The pipeline accepts either a single video or a batch of videos. Finally, this pipeline also supports + the chat format (see `text`) containing videos and text in this argument. + audio (`str`, `list[str]`, `AudioInput`): + The pipeline handles three types of audios: + + - A string containing a HTTP(s) link pointing to an audio + - A string containing a local path to an audio + - An audio loaded in PIL directly + + The pipeline accepts either a single audios or a batch of audios. Finally, this pipeline also supports + the chat format (see `text`) containing audios and text in this argument. + return_tensors (`bool`, *optional*, defaults to `False`): + Returns the tensors of predictions (as token indices) in the outputs. If set to + `True`, the decoded text is not returned. + return_text (`bool`, *optional*): + Returns the decoded texts in the outputs. + return_full_text (`bool`, *optional*, defaults to `True`): + If set to `False` only added text is returned, otherwise the full text is returned. Cannot be + specified at the same time as `return_text`. + clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`): + Whether or not to clean up the potential extra spaces in the text output. + continue_final_message( `bool`, *optional*): This indicates that you want the model to continue the + last message in the input chat rather than starting a new one, allowing you to "prefill" its response. + By default this is `True` when the final message in the input chat has the `assistant` role and + `False` otherwise, but you can manually override that behaviour by setting this flag. + + Return: + A list or a list of list of `dict`: Each result comes as a dictionary with the following key (cannot + return a combination of both `generated_text` and `generated_token_ids`): + + - **generated_text** (`str`, present when `return_text=True` and `generation_mode="text"`) -- The generated text. + - **generated_audio** (`np.ndarray`, present when `generation_mode="audio"`) -- The generated audio. + - **generated_image** (`PIL.Image.Image`, present when `generation_mode="image"`) -- The generated image. + - **generated_token_ids** (`torch.Tensor`, present when `return_tensors=True` and `generation_mode="text"`) -- The token + ids of the generated text. + - **input_text** (`str`) -- The input text. + """ + if images is None and text is None: + raise ValueError("You must at least provide either text or images.") + + if isinstance(text, (list, tuple, KeyDataset)) and isinstance(text[0], (list, tuple, dict)): + # We have one or more prompts in list-of-dicts format, so this is chat mode + if isinstance(text[0], dict) and "role" in text[0]: + return super().__call__(Chat(text), **kwargs) + elif isinstance(text[0], (list, tuple)) and isinstance(text[0][0], dict) and "role" in text[0][0]: + chats = [Chat(chat) for chat in text] # 🐈 🐈 🐈 + return super().__call__(chats, **kwargs) + + if text is not None and not (isinstance(text, str) or (isinstance(text, list) and isinstance(text[0], str))): + """ + Supports the following format + - {"text": text, "image": image, "video": video, "audio": audio} + - [{"text": text, "image": image, "video": video, "audio": audio}] + - Generator and datasets + This is a common pattern in other multimodal pipelines, so we support it here as well. + """ + return super().__call__(text, **kwargs) + + # encourage the user to use the chat format if supported + if getattr(self.processor, "chat_template", None) is not None: + logger.warning_once( + "The input data was not formatted as a chat with dicts containing 'role' and 'content' keys, even " + "though this model supports chat. Consider using the chat format for better results. For more " + "information, see https://huggingface.co/docs/transformers/en/chat_templating" + ) + + return super().__call__({"text": text, "images": images, "video": videos, "audio": audio}, **kwargs) + + def preprocess(self, inputs=None, timeout=None, continue_final_message=None, **processing_kwargs): + if isinstance(inputs, Chat): + # If the user passes a chat that ends in an assistant message, we treat it as a prefill by default + # because very few models support multiple separate, consecutive assistant messages + if continue_final_message is None: + continue_final_message = inputs.messages[-1]["role"] == "assistant" + + # Processor kwargs are passed separately from jinja kwargs to chat template + # but it was added only in https://github.com/huggingface/transformers/pull/44881 + processor_kwargs = processing_kwargs.pop("processor_kwargs", None) or {} + + chat_template_kwargs = { + "continue_final_message": continue_final_message, + "return_tensors": "pt", + "tokenize": True, + "return_dict": True, + "add_generation_prompt": not continue_final_message, + "processor_kwargs": processor_kwargs, + **processing_kwargs, + } + + # Handle Mistral tokenizer which does not accept processing kwargs + if self.processor.tokenizer.__class__.__name__ == "MistralCommonBackend": + chat_template_kwargs = { + k: v for k, v in chat_template_kwargs.items() if k in ["padding", "truncation", "max_length"] + } + + model_inputs = self.processor.apply_chat_template( + inputs.messages, + **chat_template_kwargs, + ).to(dtype=self.dtype) + model_inputs["text"] = inputs + return model_inputs + + # In case we only have text inputs + if isinstance(inputs, (list, tuple, str)): + text = inputs + inputs = {} + else: + inputs = inputs.copy() # avoid in-place changes if users passed dict + text = inputs.pop("text") + + # Feature extractor do not load audio files and expect a decoded array + if inputs.get("audio", None) is not None and hasattr(self.processor, "feature_extractor"): + inputs["audio"] = self.processor.feature_extractor.fetch_audio(inputs["audio"]) + + # If batched text inputs, we set padding to True unless specified otherwise + processor_kwargs = processing_kwargs.pop("processor_kwargs", None) or processing_kwargs + if isinstance(text, (list, tuple)) and len(text) > 1: + processor_kwargs.setdefault("padding", True) + model_inputs = self.processor(text=text, **inputs, return_tensors="pt", **processor_kwargs).to( + dtype=self.dtype + ) + model_inputs["text"] = text + return model_inputs + + def _forward(self, model_inputs, generate_kwargs=None): + generate_kwargs = {} if generate_kwargs is None else generate_kwargs + prompt_text = model_inputs.pop("text") + input_ids = model_inputs.get("input_ids", model_inputs.get("decoder_input_ids")) + + # User-defined `generation_config` passed to the pipeline call take precedence + if "generation_config" not in generate_kwargs: + generate_kwargs["generation_config"] = self.generation_config + + generated_sequence = self.model.generate(**model_inputs, **generate_kwargs) + return {"generated_sequence": generated_sequence, "prompt_text": prompt_text, "input_ids": input_ids} + + def postprocess( + self, + model_outputs, + return_type=None, + continue_final_message=None, + skip_special_tokens=None, + **postprocess_kwargs, + ): + input_texts = model_outputs["prompt_text"] + input_texts = [input_texts] if isinstance(input_texts, (str, Chat)) else input_texts + generated_sequence = model_outputs["generated_sequence"] + input_ids = model_outputs["input_ids"] + if return_type == ReturnType.TENSORS: + return [ + {"input_text": input_texts[i], "generated_token_ids": generated_sequence[i]} + for i in range(len(input_texts)) + ] + + # Decode inputs and outputs the same way to remove input text from generated text if present + skip_special_tokens = skip_special_tokens if skip_special_tokens is not None else True + if getattr(self.tokenizer, "response_schema", False): + skip_special_tokens = False + generation_mode = postprocess_kwargs["generation_mode"] or "text" + if generation_mode == "image" and hasattr(self.model, "decode_image_tokens"): + generated_sequence = self.model.decode_image_tokens(generated_sequence.to(self.model.device)) + generated_outputs = self.processor.post_process_multimodal_output( + generated_sequence, skip_special_tokens=skip_special_tokens, **postprocess_kwargs + ) + + # Force consistent behavior for including the input text in the output + if return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: + # Remove the input text from the generated text if the generated text starts with the input text + # (accounting for the possibility of a space between the input and generated text) + new_generated_texts = [] + postprocess_kwargs["generation_mode"] = "text" + decoded_inputs = self.processor.post_process_multimodal_output( + input_ids, skip_special_tokens=skip_special_tokens, **postprocess_kwargs + ) + for text_generated, decoded_input in zip(generated_outputs, decoded_inputs): + # There can be added characters before the input text, so we need to find the beginning of the input text in the generated text + index_input_text = text_generated.find(decoded_input) + # Limit the search to 2 residual characters, like spaces or new lines, to avoid removing a large part of the answer + if 0 <= index_input_text <= 2: + # If the input text is found, we remove it + new_generated_texts.append(text_generated[index_input_text + len(decoded_input) :]) + else: + new_generated_texts.append(text_generated) + generated_outputs = new_generated_texts + if return_type == ReturnType.FULL_TEXT: + full_texts = [] + for prompt_text, generated_text in zip(input_texts, generated_outputs): + if isinstance(prompt_text, str): + generated_text = prompt_text + generated_text + elif isinstance(prompt_text, Chat): + if continue_final_message is None: + # If the user passes a chat ending in an assistant message, we treat it as a prefill by + # default because very few models support multiple separate, consecutive assistant messages + continue_final_message = prompt_text.messages[-1]["role"] == "assistant" + if continue_final_message: + # With assistant prefill, concat onto the end of the last message + new_text = dict(prompt_text.messages[-1]["content"][-1].items()) + new_text["text"] += generated_text + generated_text = list(prompt_text.messages)[:-1] + [ + { + "role": prompt_text.messages[-1]["role"], + "content": prompt_text.messages[-1]["content"][:-1] + [new_text], + } + ] + else: + # When we're not starting from a prefill, the output is a new assistant message + if getattr(self.tokenizer, "response_schema", False): + assistant_message = self.tokenizer.parse_response(generated_text) + else: + assistant_message = {"role": "assistant", "content": generated_text} + generated_text = list(prompt_text.messages) + [assistant_message] + full_texts.append(generated_text) + generated_outputs = full_texts + + records = [ + { + "input_text": input_text.messages if isinstance(input_text, Chat) else input_text, + f"generated_{generation_mode}": generated_output, + } + for input_text, generated_output in zip(input_texts, generated_outputs) + ] + + return records diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/audio_classification.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/audio_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..6e173111aa860dd2dd313b3c613cb04334a3ac72 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/audio_classification.py @@ -0,0 +1,260 @@ +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# 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. +import subprocess +from typing import Any + +import httpx +import numpy as np + +from ..utils import add_end_docstrings, is_torch_available, is_torchaudio_available, is_torchcodec_available, logging +from .base import Pipeline, build_pipeline_init_args + + +if is_torch_available(): + from ..models.auto.modeling_auto import MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES + +logger = logging.get_logger(__name__) + + +def ffmpeg_read(bpayload: bytes, sampling_rate: int) -> np.ndarray: + """ + Helper function to read an audio file through ffmpeg. + """ + ar = f"{sampling_rate}" + ac = "1" + format_for_conversion = "f32le" + ffmpeg_command = [ + "ffmpeg", + "-i", + "pipe:0", + "-ac", + ac, + "-ar", + ar, + "-f", + format_for_conversion, + "-hide_banner", + "-loglevel", + "quiet", + "pipe:1", + ] + + try: + ffmpeg_process = subprocess.Popen(ffmpeg_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE) + except FileNotFoundError: + raise ValueError("ffmpeg was not found but is required to load audio files from filename") + output_stream = ffmpeg_process.communicate(bpayload) + out_bytes = output_stream[0] + + audio = np.frombuffer(out_bytes, np.float32) + if audio.shape[0] == 0: + raise ValueError("Malformed soundfile") + return audio + + +@add_end_docstrings(build_pipeline_init_args(has_feature_extractor=True)) +class AudioClassificationPipeline(Pipeline): + # no-format + """ + Audio classification pipeline using any `AutoModelForAudioClassification`. This pipeline predicts the class of a + raw waveform or an audio file. In case of an audio file, ffmpeg should be installed to support multiple audio + formats. + + Example: + + ```python + >>> from transformers import pipeline + + >>> classifier = pipeline(model="superb/wav2vec2-base-superb-ks") + >>> classifier("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac") + [{'score': 0.997, 'label': '_unknown_'}, {'score': 0.002, 'label': 'left'}, {'score': 0.0, 'label': 'yes'}, {'score': 0.0, 'label': 'down'}, {'score': 0.0, 'label': 'stop'}] + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) + + + This pipeline can currently be loaded from [`pipeline`] using the following task identifier: + `"audio-classification"`. + + See the list of available models on + [huggingface.co/models](https://huggingface.co/models?filter=audio-classification). + """ + + _load_processor = False + _load_image_processor = False + _load_feature_extractor = True + _load_tokenizer = False + + def __init__(self, *args, **kwargs): + # Only set default top_k if explicitly provided + if "top_k" in kwargs and kwargs["top_k"] is None: + kwargs["top_k"] = None + elif "top_k" not in kwargs: + kwargs["top_k"] = 5 + super().__init__(*args, **kwargs) + + self.check_model_type(MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES) + + def __call__(self, inputs: np.ndarray | bytes | str | dict, **kwargs: Any) -> list[dict[str, Any]]: + """ + Classify the sequence(s) given as inputs. See the [`AutomaticSpeechRecognitionPipeline`] documentation for more + information. + + Args: + inputs (`np.ndarray` or `bytes` or `str` or `dict`): + The inputs is either : + - `str` that is the filename of the audio file, the file will be read at the correct sampling rate + to get the waveform using *ffmpeg*. This requires *ffmpeg* to be installed on the system. + - `bytes` it is supposed to be the content of an audio file and is interpreted by *ffmpeg* in the + same way. + - (`np.ndarray` of shape (n, ) of type `np.float32` or `np.float64`) + Raw audio at the correct sampling rate (no further check will be done) + - `dict` form can be used to pass raw audio sampled at arbitrary `sampling_rate` and let this + pipeline do the resampling. The dict must be either be in the format `{"sampling_rate": int, + "raw": np.array}`, or `{"sampling_rate": int, "array": np.array}`, where the key `"raw"` or + `"array"` is used to denote the raw audio waveform. + top_k (`int`, *optional*, defaults to None): + The number of top labels that will be returned by the pipeline. If the provided number is `None` or + higher than the number of labels available in the model configuration, it will default to the number of + labels. + function_to_apply (`str`, *optional*, defaults to "softmax"): + The function to apply to the model output. By default, the pipeline will apply the softmax function to + the output of the model. Valid options: ["softmax", "sigmoid", "none"]. Note that passing Python's + built-in `None` will default to "softmax", so you need to pass the string "none" to disable any + post-processing. + + Return: + A list of `dict` with the following keys: + + - **label** (`str`) -- The label predicted. + - **score** (`float`) -- The corresponding probability. + """ + return super().__call__(inputs, **kwargs) + + def _sanitize_parameters(self, top_k=None, function_to_apply=None, **kwargs): + postprocess_params = {} + + # If top_k is None, use all labels + if top_k is None: + postprocess_params["top_k"] = self.model.config.num_labels + else: + if top_k > self.model.config.num_labels: + top_k = self.model.config.num_labels + postprocess_params["top_k"] = top_k + + if function_to_apply is not None: + if function_to_apply not in ["softmax", "sigmoid", "none"]: + raise ValueError( + f"Invalid value for `function_to_apply`: {function_to_apply}. " + "Valid options are ['softmax', 'sigmoid', 'none']" + ) + postprocess_params["function_to_apply"] = function_to_apply + else: + postprocess_params["function_to_apply"] = "softmax" + return {}, {}, postprocess_params + + def preprocess(self, inputs): + if isinstance(inputs, str): + if inputs.startswith("http://") or inputs.startswith("https://"): + # We need to actually check for a real protocol, otherwise it's impossible to use a local file + # like http_huggingface_co.png + inputs = httpx.get(inputs, follow_redirects=True).content + else: + with open(inputs, "rb") as f: + inputs = f.read() + + if isinstance(inputs, bytes): + inputs = ffmpeg_read(inputs, self.feature_extractor.sampling_rate) + + if is_torch_available(): + import torch + + if isinstance(inputs, torch.Tensor): + inputs = inputs.cpu().numpy() + + if is_torchcodec_available(): + import torch + import torchcodec + + if isinstance(inputs, torchcodec.decoders.AudioDecoder): + _audio_samples = inputs.get_all_samples() + _array = _audio_samples.data + inputs = {"array": _array, "sampling_rate": _audio_samples.sample_rate} + + if isinstance(inputs, dict): + inputs = inputs.copy() # So we don't mutate the original dictionary outside the pipeline + # Accepting `"array"` which is the key defined in `datasets` for + # better integration + if not ("sampling_rate" in inputs and ("raw" in inputs or "array" in inputs)): + raise ValueError( + "When passing a dictionary to AudioClassificationPipeline, the dict needs to contain a " + '"raw" key containing the numpy array or torch tensor representing the audio and a "sampling_rate" key, ' + "containing the sampling_rate associated with that array" + ) + + _inputs = inputs.pop("raw", None) + if _inputs is None: + # Remove path which will not be used from `datasets`. + inputs.pop("path", None) + _inputs = inputs.pop("array", None) + in_sampling_rate = inputs.pop("sampling_rate") + inputs = _inputs + if in_sampling_rate != self.feature_extractor.sampling_rate: + import torch + + if is_torchaudio_available(): + from torchaudio import functional as F + else: + raise ImportError( + "torchaudio is required to resample audio samples in AudioClassificationPipeline. " + "The torchaudio package can be installed through: `pip install torchaudio`." + ) + + inputs = F.resample( + torch.from_numpy(inputs) if isinstance(inputs, np.ndarray) else inputs, + in_sampling_rate, + self.feature_extractor.sampling_rate, + ).numpy() + + if not isinstance(inputs, np.ndarray): + raise TypeError("We expect a numpy ndarray or torch tensor as input") + if len(inputs.shape) != 1: + raise ValueError("We expect a single channel audio input for AudioClassificationPipeline") + + processed = self.feature_extractor( + inputs, sampling_rate=self.feature_extractor.sampling_rate, return_tensors="pt" + ) + if self.dtype is not None: + processed = processed.to(dtype=self.dtype) + return processed + + def _forward(self, model_inputs): + model_outputs = self.model(**model_inputs) + return model_outputs + + def postprocess(self, model_outputs, top_k=5, function_to_apply="softmax"): + if function_to_apply == "softmax": + probs = model_outputs.logits[0].softmax(-1) + elif function_to_apply == "sigmoid": + probs = model_outputs.logits[0].sigmoid() + else: + probs = model_outputs.logits[0] + scores, ids = probs.topk(top_k) + + scores = scores.tolist() + ids = ids.tolist() + + labels = [{"score": score, "label": self.model.config.id2label[_id]} for score, _id in zip(scores, ids)] + + return labels diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/audio_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/audio_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3e3e0bcd521572f751202c4f618e0a0be0251a16 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/audio_utils.py @@ -0,0 +1,295 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +import datetime +import platform +import subprocess + +import numpy as np + + +def ffmpeg_read(bpayload: bytes, sampling_rate: int) -> np.ndarray: + """ + Helper function to read an audio file through ffmpeg. + """ + ar = f"{sampling_rate}" + ac = "1" + format_for_conversion = "f32le" + ffmpeg_command = [ + "ffmpeg", + "-i", + "pipe:0", + "-ac", + ac, + "-ar", + ar, + "-f", + format_for_conversion, + "-hide_banner", + "-loglevel", + "quiet", + "pipe:1", + ] + + try: + with subprocess.Popen(ffmpeg_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE) as ffmpeg_process: + output_stream = ffmpeg_process.communicate(bpayload) + except FileNotFoundError as error: + raise ValueError("ffmpeg was not found but is required to load audio files from filename") from error + out_bytes = output_stream[0] + audio = np.frombuffer(out_bytes, np.float32) + if audio.shape[0] == 0: + raise ValueError( + "Soundfile is either not in the correct format or is malformed. Ensure that the soundfile has " + "a valid audio file extension (e.g. wav, flac or mp3) and is not corrupted. If reading from a remote " + "URL, ensure that the URL is the full address to **download** the audio file." + ) + return audio + + +def ffmpeg_microphone( + sampling_rate: int, + chunk_length_s: float, + format_for_conversion: str = "f32le", + ffmpeg_input_device: str | None = None, + ffmpeg_additional_args: list[str] | None = None, +): + """ + Helper function to read audio from a microphone using ffmpeg. The default input device will be used unless another + input device is specified using the `ffmpeg_input_device` argument. Uses 'alsa' on Linux, 'avfoundation' on MacOS and + 'dshow' on Windows. + + Arguments: + sampling_rate (`int`): + The sampling_rate to use when reading the data from the microphone. Try using the model's sampling_rate to + avoid resampling later. + chunk_length_s (`float` or `int`): + The length of the maximum chunk of audio to be sent returned. + format_for_conversion (`str`, defaults to `f32le`): + The name of the format of the audio samples to be returned by ffmpeg. The standard is `f32le`, `s16le` + could also be used. + ffmpeg_input_device (`str`, *optional*): + The identifier of the input device to be used by ffmpeg (i.e. ffmpeg's '-i' argument). If unset, + the default input device will be used. See `https://www.ffmpeg.org/ffmpeg-devices.html#Input-Devices` + for how to specify and list input devices. + ffmpeg_additional_args (`list[str]`, *optional*): + Additional arguments to pass to ffmpeg, can include arguments like -nostdin for running as a background + process. For example, to pass -nostdin to the ffmpeg process, pass in ["-nostdin"]. If passing in flags + with multiple arguments, use the following convention (eg ["flag", "arg1", "arg2]). + + Returns: + A generator yielding audio chunks of `chunk_length_s` seconds as `bytes` objects of length + `int(round(sampling_rate * chunk_length_s)) * size_of_sample`. + """ + ar = f"{sampling_rate}" + ac = "1" + if format_for_conversion == "s16le": + size_of_sample = 2 + elif format_for_conversion == "f32le": + size_of_sample = 4 + else: + raise ValueError(f"Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`") + + system = platform.system() + + if system == "Linux": + format_ = "alsa" + input_ = ffmpeg_input_device or "default" + elif system == "Darwin": + format_ = "avfoundation" + input_ = ffmpeg_input_device or ":default" + elif system == "Windows": + format_ = "dshow" + input_ = ffmpeg_input_device or _get_microphone_name() + + ffmpeg_additional_args = [] if ffmpeg_additional_args is None else ffmpeg_additional_args + + ffmpeg_command = [ + "ffmpeg", + "-f", + format_, + "-i", + input_, + "-ac", + ac, + "-ar", + ar, + "-f", + format_for_conversion, + "-fflags", + "nobuffer", + "-hide_banner", + "-loglevel", + "quiet", + "pipe:1", + ] + + ffmpeg_command.extend(ffmpeg_additional_args) + + chunk_len = int(round(sampling_rate * chunk_length_s)) * size_of_sample + iterator = _ffmpeg_stream(ffmpeg_command, chunk_len) + yield from iterator + + +def ffmpeg_microphone_live( + sampling_rate: int, + chunk_length_s: float, + stream_chunk_s: int | None = None, + stride_length_s: tuple[float, float] | float | None = None, + format_for_conversion: str = "f32le", + ffmpeg_input_device: str | None = None, + ffmpeg_additional_args: list[str] | None = None, +): + """ + Helper function to read audio from a microphone using ffmpeg. This will output `partial` overlapping chunks starting + from `stream_chunk_s` (if it is defined) until `chunk_length_s` is reached. It will make use of striding to avoid + errors on the "sides" of the various chunks. The default input device will be used unless another input device is + specified using the `ffmpeg_input_device` argument. Uses 'alsa' on Linux, 'avfoundation' on MacOS and 'dshow' on Windows. + + Arguments: + sampling_rate (`int`): + The sampling_rate to use when reading the data from the microphone. Try using the model's sampling_rate to + avoid resampling later. + chunk_length_s (`float` or `int`): + The length of the maximum chunk of audio to be sent returned. This includes the eventual striding. + stream_chunk_s (`float` or `int`): + The length of the minimal temporary audio to be returned. + stride_length_s (`float` or `int` or `(float, float)`, *optional*): + The length of the striding to be used. Stride is used to provide context to a model on the (left, right) of + an audio sample but without using that part to actually make the prediction. Setting this does not change + the length of the chunk. + format_for_conversion (`str`, *optional*, defaults to `f32le`): + The name of the format of the audio samples to be returned by ffmpeg. The standard is `f32le`, `s16le` + could also be used. + ffmpeg_input_device (`str`, *optional*): + The identifier of the input device to be used by ffmpeg (i.e. ffmpeg's '-i' argument). If unset, + the default input device will be used. See `https://www.ffmpeg.org/ffmpeg-devices.html#Input-Devices` + for how to specify and list input devices. + ffmpeg_additional_args (`list[str]`, *optional*): + Additional arguments to pass to ffmpeg, can include arguments like -nostdin for running as a background + process. For example, to pass -nostdin to the ffmpeg process, pass in ["-nostdin"]. If passing in flags + with multiple arguments, use the following convention (eg ["flag", "arg1", "arg2]). + + Return: + A generator yielding dictionaries of the following form + + `{"sampling_rate": int, "raw": np.ndarray, "partial" bool}` With optionally a `"stride" (int, int)` key if + `stride_length_s` is defined. + + `stride` and `raw` are all expressed in `samples`, and `partial` is a boolean saying if the current yield item + is a whole chunk, or a partial temporary result to be later replaced by another larger chunk. + """ + if stream_chunk_s is not None: + chunk_s = stream_chunk_s + else: + chunk_s = chunk_length_s + + microphone = ffmpeg_microphone( + sampling_rate, + chunk_s, + format_for_conversion=format_for_conversion, + ffmpeg_input_device=ffmpeg_input_device, + ffmpeg_additional_args=[] if ffmpeg_additional_args is None else ffmpeg_additional_args, + ) + + if format_for_conversion == "s16le": + dtype = np.int16 + size_of_sample = 2 + elif format_for_conversion == "f32le": + dtype = np.float32 + size_of_sample = 4 + else: + raise ValueError(f"Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`") + + if stride_length_s is None: + stride_length_s = chunk_length_s / 6 + chunk_len = int(round(sampling_rate * chunk_length_s)) * size_of_sample + if isinstance(stride_length_s, (int, float)): + stride_length_s = [stride_length_s, stride_length_s] + + stride_left = int(round(sampling_rate * stride_length_s[0])) * size_of_sample + stride_right = int(round(sampling_rate * stride_length_s[1])) * size_of_sample + audio_time = datetime.datetime.now() + delta = datetime.timedelta(seconds=chunk_s) + for item in chunk_bytes_iter(microphone, chunk_len, stride=(stride_left, stride_right), stream=True): + # Put everything back in numpy scale + item["raw"] = np.frombuffer(item["raw"], dtype=dtype) + item["stride"] = ( + item["stride"][0] // size_of_sample, + item["stride"][1] // size_of_sample, + ) + item["sampling_rate"] = sampling_rate + audio_time += delta + if datetime.datetime.now() > audio_time + 10 * delta: + # We're late !! SKIP + continue + yield item + + +def chunk_bytes_iter(iterator, chunk_len: int, stride: tuple[int, int], stream: bool = False): + """ + Reads raw bytes from an iterator and does chunks of length `chunk_len`. Optionally adds `stride` to each chunks to + get overlaps. `stream` is used to return partial results even if a full `chunk_len` is not yet available. + """ + acc = b"" + stride_left, stride_right = stride + if stride_left + stride_right >= chunk_len: + raise ValueError( + f"Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}" + ) + _stride_left = 0 + for raw in iterator: + acc += raw + if stream and len(acc) < chunk_len: + stride = (_stride_left, 0) + yield {"raw": acc[:chunk_len], "stride": stride, "partial": True} + else: + while len(acc) >= chunk_len: + # We are flushing the accumulator + stride = (_stride_left, stride_right) + item = {"raw": acc[:chunk_len], "stride": stride} + if stream: + item["partial"] = False + yield item + _stride_left = stride_left + acc = acc[chunk_len - stride_left - stride_right :] + # Last chunk + if len(acc) > stride_left: + item = {"raw": acc, "stride": (_stride_left, 0)} + if stream: + item["partial"] = False + yield item + + +def _ffmpeg_stream(ffmpeg_command, buflen: int): + """ + Internal function to create the generator of data through ffmpeg + """ + bufsize = 2**24 # 16Mo + try: + with subprocess.Popen(ffmpeg_command, stdout=subprocess.PIPE, bufsize=bufsize) as ffmpeg_process: + while True: + raw = ffmpeg_process.stdout.read(buflen) + if raw == b"": + break + yield raw + except FileNotFoundError as error: + raise ValueError("ffmpeg was not found but is required to stream audio files from filename") from error + + +def _get_microphone_name(): + """ + Retrieve the microphone name in Windows . + """ + command = ["ffmpeg", "-list_devices", "true", "-f", "dshow", "-i", ""] + + try: + ffmpeg_devices = subprocess.run(command, text=True, stderr=subprocess.PIPE, encoding="utf-8") + microphone_lines = [line for line in ffmpeg_devices.stderr.splitlines() if "(audio)" in line] + + if microphone_lines: + microphone_name = microphone_lines[0].split('"')[1] + print(f"Using microphone: {microphone_name}") + return f"audio={microphone_name}" + except FileNotFoundError: + print("ffmpeg was not found. Please install it or make sure it is in your system PATH.") + + return "default" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/automatic_speech_recognition.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/automatic_speech_recognition.py new file mode 100644 index 0000000000000000000000000000000000000000..4817b4b2d37d0e11d34cc24c15df162c1f4cee48 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/automatic_speech_recognition.py @@ -0,0 +1,693 @@ +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# 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. +from collections import defaultdict +from typing import TYPE_CHECKING, Any, Union + +import httpx +import numpy as np + +from ..generation import GenerationConfig +from ..tokenization_python import PreTrainedTokenizer +from ..utils import is_torch_available, is_torchaudio_available, is_torchcodec_available, logging +from .audio_utils import ffmpeg_read +from .base import ChunkPipeline + + +if TYPE_CHECKING: + from pyctcdecode import BeamSearchDecoderCTC + + from ..feature_extraction_sequence_utils import SequenceFeatureExtractor + from ..modeling_utils import PreTrainedModel + +logger = logging.get_logger(__name__) + +if is_torch_available(): + import torch + + from ..models.auto.modeling_auto import MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES + + +def rescale_stride(stride, ratio): + """ + Rescales the stride values from audio space to tokens/logits space. + + (160_000, 16_000, 16_000) -> (2000, 200, 200) for instance. + """ + # Shape is [B, SEQ] for tokens + # [B, SEQ, V] for logits + + new_strides = [] + for input_n, left, right in stride: + token_n = int(round(input_n * ratio)) + left = int(round(left / input_n * token_n)) + right = int(round(right / input_n * token_n)) + new_stride = (token_n, left, right) + new_strides.append(new_stride) + + return new_strides + + +def chunk_iter(inputs, feature_extractor, chunk_len, stride_left, stride_right, dtype=None): + inputs_len = inputs.shape[0] + step = chunk_len - stride_left - stride_right + for chunk_start_idx in range(0, inputs_len, step): + chunk_end_idx = chunk_start_idx + chunk_len + chunk = inputs[chunk_start_idx:chunk_end_idx] + processed = feature_extractor( + chunk, + sampling_rate=feature_extractor.sampling_rate, + return_tensors="pt", + return_attention_mask=True, + ) + if dtype is not None: + processed = processed.to(dtype=dtype) + _stride_left = 0 if chunk_start_idx == 0 else stride_left + is_last = chunk_end_idx >= inputs_len + _stride_right = 0 if is_last else stride_right + + chunk_len = chunk.shape[0] + stride = (chunk_len, _stride_left, _stride_right) + if chunk.shape[0] > _stride_left: + yield {"is_last": is_last, "stride": stride, **processed} + if is_last: + break + + +def _find_longest_common_sequence(sequences, tokenizer): + # TODO Use a faster algorithm this can probably be done in O(n) + # using suffix array. + # It might be tedious to do because of fault tolerance. + # We actually have a really good property which is that the total sequence + # MUST be those subsequences in order. + # Also the algorithm should be more tolerant to errors. + sequence = [tok_id for tok_id in sequences[0][0].tolist() if tok_id not in tokenizer.all_special_ids] + for new_seq in sequences[1:]: + new_sequence = [tok_id for tok_id in new_seq[0].tolist() if tok_id not in tokenizer.all_special_ids] + + index = 0 + max_ = 0.0 + for i in range(1, len(new_sequence) + 1): + # epsilon to favor long perfect matches + eps = i / 10000.0 + matches = np.sum(np.array(sequence[-i:]) == np.array(new_sequence[:i])) + matching = matches / i + eps + if matches > 1 and matching > max_: + index = i + max_ = matching + sequence.extend(new_sequence[index:]) + return np.array(sequence) + + +class AutomaticSpeechRecognitionPipeline(ChunkPipeline): + """ + Pipeline that aims at extracting spoken text contained within some audio. + + The input can be either a raw waveform or a audio file. In case of the audio file, ffmpeg should be installed for + to support multiple audio formats + + Unless the model you're using explicitly sets these generation parameters in its configuration files + (`generation_config.json`), the following default values will be used: + - max_new_tokens: 256 + - num_beams: 5 + + Example: + + ```python + >>> from transformers import pipeline + + >>> transcriber = pipeline(model="openai/whisper-base") + >>> transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac") + {'text': ' He hoped there would be stew for dinner, turnips and carrots and bruised potatoes and fat mutton pieces to be ladled out in thick, peppered flour-fatten sauce.'} + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) + + Arguments: + model ([`PreTrainedModel`]): + The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from + [`PreTrainedModel`]. + feature_extractor ([`SequenceFeatureExtractor`], *optional*): + The feature extractor that will be used by the pipeline to encode waveform for the model. + tokenizer ([`PreTrainedTokenizer`], *optional*): + The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from + [`PreTrainedTokenizer`]. + decoder (`pyctcdecode.BeamSearchDecoderCTC`, *optional*): + [PyCTCDecode's + BeamSearchDecoderCTC](https://github.com/kensho-technologies/pyctcdecode/blob/2fd33dc37c4111417e08d89ccd23d28e9b308d19/pyctcdecode/decoder.py#L180) + can be passed for language model boosted decoding. See [`Wav2Vec2ProcessorWithLM`] for more information. + device (Union[`int`, `torch.device`], *optional*): + Device ordinal for CPU/GPU supports. Setting this to `None` will leverage CPU, a positive will run the + model on the associated CUDA device id. + """ + + _pipeline_calls_generate = True + _load_processor = False + _load_image_processor = False + _load_feature_extractor = True + _load_tokenizer = True + # Make sure the docstring is updated when the default generation config is changed + _default_generation_config = GenerationConfig( + max_new_tokens=256, + num_beams=5, # follows openai's whisper implementation + ) + + def __init__( + self, + model: "PreTrainedModel", + feature_extractor: Union["SequenceFeatureExtractor", str] | None = None, + tokenizer: PreTrainedTokenizer | None = None, + decoder: Union["BeamSearchDecoderCTC", str] | None = None, + device: Union[int, "torch.device"] | None = None, + **kwargs, + ): + # set the model type so we can check we have the right pre- and post-processing parameters + if model.config.model_type == "whisper": + self.type = "seq2seq_whisper" + elif model.__class__.__name__ in MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES.values(): + self.type = "seq2seq" + elif decoder is not None: + self.decoder = decoder + self.type = "ctc_with_lm" + else: + self.type = "ctc" + + super().__init__(model, tokenizer, feature_extractor, device=device, **kwargs) + + def __call__(self, inputs: np.ndarray | bytes | str | dict, **kwargs: Any) -> list[dict[str, Any]]: + """ + Transcribe the audio sequence(s) given as inputs to text. See the [`AutomaticSpeechRecognitionPipeline`] + documentation for more information. + + Args: + inputs (`np.ndarray` or `bytes` or `str` or `dict`): + The inputs is either : + - `str` that is either the filename of a local audio file, or a public URL address to download the + audio file. The file will be read at the correct sampling rate to get the waveform using + *ffmpeg*. This requires *ffmpeg* to be installed on the system. + - `bytes` it is supposed to be the content of an audio file and is interpreted by *ffmpeg* in the + same way. + - (`np.ndarray` of shape (n, ) of type `np.float32` or `np.float64`) + Raw audio at the correct sampling rate (no further check will be done) + - `dict` form can be used to pass raw audio sampled at arbitrary `sampling_rate` and let this + pipeline do the resampling. The dict must be in the format `{"sampling_rate": int, "raw": + np.array}` with optionally a `"stride": (left: int, right: int)` than can ask the pipeline to + treat the first `left` samples and last `right` samples to be ignored in decoding (but used at + inference to provide more context to the model). Only use `stride` with CTC models. + return_timestamps (*optional*, `str` or `bool`): + Only available for pure CTC models (Wav2Vec2, HuBERT, etc) and the Whisper model. Not available for + other sequence-to-sequence models. + + For CTC models, timestamps can take one of two formats: + - `"char"`: the pipeline will return timestamps along the text for every character in the text. For + instance, if you get `[{"text": "h", "timestamp": (0.5, 0.6)}, {"text": "i", "timestamp": (0.7, + 0.9)}]`, then it means the model predicts that the letter "h" was spoken after `0.5` and before + `0.6` seconds. + - `"word"`: the pipeline will return timestamps along the text for every word in the text. For + instance, if you get `[{"text": "hi ", "timestamp": (0.5, 0.9)}, {"text": "there", "timestamp": + (1.0, 1.5)}]`, then it means the model predicts that the word "hi" was spoken after `0.5` and + before `0.9` seconds. + + For the Whisper model, timestamps can take one of two formats: + - `"word"`: same as above for word-level CTC timestamps. Word-level timestamps are predicted + through the *dynamic-time warping (DTW)* algorithm, an approximation to word-level timestamps + by inspecting the cross-attention weights. + - `True`: the pipeline will return timestamps along the text for *segments* of words in the text. + For instance, if you get `[{"text": " Hi there!", "timestamp": (0.5, 1.5)}]`, then it means the + model predicts that the segment "Hi there!" was spoken after `0.5` and before `1.5` seconds. + Note that a segment of text refers to a sequence of one or more words, rather than individual + words as with word-level timestamps. + generate_kwargs (`dict`, *optional*): + The dictionary of ad-hoc parametrization of `generate_config` to be used for the generation call. For a + complete overview of generate, check the [following + guide](https://huggingface.co/docs/transformers/en/main_classes/text_generation). + + Return: + `Dict`: A dictionary with the following keys: + - **text** (`str`): The recognized text. + - **chunks** (*optional(, `list[Dict]`) + When using `return_timestamps`, the `chunks` will become a list containing all the various text + chunks identified by the model, *e.g.* `[{"text": "hi ", "timestamp": (0.5, 0.9)}, {"text": + "there", "timestamp": (1.0, 1.5)}]`. The original full text can roughly be recovered by doing + `"".join(chunk["text"] for chunk in output["chunks"])`. + """ + return super().__call__(inputs, **kwargs) + + def _sanitize_parameters( + self, + chunk_length_s=None, + stride_length_s=None, + ignore_warning=None, + decoder_kwargs=None, + return_timestamps=None, + return_language=None, + **generate_kwargs, + ): + preprocess_params = {} + forward_params = {} + postprocess_params = {} + + # Preprocess params + if chunk_length_s is not None: + if self.type in ["seq2seq", "seq2seq_whisper"] and not ignore_warning: + type_warning = ( + "Using `chunk_length_s` is very experimental with seq2seq models. The results will not necessarily" + " be entirely accurate and will have caveats. More information:" + " https://github.com/huggingface/transformers/pull/20104. Ignore this warning with pipeline(...," + " ignore_warning=True)." + ) + if self.type == "seq2seq_whisper": + type_warning += ( + " To use Whisper for long-form transcription, use rather the model's `generate` method directly " + "as the model relies on it's own chunking mechanism (cf. Whisper original paper, section 3.8. " + "Long-form Transcription)." + ) + logger.warning(type_warning) + preprocess_params["chunk_length_s"] = chunk_length_s + if stride_length_s is not None: + preprocess_params["stride_length_s"] = stride_length_s + + # Forward params + # BC: accept a dictionary of generation kwargs (as opposed to **generate_kwargs) + if "generate_kwargs" in generate_kwargs: + forward_params.update(generate_kwargs.pop("generate_kwargs")) + # Default use for kwargs: they are generation-time kwargs + forward_params.update(generate_kwargs) + + if getattr(self, "assistant_model", None) is not None: + forward_params["assistant_model"] = self.assistant_model + if getattr(self, "assistant_tokenizer", None) is not None: + forward_params["tokenizer"] = self.tokenizer + forward_params["assistant_tokenizer"] = self.assistant_tokenizer + + # Postprocess params + if decoder_kwargs is not None: + postprocess_params["decoder_kwargs"] = decoder_kwargs + if return_language is not None: + if self.type != "seq2seq_whisper": + raise ValueError("Only Whisper can return language for now.") + postprocess_params["return_language"] = return_language + forward_params["return_language"] = return_language + + # Parameter used in more than one place + # in some models like whisper, the generation config has a `return_timestamps` key + if hasattr(self, "generation_config") and hasattr(self.generation_config, "return_timestamps"): + return_timestamps = return_timestamps or self.generation_config.return_timestamps + + if return_timestamps is not None: + # Check whether we have a valid setting for return_timestamps and throw an error before we perform a forward pass + if self.type == "seq2seq" and return_timestamps: + raise ValueError("We cannot return_timestamps yet on non-CTC models apart from Whisper!") + if self.type == "ctc_with_lm" and return_timestamps != "word": + raise ValueError("CTC with LM can only predict word level timestamps, set `return_timestamps='word'`") + if self.type == "ctc" and return_timestamps not in ["char", "word"]: + raise ValueError( + "CTC can either predict character level timestamps, or word level timestamps. " + "Set `return_timestamps='char'` or `return_timestamps='word'` as required." + ) + if self.type == "seq2seq_whisper" and return_timestamps == "char": + raise ValueError( + "Whisper cannot return `char` timestamps, only word level or segment level timestamps. " + "Use `return_timestamps='word'` or `return_timestamps=True` respectively." + ) + forward_params["return_timestamps"] = return_timestamps + postprocess_params["return_timestamps"] = return_timestamps + + return preprocess_params, forward_params, postprocess_params + + @property + def _align_to(self): + """Sample stride per output.""" + # XXX: Carefully, this variable will not exist in `seq2seq` setting. + # Currently chunking is not possible at this level for `seq2seq` so + # it's ok. + align_to = getattr(self.model.config, "inputs_to_logits_ratio", 1) + if self.model.config.model_type == "lasr_ctc": + # TODO: find a standard for that but not easy because input length -> mel length depends on the feature extractor + # specific way of doing it + # means the model take mel features as input, we align according to the hop length + align_to *= self.feature_extractor.hop_length + return align_to + + def preprocess(self, inputs, chunk_length_s=0, stride_length_s=None): + if isinstance(inputs, str): + if inputs.startswith("http://") or inputs.startswith("https://"): + # We need to actually check for a real protocol, otherwise it's impossible to use a local file + # like http_huggingface_co.png + inputs = httpx.get(inputs, follow_redirects=True).content + else: + with open(inputs, "rb") as f: + inputs = f.read() + + if isinstance(inputs, bytes): + inputs = ffmpeg_read(inputs, self.feature_extractor.sampling_rate) + + stride = None + extra = {} + + if is_torch_available(): + import torch + + if isinstance(inputs, torch.Tensor): + inputs = inputs.cpu().numpy() + + if is_torchcodec_available(): + import torchcodec + + if isinstance(inputs, torchcodec.decoders.AudioDecoder): + _audio_samples = inputs.get_all_samples() + + # torchcodec always returns (num_channels, num_samples) + # while before (datasets < 4.0) we had (2, num_samples) if stereo, (num_samples,) if mono + _array = _audio_samples.data + _array = _array[0] if _array.ndim == 2 and _array.shape[0] == 1 else _array + inputs = {"array": _array, "sampling_rate": _audio_samples.sample_rate} + + if isinstance(inputs, dict): + stride = inputs.pop("stride", None) + # Accepting `"array"` which is the key defined in `datasets` for + # better integration + if not ("sampling_rate" in inputs and ("raw" in inputs or "array" in inputs)): + raise ValueError( + "When passing a dictionary to AutomaticSpeechRecognitionPipeline, the dict needs to contain a " + '"raw" key containing the numpy array or torch tensor representing the audio and a "sampling_rate" key, ' + "containing the sampling_rate associated with that array" + ) + + _inputs = inputs.pop("raw", None) + if _inputs is None: + # Remove path which will not be used from `datasets`. + inputs.pop("path", None) + _inputs = inputs.pop("array", None) + in_sampling_rate = inputs.pop("sampling_rate") + extra = inputs + inputs = _inputs + if in_sampling_rate != self.feature_extractor.sampling_rate: + if is_torchaudio_available(): + from torchaudio import functional as F + else: + raise ImportError( + "torchaudio is required to resample audio samples in AutomaticSpeechRecognitionPipeline. " + "The torchaudio package can be installed through: `pip install torchaudio`." + ) + + inputs = F.resample( + torch.from_numpy(inputs) if isinstance(inputs, np.ndarray) else inputs, + in_sampling_rate, + self.feature_extractor.sampling_rate, + ).numpy() + ratio = self.feature_extractor.sampling_rate / in_sampling_rate + else: + ratio = 1 + if stride is not None: + if stride[0] + stride[1] > inputs.shape[0]: + raise ValueError("Stride is too large for input") + + # Stride needs to get the chunk length here, it's going to get + # swallowed by the `feature_extractor` later, and then batching + # can add extra data in the inputs, so we need to keep track + # of the original length in the stride so we can cut properly. + stride = (inputs.shape[0], int(round(stride[0] * ratio)), int(round(stride[1] * ratio))) + if not isinstance(inputs, (np.ndarray, torch.Tensor)): + raise TypeError(f"We expect a numpy ndarray or torch tensor as input, got `{type(inputs)}`") + if inputs.ndim != 1: + logger.warning( + f"We expect a single channel audio input for AutomaticSpeechRecognitionPipeline, got {inputs.ndim}. Taking the mean of the channels for mono conversion." + ) + inputs = inputs.mean(axis=0) + + if chunk_length_s: + if stride_length_s is None: + stride_length_s = chunk_length_s / 6 + + if isinstance(stride_length_s, (int, float)): + stride_length_s = [stride_length_s, stride_length_s] + + align_to = self._align_to + chunk_len = int(round(chunk_length_s * self.feature_extractor.sampling_rate / align_to) * align_to) + stride_left = int(round(stride_length_s[0] * self.feature_extractor.sampling_rate / align_to) * align_to) + stride_right = int(round(stride_length_s[1] * self.feature_extractor.sampling_rate / align_to) * align_to) + + if chunk_len < stride_left + stride_right: + raise ValueError("Chunk length must be superior to stride length") + + for item in chunk_iter(inputs, self.feature_extractor, chunk_len, stride_left, stride_right, self.dtype): + yield {**item, **extra} + else: + if self.type == "seq2seq_whisper" and inputs.shape[0] > self.feature_extractor.n_samples: + processed = self.feature_extractor( + inputs, + sampling_rate=self.feature_extractor.sampling_rate, + truncation=False, + padding="longest", + return_tensors="pt", + return_attention_mask=True, + ) + else: + if self.type == "seq2seq_whisper" and stride is None: + processed = self.feature_extractor( + inputs, + sampling_rate=self.feature_extractor.sampling_rate, + return_tensors="pt", + return_attention_mask=True, + ) + else: + processed = self.feature_extractor( + inputs, + sampling_rate=self.feature_extractor.sampling_rate, + return_tensors="pt", + return_attention_mask=True, + ) + if self.dtype is not None: + processed = processed.to(dtype=self.dtype) + if stride is not None: + if self.type == "seq2seq": + raise ValueError("Stride is only usable with CTC models, try removing it !") + + processed["stride"] = stride + yield {"is_last": True, **processed, **extra} + + def _forward(self, model_inputs, return_timestamps=False, return_language=None, **generate_kwargs): + attention_mask = model_inputs.pop("attention_mask", None) + stride = model_inputs.pop("stride", None) + num_frames = model_inputs.pop("num_frames", None) + is_last = model_inputs.pop("is_last") + + if stride is not None and num_frames is not None: + raise ValueError("num_frames must be used only when stride is None") + + if self.type in {"seq2seq", "seq2seq_whisper"}: + # Consume values so we can let extra information flow freely through + # the pipeline (important for `partial` in microphone) + if "input_features" in model_inputs: + inputs = model_inputs.pop("input_features") + elif "input_values" in model_inputs: + inputs = model_inputs.pop("input_values") + else: + raise ValueError( + "Seq2Seq speech recognition model requires either a " + f"`input_features` or `input_values` key, but only has {model_inputs.keys()}" + ) + + # custom processing for Whisper timestamps and word-level timestamps + return_timestamps = return_timestamps or getattr(self.generation_config, "return_timestamps", False) + if return_timestamps and self.type == "seq2seq_whisper": + generate_kwargs["return_timestamps"] = bool(return_timestamps) + if return_timestamps == "word": + generate_kwargs["return_token_timestamps"] = True + generate_kwargs["return_segments"] = True + + # User-defined `generation_config` passed to the pipeline call take precedence + if "generation_config" not in generate_kwargs: + generate_kwargs["generation_config"] = self.generation_config + + main_input_name = self.model.main_input_name if hasattr(self.model, "main_input_name") else "inputs" + generate_kwargs = { + main_input_name: inputs, + "attention_mask": attention_mask, + **generate_kwargs, + } + # When return_language is requested, use return_segments to retrieve + # the full generated sequences (including init tokens with the language token) + # since generate() strips them from the main output. + if return_language and self.type == "seq2seq_whisper": + generate_kwargs["return_segments"] = True + + tokens = self.model.generate(**generate_kwargs) + + # whisper longform generation stores timestamps in "segments" + if return_timestamps == "word" and self.type == "seq2seq_whisper": + if "segments" not in tokens: + out = {"tokens": tokens["sequences"], "token_timestamps": tokens["token_timestamps"]} + else: + token_timestamps = [ + torch.cat([segment["token_timestamps"] for segment in segment_list]) + for segment_list in tokens["segments"] + ] + out = {"tokens": tokens["sequences"], "token_timestamps": token_timestamps} + elif isinstance(tokens, dict) and "sequences" in tokens: + out = {"tokens": tokens["sequences"]} + else: + out = {"tokens": tokens} + if self.type == "seq2seq_whisper": + if stride is not None: + out["stride"] = stride + if return_language and isinstance(tokens, dict) and "segments" in tokens: + # Extract the language token from the full unstripped sequence + # stored in segments[batch][segment]["result"]. The result is either + # a 1D tensor (full sequence) or a dict with a "sequences" key. + segments = tokens["segments"] + if segments and segments[0]: + result = segments[0][0]["result"] + full_seq = result["sequences"] if isinstance(result, dict) else result + gen_config = generate_kwargs.get("generation_config", self.generation_config) + if hasattr(gen_config, "lang_to_id"): + lang_ids = set(gen_config.lang_to_id.values()) + for token_id in full_seq.tolist(): + if token_id in lang_ids: + out["lang_id"] = torch.tensor([token_id]) + break + + else: + inputs = { + self.model.main_input_name: model_inputs.pop(self.model.main_input_name), + "attention_mask": attention_mask, + } + outputs = self.model(**inputs) + logits = outputs.logits + + if self.type == "ctc_with_lm": + out = {"logits": logits} + else: + out = {"tokens": logits.argmax(dim=-1)} + if stride is not None: + # Send stride to `postprocess`. + # it needs to be handled there where + # the pieces are to be concatenated. + ratio = 1 / self._align_to + if isinstance(stride, tuple): + out["stride"] = rescale_stride([stride], ratio)[0] + else: + out["stride"] = rescale_stride(stride, ratio) + # Leftover + extra = model_inputs + return {"is_last": is_last, **out, **extra} + + def postprocess( + self, model_outputs, decoder_kwargs: dict | None = None, return_timestamps=None, return_language=None + ): + # Optional return types + optional = {} + + final_items = [] + key = "logits" if self.type == "ctc_with_lm" else "tokens" + stride = None + for outputs in model_outputs: + if outputs[key].dtype in (torch.bfloat16, torch.float16): + items = outputs[key].to(torch.float32).numpy() + else: + items = outputs[key].numpy() + stride = outputs.get("stride", None) + if stride is not None and self.type in {"ctc", "ctc_with_lm"}: + total_n, left, right = stride + # Total_n might be < logits.shape[1] + # because of padding, that's why + # we need to reconstruct this information + # This won't work with left padding (which doesn't exist right now) + right_n = total_n - right + items = items[:, left:right_n] + final_items.append(items) + + if stride and self.type == "seq2seq": + items = _find_longest_common_sequence(final_items, self.tokenizer) + elif self.type == "seq2seq_whisper": + time_precision = self.feature_extractor.chunk_length / self.model.config.max_source_positions + # Send the chunking back to seconds, it's easier to handle in whisper + sampling_rate = self.feature_extractor.sampling_rate + for output in model_outputs: + if "stride" in output: + chunk_len, stride_left, stride_right = output["stride"] + # Go back in seconds + chunk_len /= sampling_rate + stride_left /= sampling_rate + stride_right /= sampling_rate + output["stride"] = chunk_len, stride_left, stride_right + + # Since Whisper's generate() strips init tokens (including the language token) + # from the output, we need to re-prepend the detected language token so that + # _decode_asr can find it and populate the language field in chunks. + if return_language: + for output in model_outputs: + if "lang_id" in output: + lang_id = output["lang_id"] + if lang_id.dim() == 0: + lang_id = lang_id.unsqueeze(0) + lang_token = lang_id.unsqueeze(0).to(dtype=output["tokens"].dtype) + output["tokens"] = torch.cat([lang_token, output["tokens"]], dim=-1) + + text, optional = self.tokenizer._decode_asr( + model_outputs, + return_timestamps=return_timestamps, + return_language=return_language, + time_precision=time_precision, + ) + else: + items = np.concatenate(final_items, axis=1) + items = items.squeeze(0) + + if self.type == "ctc_with_lm": + if decoder_kwargs is None: + decoder_kwargs = {} + beams = self.decoder.decode_beams(items, **decoder_kwargs) + text = beams[0][0] + if return_timestamps: + # Simply cast from pyctcdecode format to wav2vec2 format to leverage + # pre-existing code later + chunk_offset = beams[0][2] + offsets = [] + for word, (start_offset, end_offset) in chunk_offset: + offsets.append({"word": word, "start_offset": start_offset, "end_offset": end_offset}) + elif self.type != "seq2seq_whisper": + skip_special_tokens = self.type != "ctc" + text = self.tokenizer.decode(items, skip_special_tokens=skip_special_tokens) + if return_timestamps: + offsets = self.tokenizer.decode( + items, skip_special_tokens=skip_special_tokens, output_char_offsets=True + )["char_offsets"] + if return_timestamps == "word": + offsets = self.tokenizer._get_word_offsets(offsets, self.tokenizer.replace_word_delimiter_char) + + if return_timestamps and self.type not in {"seq2seq", "seq2seq_whisper"}: + chunks = [] + align_to = self._align_to + for item in offsets: + start = item["start_offset"] * align_to + start /= self.feature_extractor.sampling_rate + + stop = item["end_offset"] * align_to + stop /= self.feature_extractor.sampling_rate + + chunks.append({"text": item[return_timestamps], "timestamp": (start, stop)}) + optional["chunks"] = chunks + + extra = defaultdict(list) + for output in model_outputs: + output.pop("tokens", None) + output.pop("logits", None) + output.pop("is_last", None) + output.pop("stride", None) + output.pop("token_timestamps", None) + output.pop("lang_id", None) + for k, v in output.items(): + extra[k].append(v) + return {"text": text, **optional, **extra} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ebcb55d1baf376dc8417926cf1e0e411c3a269ce --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/base.py @@ -0,0 +1,1372 @@ +# Copyright 2018 The HuggingFace Inc. team. +# +# 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. +from __future__ import annotations + +import collections +import copy +import csv +import importlib +import json +import os +import pickle +import sys +import traceback +import types +from abc import ABC, abstractmethod +from collections import UserDict +from contextlib import contextmanager +from os.path import abspath, exists +from typing import TYPE_CHECKING, Any, Union + +from ..dynamic_module_utils import custom_object_save +from ..feature_extraction_utils import PreTrainedFeatureExtractor +from ..generation import GenerationConfig +from ..image_processing_utils import BaseImageProcessor +from ..models.auto import AutoConfig, AutoTokenizer +from ..processing_utils import ProcessorMixin +from ..tokenization_python import PreTrainedTokenizer +from ..utils import ( + ModelOutput, + PushToHubMixin, + add_end_docstrings, + copy_func, + is_torch_available, + is_torch_cuda_available, + is_torch_hpu_available, + is_torch_mlu_available, + is_torch_mps_available, + is_torch_musa_available, + is_torch_npu_available, + is_torch_xpu_available, + logging, +) +from ..utils.chat_template_utils import Chat, is_valid_message + + +GenericTensor = Union[list["GenericTensor"], "torch.Tensor"] + +if is_torch_available() or TYPE_CHECKING: + import torch + from torch.utils.data import DataLoader, Dataset + + from ..modeling_utils import PreTrainedModel + from .pt_utils import KeyDataset +else: + Dataset = None + + +logger = logging.get_logger(__name__) + + +def no_collate_fn(items): + if len(items) != 1: + raise ValueError("This collate_fn is meant to be used with batch_size=1") + return items[0] + + +def _pad(items, key, padding_value, padding_side): + batch_size = len(items) + if isinstance(items[0][key], torch.Tensor): + # Others include `attention_mask` etc... + shape = items[0][key].shape + dim = items[0][key].ndim + if dim == 1: + # We have a list of 1-dim torch tensors, which can be stacked without padding + return torch.cat([item[key] for item in items], dim=0) + if key in ["pixel_values", "image"]: + # This is probable image so padding shouldn't be necessary + # B, C, H, W + return torch.cat([item[key] for item in items], dim=0) + elif dim == 4 and key == "input_features": + # this is probably a mel spectrogram batched + return torch.cat([item[key] for item in items], dim=0) + max_length = max(item[key].shape[1] for item in items) + min_length = min(item[key].shape[1] for item in items) + dtype = items[0][key].dtype + + if dim == 2 and max_length == min_length: + # Bypass for `ImageGPT` which doesn't provide a padding value, yet + # we can consistently pad since the size should be matching + return torch.cat([item[key] for item in items], dim=0) + else: + tensor = torch.full([batch_size, max_length] + list(shape[2:]), fill_value=padding_value, dtype=dtype) + + for i, item in enumerate(items): + if padding_side == "left": + tensor[i, -len(item[key][0]) :] = item[key][0] + else: + tensor[i, : len(item[key][0])] = item[key][0] + + return tensor + else: + return [item[key] for item in items] + + +def pad_collate_fn(tokenizer, feature_extractor): + # Tokenizer + t_padding_side = None + # Feature extractor + f_padding_side = None + if tokenizer is None and feature_extractor is None: + raise ValueError("Pipeline without tokenizer or feature_extractor cannot do batching") + if tokenizer is not None: + if tokenizer.pad_token_id is None: + raise ValueError( + "Pipeline with tokenizer without pad_token cannot do batching. You can try to set it with " + "`pipe.tokenizer.pad_token_id = model.config.eos_token_id`." + ) + else: + t_padding_value = tokenizer.pad_token_id + t_padding_side = tokenizer.padding_side + if feature_extractor is not None: + # Feature extractor can be images, where no padding is expected + f_padding_value = getattr(feature_extractor, "padding_value", None) + f_padding_side = getattr(feature_extractor, "padding_side", None) + + if t_padding_side is not None and f_padding_side is not None and t_padding_side != f_padding_side: + raise ValueError( + f"The feature extractor, and tokenizer don't agree on padding side {t_padding_side} != {f_padding_side}" + ) + padding_side = "right" + if t_padding_side is not None: + padding_side = t_padding_side + if f_padding_side is not None: + padding_side = f_padding_side + + def inner(items): + keys = set(items[0].keys()) + for item in items: + if set(item.keys()) != keys: + raise ValueError( + f"The elements of the batch contain different keys. Cannot batch them ({set(item.keys())} !=" + f" {keys})" + ) + # input_values, input_pixels, input_ids, ... + padded = {} + for key in keys: + if key == "input_ids": + # ImageGPT uses a feature extractor + if tokenizer is None and feature_extractor is not None: + _padding_value = f_padding_value + else: + _padding_value = t_padding_value + elif key in {"input_values", "pixel_values", "input_features"}: + _padding_value = f_padding_value + elif key in {"p_mask", "special_tokens_mask"}: + _padding_value = 1 + elif key in {"attention_mask", "token_type_ids"}: + _padding_value = 0 + else: + # This is likely another random key maybe even user provided + _padding_value = 0 + padded[key] = _pad(items, key, _padding_value, padding_side) + return padded + + return inner + + +def load_model( + model, + config: AutoConfig, + model_classes: tuple[type, ...] | None = None, + task: str | None = None, + **model_kwargs, +): + """ + Load a model. + + If `model` is instantiated, this function will just return it. Otherwise `model` is + actually a checkpoint name and this method will try to instantiate it using `model_classes`. Since we don't want to + instantiate the model twice, this model is returned for use by the pipeline. + + Args: + model (`str`, or [`PreTrainedModel`]): + If `str`, a checkpoint name. The model to load. + config ([`AutoConfig`]): + The config associated with the model to help using the correct class + model_classes (`tuple[type]`, *optional*): + A tuple of model classes. + task (`str`): + The task defining which pipeline will be returned. + model_kwargs: + Additional dictionary of keyword arguments passed along to the model's `from_pretrained(..., + **model_kwargs)` function. + + Returns: + The model. + """ + if not is_torch_available(): + raise RuntimeError("PyTorch should be installed. Please follow the instructions at https://pytorch.org/.") + + if isinstance(model, str): + model_kwargs["_from_pipeline"] = task + class_tuple = model_classes if model_classes is not None else () + if config.architectures: + classes = [] + for architecture in config.architectures: + transformers_module = importlib.import_module("transformers") + _class = getattr(transformers_module, architecture, None) + if _class is not None: + classes.append(_class) + class_tuple = class_tuple + tuple(classes) + + if len(class_tuple) == 0: + raise ValueError(f"Pipeline cannot infer suitable model classes from {model}") + + all_traceback = {} + for model_class in class_tuple: + kwargs = model_kwargs.copy() + + try: + model = model_class.from_pretrained(model, **kwargs) + # Stop loading on the first successful load. + break + except (OSError, ValueError, TypeError, RuntimeError): + # `from_pretrained` may raise a `TypeError` or `RuntimeError` when the requested `dtype` + # is not supported on the execution device (e.g. bf16 on a consumer GPU). We capture those so + # we can transparently retry the load in float32 before surfacing an error to the user. + fallback_tried = False + if "dtype" in kwargs: + import torch + + fallback_tried = True + fp32_kwargs = kwargs.copy() + fp32_kwargs["dtype"] = torch.float32 + + try: + model = model_class.from_pretrained(model, **fp32_kwargs) + logger.warning( + "Falling back to torch.float32 because loading with the original dtype failed on the" + " target device." + ) + break + except Exception: + # If it still fails, capture the traceback and continue to the next class. + all_traceback[model_class.__name__] = traceback.format_exc() + continue + + # If no fallback was attempted or it also failed, record the original traceback. + if not fallback_tried: + all_traceback[model_class.__name__] = traceback.format_exc() + continue + + if isinstance(model, str): + error = "" + for class_name, trace in all_traceback.items(): + error += f"while loading with {class_name}, an error is thrown:\n{trace}\n" + raise ValueError( + f"Could not load model {model} with any of the following classes: {class_tuple}. See the original errors:\n\n{error}\n" + ) + + return model + + +def get_default_model_and_revision(targeted_task: dict, task_options: Any | None) -> tuple[str, str]: + """ + Select a default model to use for a given task. + + Args: + targeted_task (`Dict`): + Dictionary representing the given task, that should contain default models + + task_options (`Any`, None) + Any further value required by the task to get fully specified. + + Returns + + Tuple: + - `str` The model string representing the default model for this pipeline. + - `str` The revision of the model. + """ + defaults = targeted_task["default"] + if task_options: + if task_options not in defaults: + raise ValueError(f"The task does not provide any default models for options {task_options}") + default_models = defaults[task_options]["model"] + elif "model" in defaults: + default_models = targeted_task["default"]["model"] + else: + raise ValueError("The task defaults can't be correctly selected.") + + return default_models + + +def load_assistant_model( + model: PreTrainedModel, + assistant_model: str | PreTrainedModel | None, + assistant_tokenizer: PreTrainedTokenizer | None, +) -> tuple[PreTrainedModel | None, PreTrainedTokenizer | None]: + """ + Prepares the assistant model and the assistant tokenizer for a pipeline whose model that can call `generate`. + + Args: + model ([`PreTrainedModel`]): + The main model that will be used by the pipeline to make predictions. + assistant_model (`str` or [`PreTrainedModel`], *optional*): + The assistant model that will be used by the pipeline to make predictions. + assistant_tokenizer ([`PreTrainedTokenizer`], *optional*): + The assistant tokenizer that will be used by the pipeline to encode data for the model. + + Returns: + Tuple: The loaded assistant model and (optionally) the loaded tokenizer. + """ + if not model.can_generate() or assistant_model is None: + return None, None + + # If the model is passed as a string, load the model and the corresponding tokenizer + if isinstance(assistant_model, str): + assistant_config = AutoConfig.from_pretrained(assistant_model) + loaded_assistant_model = load_model(assistant_model, config=assistant_config) + loaded_assistant_model = loaded_assistant_model.to(device=model.device, dtype=model.dtype) + loaded_assistant_tokenizer = AutoTokenizer.from_pretrained(assistant_model) + else: + loaded_assistant_model = assistant_model + loaded_assistant_tokenizer = assistant_tokenizer + + # Finally, let's check the tokenizers: if the two models have different tokenizers, we need to keep the assistant + # tokenizer + model_text_config = model.config.get_text_config() + assistant_text_config = loaded_assistant_model.config.get_text_config() + same_vocab_size = model_text_config.vocab_size == assistant_text_config.vocab_size + same_special_tokens = all( + getattr(model_text_config, token) == getattr(assistant_text_config, token) + for token in ("eos_token_id", "pad_token_id", "bos_token_id") + ) + if same_vocab_size and same_special_tokens: + loaded_assistant_tokenizer = None + elif loaded_assistant_tokenizer is None: + raise ValueError( + "The assistant model has a different tokenizer than the main model. You should pass the assistant " + "tokenizer." + ) + + return loaded_assistant_model, loaded_assistant_tokenizer + + +class PipelineException(Exception): + """ + Raised by a [`Pipeline`] when handling __call__. + + Args: + task (`str`): The task of the pipeline. + model (`str`): The model used by the pipeline. + reason (`str`): The error message to display. + """ + + def __init__(self, task: str, model: str, reason: str): + super().__init__(reason) + + self.task = task + self.model = model + + +class ArgumentHandler(ABC): + """ + Base interface for handling arguments for each [`~pipelines.Pipeline`]. + """ + + @abstractmethod + def __call__(self, *args, **kwargs): + raise NotImplementedError() + + +class PipelineDataFormat: + """ + Base class for all the pipeline supported data format both for reading and writing. Supported data formats + currently includes: + + - JSON + - CSV + - stdin/stdout (pipe) + + `PipelineDataFormat` also includes some utilities to work with multi-columns like mapping from datasets columns to + pipelines keyword arguments through the `dataset_kwarg_1=dataset_column_1` format. + + Args: + output_path (`str`): Where to save the outgoing data. + input_path (`str`): Where to look for the input data. + column (`str`): The column to read. + overwrite (`bool`, *optional*, defaults to `False`): + Whether or not to overwrite the `output_path`. + """ + + SUPPORTED_FORMATS = ["json", "csv", "pipe"] + + def __init__( + self, + output_path: str | None, + input_path: str | None, + column: str | None, + overwrite: bool = False, + ): + self.output_path = output_path + self.input_path = input_path + self.column = column.split(",") if column is not None else [""] + self.is_multi_columns = len(self.column) > 1 + + if self.is_multi_columns: + self.column = [tuple(c.split("=")) if "=" in c else (c, c) for c in self.column] + + if output_path is not None and not overwrite: + if exists(abspath(self.output_path)): + raise OSError(f"{self.output_path} already exists on disk") + + if input_path is not None: + if not exists(abspath(self.input_path)): + raise OSError(f"{self.input_path} doesn't exist on disk") + + @abstractmethod + def __iter__(self): + raise NotImplementedError() + + @abstractmethod + def save(self, data: dict | list[dict]): + """ + Save the provided data object with the representation for the current [`~pipelines.PipelineDataFormat`]. + + Args: + data (`dict` or list of `dict`): The data to store. + """ + raise NotImplementedError() + + def save_binary(self, data: dict | list[dict]) -> str: + """ + Save the provided data object as a pickle-formatted binary data on the disk. + + Args: + data (`dict` or list of `dict`): The data to store. + + Returns: + `str`: Path where the data has been saved. + """ + path, _ = os.path.splitext(self.output_path) + binary_path = os.path.extsep.join((path, "pickle")) + + with open(binary_path, "wb+") as f_output: + pickle.dump(data, f_output) + + return binary_path + + @staticmethod + def from_str( + format: str, + output_path: str | None, + input_path: str | None, + column: str | None, + overwrite=False, + ) -> PipelineDataFormat: + """ + Creates an instance of the right subclass of [`~pipelines.PipelineDataFormat`] depending on `format`. + + Args: + format (`str`): + The format of the desired pipeline. Acceptable values are `"json"`, `"csv"` or `"pipe"`. + output_path (`str`, *optional*): + Where to save the outgoing data. + input_path (`str`, *optional*): + Where to look for the input data. + column (`str`, *optional*): + The column to read. + overwrite (`bool`, *optional*, defaults to `False`): + Whether or not to overwrite the `output_path`. + + Returns: + [`~pipelines.PipelineDataFormat`]: The proper data format. + """ + if format == "json": + return JsonPipelineDataFormat(output_path, input_path, column, overwrite=overwrite) + elif format == "csv": + return CsvPipelineDataFormat(output_path, input_path, column, overwrite=overwrite) + elif format == "pipe": + return PipedPipelineDataFormat(output_path, input_path, column, overwrite=overwrite) + else: + raise KeyError(f"Unknown reader {format} (Available reader are json/csv/pipe)") + + +class CsvPipelineDataFormat(PipelineDataFormat): + """ + Support for pipelines using CSV data format. + + Args: + output_path (`str`): Where to save the outgoing data. + input_path (`str`): Where to look for the input data. + column (`str`): The column to read. + overwrite (`bool`, *optional*, defaults to `False`): + Whether or not to overwrite the `output_path`. + """ + + def __init__( + self, + output_path: str | None, + input_path: str | None, + column: str | None, + overwrite=False, + ): + super().__init__(output_path, input_path, column, overwrite=overwrite) + + def __iter__(self): + with open(self.input_path, "r") as f: + reader = csv.DictReader(f) + for row in reader: + if self.is_multi_columns: + yield {k: row[c] for k, c in self.column} + else: + yield row[self.column[0]] + + def save(self, data: list[dict]): + """ + Save the provided data object with the representation for the current [`~pipelines.PipelineDataFormat`]. + + Args: + data (`list[dict]`): The data to store. + """ + with open(self.output_path, "w") as f: + if len(data) > 0: + writer = csv.DictWriter(f, list(data[0].keys())) + writer.writeheader() + writer.writerows(data) + + +class JsonPipelineDataFormat(PipelineDataFormat): + """ + Support for pipelines using JSON file format. + + Args: + output_path (`str`): Where to save the outgoing data. + input_path (`str`): Where to look for the input data. + column (`str`): The column to read. + overwrite (`bool`, *optional*, defaults to `False`): + Whether or not to overwrite the `output_path`. + """ + + def __init__( + self, + output_path: str | None, + input_path: str | None, + column: str | None, + overwrite=False, + ): + super().__init__(output_path, input_path, column, overwrite=overwrite) + + with open(input_path, "r") as f: + self._entries = json.load(f) + + def __iter__(self): + for entry in self._entries: + if self.is_multi_columns: + yield {k: entry[c] for k, c in self.column} + else: + yield entry[self.column[0]] + + def save(self, data: dict): + """ + Save the provided data object in a json file. + + Args: + data (`dict`): The data to store. + """ + with open(self.output_path, "w") as f: + json.dump(data, f) + + +class PipedPipelineDataFormat(PipelineDataFormat): + """ + Read data from piped input to the python process. For multi columns data, columns should separated by \t + + If columns are provided, then the output will be a dictionary with {column_x: value_x} + + Args: + output_path (`str`): Where to save the outgoing data. + input_path (`str`): Where to look for the input data. + column (`str`): The column to read. + overwrite (`bool`, *optional*, defaults to `False`): + Whether or not to overwrite the `output_path`. + """ + + def __iter__(self): + for line in sys.stdin: + # Split for multi-columns + if "\t" in line: + line = line.split("\t") + if self.column: + # Dictionary to map arguments + yield {kwargs: l for (kwargs, _), l in zip(self.column, line)} + else: + yield tuple(line) + + # No dictionary to map arguments + else: + yield line + + def save(self, data: dict): + """ + Print the data. + + Args: + data (`dict`): The data to store. + """ + print(data) + + def save_binary(self, data: dict | list[dict]) -> str: + if self.output_path is None: + raise KeyError( + "When using piped input on pipeline outputting large object requires an output file path. " + "Please provide such output path through --output argument." + ) + + return super().save_binary(data) + + +class _ScikitCompat(ABC): + """ + Interface layer for the Scikit and Keras compatibility. + """ + + @abstractmethod + def transform(self, X): + raise NotImplementedError() + + @abstractmethod + def predict(self, X): + raise NotImplementedError() + + +def build_pipeline_init_args( + has_tokenizer: bool = False, + has_feature_extractor: bool = False, + has_image_processor: bool = False, + has_processor: bool = False, + supports_binary_output: bool = True, +) -> str: + docstring = r""" + Arguments: + model ([`PreTrainedModel`]): + The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from + [`PreTrainedModel`].""" + if has_tokenizer: + docstring += r""" + tokenizer ([`PreTrainedTokenizer`]): + The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from + [`PreTrainedTokenizer`].""" + if has_feature_extractor: + docstring += r""" + feature_extractor ([`SequenceFeatureExtractor`]): + The feature extractor that will be used by the pipeline to encode data for the model. This object inherits from + [`SequenceFeatureExtractor`].""" + if has_image_processor: + docstring += r""" + image_processor ([`BaseImageProcessor`]): + The image processor that will be used by the pipeline to encode data for the model. This object inherits from + [`BaseImageProcessor`].""" + if has_processor: + docstring += r""" + processor ([`ProcessorMixin`]): + The processor that will be used by the pipeline to encode data for the model. This object inherits from + [`ProcessorMixin`]. Processor is a composite object that might contain `tokenizer`, `feature_extractor`, and + `image_processor`.""" + docstring += r""" + task (`str`, defaults to `""`): + A task-identifier for the pipeline. + num_workers (`int`, *optional*, defaults to 8): + When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of + workers to be used. + batch_size (`int`, *optional*, defaults to 1): + When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of + the batch to use, for inference this is not always beneficial, please read [Batching with + pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) . + args_parser ([`~pipelines.ArgumentHandler`], *optional*): + Reference to the object in charge of parsing supplied pipeline parameters. + device (`int`, *optional*, defaults to -1): + Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on + the associated CUDA device id. You can pass native `torch.device` or a `str` too + dtype (`str` or `torch.dtype`, *optional*): + Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model + (`torch.float16`, `torch.bfloat16`, ... or `"auto"`)""" + if supports_binary_output: + docstring += r""" + binary_output (`bool`, *optional*, defaults to `False`): + Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as + the raw output data e.g. text.""" + return docstring + + +PIPELINE_INIT_ARGS = build_pipeline_init_args( + has_tokenizer=True, + has_feature_extractor=True, + has_image_processor=True, + has_processor=True, + supports_binary_output=True, +) + +SUPPORTED_PEFT_TASKS = { + "document-question-answering": ["PeftModelForQuestionAnswering"], + "feature-extraction": ["PeftModelForFeatureExtraction", "PeftModel"], + "summarization": ["PeftModelForSeq2SeqLM"], + "table-question-answering": ["PeftModelForQuestionAnswering"], + "text-classification": ["PeftModelForSequenceClassification"], + "sentiment-analysis": ["PeftModelForSequenceClassification"], + "text-generation": ["PeftModelForCausalLM"], + "token-classification": ["PeftModelForTokenClassification"], + "ner": ["PeftModelForTokenClassification"], + "zero-shot-classification": ["PeftModelForSequenceClassification"], +} + +if is_torch_available(): + from transformers.pipelines.pt_utils import ( + PipelineChunkIterator, + PipelineDataset, + PipelineIterator, + PipelinePackIterator, + ) + + +@add_end_docstrings( + build_pipeline_init_args( + has_tokenizer=True, has_feature_extractor=True, has_image_processor=True, has_processor=True + ) +) +class Pipeline(_ScikitCompat, PushToHubMixin): + """ + The Pipeline class is the class from which all pipelines inherit. Refer to this class for methods shared across + different pipelines. + + Base class implementing pipelined operations. Pipeline workflow is defined as a sequence of the following + operations: + + Input -> Tokenization -> Model Inference -> Post-Processing (task dependent) -> Output + + Pipeline supports running on CPU or GPU through the device argument (see below). + + Some pipeline, like for instance [`FeatureExtractionPipeline`] (`'feature-extraction'`) output large tensor object + as nested-lists. In order to avoid dumping such large structure as textual data we provide the `binary_output` + constructor argument. If set to `True`, the output will be stored in the pickle format. + """ + + # These flags should be overridden for downstream pipelines. They indicate which preprocessing classes are + # used by each pipeline. The possible values are: + # - True (the class is mandatory, raise an error if it's not present in the repo) + # - None (the class is optional; it should be loaded if present in the repo but the pipeline can work without it) + # - False (the class is never used by the pipeline and should not be loaded even if present) + _load_processor = None + _load_image_processor = None + _load_feature_extractor = None + _load_tokenizer = None + + # Pipelines that call `generate` have shared logic, e.g. preparing the generation config. + _pipeline_calls_generate = False + + default_input_names = None + + def __init__( + self, + model: PreTrainedModel, + tokenizer: PreTrainedTokenizer | None = None, + feature_extractor: PreTrainedFeatureExtractor | None = None, + image_processor: BaseImageProcessor | None = None, + processor: ProcessorMixin | None = None, + task: str = "", + device: int | torch.device | None = None, + binary_output: bool = False, + **kwargs, + ): + # We need to pop them for _sanitize_parameters call later + _, _, _ = kwargs.pop("args_parser", None), kwargs.pop("torch_dtype", None), kwargs.pop("dtype", None) + + self.task = task + self.model = model + self.tokenizer = tokenizer + self.feature_extractor = feature_extractor + self.image_processor = image_processor + self.processor = processor + + # `accelerate` device map + hf_device_map = getattr(self.model, "hf_device_map", None) + + if hf_device_map is not None and device is not None: + raise ValueError( + "The model has been loaded with `accelerate` and therefore cannot be moved to a specific device. Please " + "discard the `device` argument when creating your pipeline object." + ) + + if device is None: + if hf_device_map is not None: + # Take the first device used by `accelerate`. + device = next(iter(hf_device_map.values())) + else: + device = 0 + + if device == -1 and self.model.device is not None: + device = self.model.device + if isinstance(device, torch.device): + if (device.type == "xpu" and not is_torch_xpu_available(check_device=True)) or ( + device.type == "hpu" and not is_torch_hpu_available() + ): + raise ValueError(f'{device} is not available, you should use device="cpu" instead') + + self.device = device + elif isinstance(device, str): + if ("xpu" in device and not is_torch_xpu_available(check_device=True)) or ( + "hpu" in device and not is_torch_hpu_available() + ): + raise ValueError(f'{device} is not available, you should use device="cpu" instead') + + self.device = torch.device(device) + elif device < 0: + self.device = torch.device("cpu") + elif is_torch_mlu_available(): + self.device = torch.device(f"mlu:{device}") + elif is_torch_musa_available(): + self.device = torch.device(f"musa:{device}") + elif is_torch_cuda_available(): + self.device = torch.device(f"cuda:{device}") + elif is_torch_npu_available(): + self.device = torch.device(f"npu:{device}") + elif is_torch_hpu_available(): + self.device = torch.device(f"hpu:{device}") + elif is_torch_xpu_available(check_device=True): + self.device = torch.device(f"xpu:{device}") + elif is_torch_mps_available(): + self.device = torch.device(f"mps:{device}") + else: + self.device = torch.device("cpu") + + if torch.distributed.is_available() and torch.distributed.is_initialized(): + self.device = self.model.device + logger.debug(f"Device set to use {self.device}") + + self.binary_output = binary_output + + # We shouldn't call `model.to()` for models loaded with accelerate as well as the case that model is already on device + if ( + self.model.device != self.device + and not (isinstance(self.device, int) and self.device < 0) + and hf_device_map is None + ): + self.model.to(self.device) + + # If it's a generation pipeline and the model can generate: + # 1 - create a local generation config. This is done to avoid side-effects on the model as we apply local + # tweaks to the generation config. + # 2 - load the assistant model if it is passed. + if self._pipeline_calls_generate and self.model.can_generate(): + self.assistant_model, self.assistant_tokenizer = load_assistant_model( + self.model, kwargs.pop("assistant_model", None), kwargs.pop("assistant_tokenizer", None) + ) + self.prefix = self.model.config.prefix if hasattr(self.model.config, "prefix") else None + # each pipeline with text generation capabilities should define its own default generation in a + # `_default_generation_config` class attribute + default_pipeline_generation_config = getattr(self, "_default_generation_config", GenerationConfig()) + if hasattr(self.model, "_prepare_generation_config"): + # Uses `generate`'s logic to enforce the following priority of arguments: + # 1. user-defined config options in `**kwargs` + # 2. model's generation config values + # 3. pipeline's default generation config values + # NOTE: _prepare_generation_config creates a deep copy of the generation config before updating it, + # and returns all kwargs that were not used to update the generation config + prepared_generation_config, kwargs = self.model._prepare_generation_config( + generation_config=default_pipeline_generation_config, **kwargs + ) + self.generation_config = prepared_generation_config + # if the `max_new_tokens` is set to the pipeline default, but `max_length` is set to a non-default + # value: let's honor `max_length`. E.g. we want Whisper's default `max_length=448` take precedence + # over over the pipeline's length default. + if ( + default_pipeline_generation_config.max_new_tokens is not None # there's a pipeline default + and self.generation_config.max_new_tokens == default_pipeline_generation_config.max_new_tokens + and self.generation_config.max_length is not None + and self.generation_config.max_length != 20 # global default + ): + self.generation_config.max_new_tokens = None + else: + # TODO (joao): no PT model should reach this line. However, some audio models with complex + # inheritance patterns do. Streamline those models such that this line is no longer needed. + # In those models, the default generation config is not (yet) used. + self.generation_config = copy.deepcopy(self.model.generation_config) + # Update the generation config with task specific params if they exist. + # NOTE: 1. `prefix` is pipeline-specific and doesn't exist in the generation config. + # 2. `task_specific_params` is a legacy feature and should be removed in a future version. + task_specific_params = getattr(self.model.config, "task_specific_params", None) + if task_specific_params is not None and task in task_specific_params: + this_task_params = task_specific_params.get(task) + if "prefix" in this_task_params: + self.prefix = this_task_params.pop("prefix") + self.generation_config.update(**this_task_params) + # If the tokenizer has a pad token but the model doesn't, set it so that `generate` is aware of it. + if ( + self.tokenizer is not None + and self.tokenizer.pad_token_id is not None + and self.generation_config.pad_token_id is None + ): + self.generation_config.pad_token_id = self.tokenizer.pad_token_id + + self.call_count = 0 + self._batch_size = kwargs.pop("batch_size", None) + self._num_workers = kwargs.pop("num_workers", None) + self._preprocess_params, self._forward_params, self._postprocess_params = self._sanitize_parameters(**kwargs) + + # In processor only mode, we can get the modality processors from the processor + if self.processor is not None and all( + [self.tokenizer is None, self.feature_extractor is None, self.image_processor is None] + ): + self.tokenizer = getattr(self.processor, "tokenizer", None) + self.feature_extractor = getattr(self.processor, "feature_extractor", None) + self.image_processor = getattr(self.processor, "image_processor", None) + + if self.image_processor is None and self.feature_extractor is not None: + if isinstance(self.feature_extractor, BaseImageProcessor): + # Backward compatible change, if users called + # ImageSegmentationPipeline(.., feature_extractor=MyFeatureExtractor()) + # then we should keep working + self.image_processor = self.feature_extractor + + def __repr__(self): + pipe_information = { + "model": self.model.__class__.__name__, + "dtype": str(self.dtype).split(".")[-1], + "device": self.device.type, + "input_modalities": self.model.input_modalities, + } + if self.model.can_generate(): + pipe_information["output_modalities"] = self.model.output_modalities + return f"{self.__class__.__name__}: {pipe_information}" + + def save_pretrained(self, save_directory: str | os.PathLike, **kwargs: Any): + """ + Save the pipeline's model and tokenizer. + + Args: + save_directory (`str` or `os.PathLike`): + A path to the directory where to saved. It will be created if it doesn't exist. + kwargs (`dict[str, Any]`, *optional*): + Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method. + """ + if os.path.isfile(save_directory): + logger.error(f"Provided path ({save_directory}) should be a directory, not a file") + return + os.makedirs(save_directory, exist_ok=True) + + if hasattr(self, "_registered_impl"): + # Add info to the config + pipeline_info = self._registered_impl.copy() + custom_pipelines = {} + for task, info in pipeline_info.items(): + if info["impl"] != self.__class__: + continue + + info = info.copy() + module_name = info["impl"].__module__ + last_module = module_name.split(".")[-1] + # Change classes into their names/full names + info["impl"] = f"{last_module}.{info['impl'].__name__}" + info["pt"] = tuple(c.__name__ for c in info["pt"]) + + custom_pipelines[task] = info + self.model.config.custom_pipelines = custom_pipelines + # Save the pipeline custom code + custom_object_save(self, save_directory) + + self.model.save_pretrained(save_directory, **kwargs) + + if self.tokenizer is not None: + self.tokenizer.save_pretrained(save_directory, **kwargs) + + if self.feature_extractor is not None: + self.feature_extractor.save_pretrained(save_directory, **kwargs) + + if self.image_processor is not None: + self.image_processor.save_pretrained(save_directory, **kwargs) + + def transform(self, X): + """ + Scikit / Keras interface to transformers' pipelines. This method will forward to __call__(). + """ + return self(X) + + def predict(self, X): + """ + Scikit / Keras interface to transformers' pipelines. This method will forward to __call__(). + """ + return self(X) + + @property + def dtype(self) -> torch.dtype | None: + """ + Dtype of the model (if it's Pytorch model), `None` otherwise. + """ + return getattr(self.model, "dtype", None) + + @property + def torch_dtype(self) -> torch.dtype | None: + """ + Torch dtype of the model (if it's Pytorch model), `None` otherwise. + """ + logger.warning_once("`torch_dtype` attribute is deprecated. Use `dtype` instead!") + return getattr(self.model, "dtype", None) + + @contextmanager + def device_placement(self): + """ + Context Manager allowing tensor allocation on the user-specified device. + + Returns: + Context manager + + Examples: + + ```python + # Explicitly ask for tensor allocation on CUDA device :0 + pipe = pipeline(..., device=0) + with pipe.device_placement(): + # Every tensor allocation will be done on the request device + output = pipe(...) + ```""" + if self.device.type == "cuda": + with torch.cuda.device(self.device): + yield + elif self.device.type == "mlu": + with torch.mlu.device(self.device): + yield + elif self.device.type == "musa": + with torch.musa.device(self.device): + yield + elif self.device.type == "xpu": + with torch.xpu.device(self.device): + yield + else: + yield + + def ensure_tensor_on_device(self, **inputs): + """ + Ensure PyTorch tensors are on the specified device. + + Args: + inputs (keyword arguments that should be `torch.Tensor`, the rest is ignored): + The tensors to place on `self.device`. + Recursive on lists **only**. + + Return: + `dict[str, torch.Tensor]`: The same as `inputs` but on the proper device. + """ + return self._ensure_tensor_on_device(inputs, self.device) + + def _ensure_tensor_on_device(self, inputs, device): + if isinstance(inputs, ModelOutput): + return ModelOutput( + {name: self._ensure_tensor_on_device(tensor, device) for name, tensor in inputs.items()} + ) + elif isinstance(inputs, dict): + return {name: self._ensure_tensor_on_device(tensor, device) for name, tensor in inputs.items()} + elif isinstance(inputs, UserDict): + return UserDict({name: self._ensure_tensor_on_device(tensor, device) for name, tensor in inputs.items()}) + elif isinstance(inputs, list): + return [self._ensure_tensor_on_device(item, device) for item in inputs] + elif isinstance(inputs, tuple): + return tuple(self._ensure_tensor_on_device(item, device) for item in inputs) + elif isinstance(inputs, torch.Tensor): + return inputs.to(device) + else: + return inputs + + def check_model_type(self, supported_models: list[str] | dict): + """ + Check if the model class is in supported by the pipeline. + + Args: + supported_models (`list[str]` or `dict`): + The list of models supported by the pipeline, or a dictionary with model class values. + """ + if not isinstance(supported_models, list): # Create from a model mapping + supported_models_names = [] + if self.task in SUPPORTED_PEFT_TASKS: + supported_models_names.extend(SUPPORTED_PEFT_TASKS[self.task]) + + model_name = None + for model_name in supported_models.values(): + # Mapping can now contain tuples of models for the same configuration. + if isinstance(model_name, tuple): + supported_models_names.extend(list(model_name)) + else: + supported_models_names.append(model_name) + if hasattr(supported_models, "_model_mapping"): + for model in supported_models._model_mapping._extra_content.values(): + if isinstance(model_name, tuple): + supported_models_names.extend([m.__name__ for m in model]) + else: + supported_models_names.append(model.__name__) + supported_models = supported_models_names + if self.model.__class__.__name__ not in supported_models: + logger.error( + f"The model '{self.model.__class__.__name__}' is not supported for {self.task}. Supported models are" + f" {supported_models}." + ) + + @abstractmethod + def _sanitize_parameters(self, **pipeline_parameters): + """ + _sanitize_parameters will be called with any excessive named arguments from either `__init__` or `__call__` + methods. It should return 3 dictionaries of the resolved parameters used by the various `preprocess`, + `forward` and `postprocess` methods. Do not fill dictionaries if the caller didn't specify a kwargs. This + lets you keep defaults in function signatures, which is more "natural". + + It is not meant to be called directly, it will be automatically called and the final parameters resolved by + `__init__` and `__call__` + """ + raise NotImplementedError("_sanitize_parameters not implemented") + + @abstractmethod + def preprocess(self, input_: Any, **preprocess_parameters: dict) -> dict[str, GenericTensor]: + """ + Preprocess will take the `input_` of a specific pipeline and return a dictionary of everything necessary for + `_forward` to run properly. It should contain at least one tensor, but might have arbitrary other items. + """ + raise NotImplementedError("preprocess not implemented") + + @abstractmethod + def _forward(self, input_tensors: dict[str, GenericTensor], **forward_parameters: dict) -> ModelOutput: + """ + _forward will receive the prepared dictionary from `preprocess` and run it on the model. This method might + involve the GPU or the CPU and should be agnostic to it. Isolating this function is the reason for `preprocess` + and `postprocess` to exist, so that the hot path, this method generally can run as fast as possible. + + It is not meant to be called directly, `forward` is preferred. It is basically the same but contains additional + code surrounding `_forward` making sure tensors and models are on the same device, disabling the training part + of the code (leading to faster inference). + """ + raise NotImplementedError("_forward not implemented") + + @abstractmethod + def postprocess(self, model_outputs: ModelOutput, **postprocess_parameters: dict) -> Any: + """ + Postprocess will receive the raw outputs of the `_forward` method, generally tensors, and reformat them into + something more friendly. Generally it will output a list or a dict or results (containing just strings and + numbers). + """ + raise NotImplementedError("postprocess not implemented") + + def get_inference_context(self): + return torch.no_grad + + def forward(self, model_inputs, **forward_params): + with self.device_placement(): + inference_context = self.get_inference_context() + with inference_context(): + model_inputs = self._ensure_tensor_on_device(model_inputs, device=self.device) + model_outputs = self._forward(model_inputs, **forward_params) + model_outputs = self._ensure_tensor_on_device(model_outputs, device=torch.device("cpu")) + return model_outputs + + def get_iterator( + self, inputs, num_workers: int, batch_size: int, preprocess_params, forward_params, postprocess_params + ): + if isinstance(inputs, collections.abc.Sized): + dataset = PipelineDataset(inputs, self.preprocess, preprocess_params) + else: + if num_workers > 1: + logger.warning( + "For iterable dataset using num_workers>1 is likely to result" + " in errors since everything is iterable, setting `num_workers=1`" + " to guarantee correctness." + ) + num_workers = 1 + dataset = PipelineIterator(inputs, self.preprocess, preprocess_params) + if "TOKENIZERS_PARALLELISM" not in os.environ: + logger.info("Disabling tokenizer parallelism, we're using DataLoader multithreading already") + os.environ["TOKENIZERS_PARALLELISM"] = "false" + # TODO hack by collating feature_extractor and image_processor + feature_extractor = self.feature_extractor if self.feature_extractor is not None else self.image_processor + collate_fn = no_collate_fn if batch_size == 1 else pad_collate_fn(self.tokenizer, feature_extractor) + dataloader = DataLoader(dataset, num_workers=num_workers, batch_size=batch_size, collate_fn=collate_fn) + model_iterator = PipelineIterator(dataloader, self.forward, forward_params, loader_batch_size=batch_size) + final_iterator = PipelineIterator(model_iterator, self.postprocess, postprocess_params) + return final_iterator + + def __call__(self, inputs, *args, num_workers=None, batch_size=None, **kwargs): + if args: + logger.warning(f"Ignoring args : {args}") + + # Detect if inputs are a chat-style input(s) and cast as `Chat` or list of `Chat` + container_types = (list, tuple, types.GeneratorType) + if is_torch_available(): + container_types = (*container_types, KeyDataset) + if isinstance(inputs, container_types): + if isinstance(inputs, types.GeneratorType): + inputs = list(inputs) + if is_valid_message(inputs[0]): + inputs = Chat(inputs) + elif isinstance(inputs[0], (list, tuple)) and all(chat and is_valid_message(chat[0]) for chat in inputs): + inputs = [Chat(chat) for chat in inputs] + + if num_workers is None: + if self._num_workers is None: + num_workers = 0 + else: + num_workers = self._num_workers + if batch_size is None: + if self._batch_size is None: + batch_size = 1 + else: + batch_size = self._batch_size + + preprocess_params, forward_params, postprocess_params = self._sanitize_parameters(**kwargs) + + # Fuse __init__ params and __call__ params without modifying the __init__ ones. + preprocess_params = {**self._preprocess_params, **preprocess_params} + forward_params = {**self._forward_params, **forward_params} + postprocess_params = {**self._postprocess_params, **postprocess_params} + + self.call_count += 1 + if self.call_count > 10 and self.device.type == "cuda": + logger.warning_once( + "You seem to be using the pipelines sequentially on GPU. In order to maximize efficiency please use a" + " dataset", + ) + + is_dataset = Dataset is not None and isinstance(inputs, Dataset) + is_generator = isinstance(inputs, types.GeneratorType) + is_list = isinstance(inputs, list) + + is_iterable = is_dataset or is_generator or is_list + can_use_iterator = is_dataset or is_generator or is_list + + if is_list: + if can_use_iterator: + final_iterator = self.get_iterator( + inputs, num_workers, batch_size, preprocess_params, forward_params, postprocess_params + ) + outputs = list(final_iterator) + return outputs + else: + return self.run_multi(inputs, preprocess_params, forward_params, postprocess_params) + elif can_use_iterator: + return self.get_iterator( + inputs, num_workers, batch_size, preprocess_params, forward_params, postprocess_params + ) + elif is_iterable: + return self.iterate(inputs, preprocess_params, forward_params, postprocess_params) + elif isinstance(self, ChunkPipeline): + return next( + iter( + self.get_iterator( + [inputs], num_workers, batch_size, preprocess_params, forward_params, postprocess_params + ) + ) + ) + else: + return self.run_single(inputs, preprocess_params, forward_params, postprocess_params) + + def run_multi(self, inputs, preprocess_params, forward_params, postprocess_params): + return [self.run_single(item, preprocess_params, forward_params, postprocess_params) for item in inputs] + + def run_single(self, inputs, preprocess_params, forward_params, postprocess_params): + model_inputs = self.preprocess(inputs, **preprocess_params) + model_outputs = self.forward(model_inputs, **forward_params) + outputs = self.postprocess(model_outputs, **postprocess_params) + return outputs + + def iterate(self, inputs, preprocess_params, forward_params, postprocess_params): + # This function should become `get_iterator` again, this is a temporary + # easy solution. + for input_ in inputs: + yield self.run_single(input_, preprocess_params, forward_params, postprocess_params) + + +Pipeline.push_to_hub = copy_func(Pipeline.push_to_hub) +if Pipeline.push_to_hub.__doc__ is not None: + Pipeline.push_to_hub.__doc__ = Pipeline.push_to_hub.__doc__.format( + object="pipe", object_class="pipeline", object_files="pipeline file" + ).replace(".from_pretrained", "") + + +class ChunkPipeline(Pipeline): + def run_single(self, inputs, preprocess_params, forward_params, postprocess_params): + all_outputs = [] + for model_inputs in self.preprocess(inputs, **preprocess_params): + model_outputs = self.forward(model_inputs, **forward_params) + all_outputs.append(model_outputs) + outputs = self.postprocess(all_outputs, **postprocess_params) + return outputs + + def get_iterator( + self, inputs, num_workers: int, batch_size: int, preprocess_params, forward_params, postprocess_params + ): + if "TOKENIZERS_PARALLELISM" not in os.environ: + logger.info("Disabling tokenizer parallelism, we're using DataLoader multithreading already") + os.environ["TOKENIZERS_PARALLELISM"] = "false" + if num_workers > 1: + logger.warning( + "For ChunkPipeline using num_workers>0 is likely to result in errors since everything is iterable," + " setting `num_workers=1` to guarantee correctness." + ) + num_workers = 1 + dataset = PipelineChunkIterator(inputs, self.preprocess, preprocess_params) + + # TODO hack by collating feature_extractor and image_processor + feature_extractor = self.feature_extractor if self.feature_extractor is not None else self.image_processor + collate_fn = no_collate_fn if batch_size == 1 else pad_collate_fn(self.tokenizer, feature_extractor) + dataloader = DataLoader(dataset, num_workers=num_workers, batch_size=batch_size, collate_fn=collate_fn) + model_iterator = PipelinePackIterator(dataloader, self.forward, forward_params, loader_batch_size=batch_size) + final_iterator = PipelineIterator(model_iterator, self.postprocess, postprocess_params) + return final_iterator + + +class PipelineRegistry: + def __init__(self, supported_tasks: dict[str, Any], task_aliases: dict[str, str]) -> None: + self.supported_tasks = supported_tasks + self.task_aliases = task_aliases + + def get_supported_tasks(self) -> list[str]: + supported_task = list(self.supported_tasks.keys()) + list(self.task_aliases.keys()) + supported_task.sort() + return supported_task + + def check_task(self, task: str) -> tuple[str, dict, Any]: + if task in self.task_aliases: + task = self.task_aliases[task] + if task in self.supported_tasks: + targeted_task = self.supported_tasks[task] + return task, targeted_task, None + + raise KeyError(f"Unknown task {task}, available tasks are {self.get_supported_tasks()}") + + def register_pipeline( + self, + task: str, + pipeline_class: type, + pt_model: type | tuple[type] | None = None, + default: dict | None = None, + type: str | None = None, + ) -> None: + if task in self.supported_tasks: + logger.warning(f"{task} is already registered. Overwriting pipeline for task {task}...") + + if pt_model is None: + pt_model = () + elif not isinstance(pt_model, tuple): + pt_model = (pt_model,) + + task_impl = {"impl": pipeline_class, "pt": pt_model} + + if default is not None: + if "model" not in default: + default = {"model": default} + task_impl["default"] = default + + if type is not None: + task_impl["type"] = type + + self.supported_tasks[task] = task_impl + pipeline_class._registered_impl = {task: task_impl} + + def to_dict(self): + return self.supported_tasks diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/depth_estimation.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/depth_estimation.py new file mode 100644 index 0000000000000000000000000000000000000000..03ee70673d6cecf8a0e710bf66db8d7cfc06727e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/depth_estimation.py @@ -0,0 +1,145 @@ +from typing import Any, Union, overload + +from ..utils import ( + add_end_docstrings, + is_torch_available, + is_vision_available, + logging, + requires_backends, +) +from .base import Pipeline, build_pipeline_init_args + + +if is_vision_available(): + from PIL import Image + + from ..image_utils import load_image + +if is_torch_available(): + from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES + +logger = logging.get_logger(__name__) + + +@add_end_docstrings(build_pipeline_init_args(has_image_processor=True)) +class DepthEstimationPipeline(Pipeline): + """ + Depth estimation pipeline using any `AutoModelForDepthEstimation`. This pipeline predicts the depth of an image. + + Example: + + ```python + >>> from transformers import pipeline + + >>> depth_estimator = pipeline(task="depth-estimation", model="LiheYoung/depth-anything-base-hf") + >>> output = depth_estimator("http://images.cocodataset.org/val2017/000000039769.jpg") + >>> # This is a tensor with the values being the depth expressed in meters for each pixel + >>> output["predicted_depth"].shape + torch.Size([1, 384, 384]) + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) + + + This depth estimation pipeline can currently be loaded from [`pipeline`] using the following task identifier: + `"depth-estimation"`. + + See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=depth-estimation). + """ + + _load_processor = False + _load_image_processor = True + _load_feature_extractor = False + _load_tokenizer = False + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + requires_backends(self, "vision") + self.check_model_type(MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES) + + @overload + def __call__(self, inputs: Union[str, "Image.Image"], **kwargs: Any) -> dict[str, Any]: ... + + @overload + def __call__(self, inputs: list[Union[str, "Image.Image"]], **kwargs: Any) -> list[dict[str, Any]]: ... + + def __call__( + self, inputs: Union[str, list[str], "Image.Image", list["Image.Image"]], **kwargs: Any + ) -> dict[str, Any] | list[dict[str, Any]]: + """ + Predict the depth(s) of the image(s) passed as inputs. + + Args: + inputs (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`): + The pipeline handles three types of images: + + - A string containing a http link pointing to an image + - A string containing a local path to an image + - An image loaded in PIL directly + + The pipeline accepts either a single image or a batch of images, which must then be passed as a string. + Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL + images. + parameters (`Dict`, *optional*): + A dictionary of argument names to parameter values, to control pipeline behaviour. + The only parameter available right now is `timeout`, which is the length of time, in seconds, + that the pipeline should wait before giving up on trying to download an image. + timeout (`float`, *optional*, defaults to None): + The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and + the call may block forever. + + Return: + A dictionary or a list of dictionaries containing result. If the input is a single image, will return a + dictionary, if the input is a list of several images, will return a list of dictionaries corresponding to + the images. + + The dictionaries contain the following keys: + + - **predicted_depth** (`torch.Tensor`) -- The predicted depth by the model as a `torch.Tensor`. + - **depth** (`PIL.Image`) -- The predicted depth by the model as a `PIL.Image`. + """ + # After deprecation of this is completed, remove the default `None` value for `images` + if "images" in kwargs: + inputs = kwargs.pop("images") + if inputs is None: + raise ValueError("Cannot call the depth-estimation pipeline without an inputs argument!") + return super().__call__(inputs, **kwargs) + + def _sanitize_parameters(self, timeout=None, parameters=None, **kwargs): + preprocess_params = {} + if timeout is not None: + preprocess_params["timeout"] = timeout + if isinstance(parameters, dict) and "timeout" in parameters: + preprocess_params["timeout"] = parameters["timeout"] + return preprocess_params, {}, {} + + def preprocess(self, image, timeout=None): + image = load_image(image, timeout) + model_inputs = self.image_processor(images=image, return_tensors="pt") + model_inputs = model_inputs.to(self.dtype) + model_inputs["target_size"] = image.size[::-1] + return model_inputs + + def _forward(self, model_inputs): + target_size = model_inputs.pop("target_size") + model_outputs = self.model(**model_inputs) + model_outputs["target_size"] = target_size + return model_outputs + + def postprocess(self, model_outputs): + outputs = self.image_processor.post_process_depth_estimation( + model_outputs, + # this acts as `source_sizes` for ZoeDepth and as `target_sizes` for the rest of the models so do *not* + # replace with `target_sizes = [model_outputs["target_size"]]` + [model_outputs["target_size"]], + ) + + formatted_outputs = [] + for output in outputs: + depth = output["predicted_depth"].detach().cpu().numpy() + depth = (depth - depth.min()) / (depth.max() - depth.min()) + depth = Image.fromarray((depth * 255).astype("uint8")) + + formatted_outputs.append({"predicted_depth": output["predicted_depth"], "depth": depth}) + + return formatted_outputs[0] if len(outputs) == 1 else formatted_outputs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/document_question_answering.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/document_question_answering.py new file mode 100644 index 0000000000000000000000000000000000000000..de976f9d8750719397ae8be2fcedd25800da8bbf --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/document_question_answering.py @@ -0,0 +1,649 @@ +# Copyright 2022 The Impira Team and the HuggingFace Team. All rights reserved. +# +# 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. + +import re +from typing import Any, Union, overload + +import numpy as np + +from ..generation import GenerationConfig +from ..utils import ( + ExplicitEnum, + add_end_docstrings, + is_pytesseract_available, + is_torch_available, + is_vision_available, + logging, +) +from .base import ChunkPipeline, build_pipeline_init_args + + +if is_vision_available(): + from PIL import Image + + from ..image_utils import load_image + +if is_torch_available(): + import torch + + from ..models.auto.modeling_auto import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES + +TESSERACT_LOADED = False +if is_pytesseract_available(): + TESSERACT_LOADED = True + import pytesseract + +logger = logging.get_logger(__name__) + + +# normalize_bbox() and apply_tesseract() are derived from apply_tesseract in models/layoutlmv3/feature_extraction_layoutlmv3.py. +# However, because the pipeline may evolve from what layoutlmv3 currently does, it's copied (vs. imported) to avoid creating an +# unnecessary dependency. +def normalize_box(box, width, height): + return [ + int(1000 * (box[0] / width)), + int(1000 * (box[1] / height)), + int(1000 * (box[2] / width)), + int(1000 * (box[3] / height)), + ] + + +def decode_spans( + start: np.ndarray, end: np.ndarray, topk: int, max_answer_len: int, undesired_tokens: np.ndarray +) -> tuple: + """ + Take the output of any `ModelForQuestionAnswering` and will generate probabilities for each span to be the actual + answer. + + In addition, it filters out some unwanted/impossible cases like answer len being greater than max_answer_len or + answer end position being before the starting position. The method supports output the k-best answer through the + topk argument. + + Args: + start (`np.ndarray`): Individual start probabilities for each token. + end (`np.ndarray`): Individual end probabilities for each token. + topk (`int`): Indicates how many possible answer span(s) to extract from the model output. + max_answer_len (`int`): Maximum size of the answer to extract from the model's output. + undesired_tokens (`np.ndarray`): Mask determining tokens that can be part of the answer + """ + # Ensure we have batch axis + if start.ndim == 1: + start = start[None] + + if end.ndim == 1: + end = end[None] + + # Compute the score of each tuple(start, end) to be the real answer + outer = np.matmul(np.expand_dims(start, -1), np.expand_dims(end, 1)) + + # Remove candidate with end < start and end - start > max_answer_len + candidates = np.tril(np.triu(outer), max_answer_len - 1) + + # Inspired by Chen & al. (https://github.com/facebookresearch/DrQA) + scores_flat = candidates.flatten() + if topk == 1: + idx_sort = [np.argmax(scores_flat)] + elif len(scores_flat) <= topk: + idx_sort = np.argsort(-scores_flat) + else: + idx = np.argpartition(-scores_flat, topk)[0:topk] + idx_sort = idx[np.argsort(-scores_flat[idx])] + + starts, ends = np.unravel_index(idx_sort, candidates.shape)[1:] + desired_spans = np.isin(starts, undesired_tokens.nonzero()) & np.isin(ends, undesired_tokens.nonzero()) + starts = starts[desired_spans] + ends = ends[desired_spans] + scores = candidates[0, starts, ends] + + return starts, ends, scores + + +def select_starts_ends( + start: np.ndarray, + end: np.ndarray, + p_mask: np.ndarray, + attention_mask: np.ndarray, + min_null_score=1000000, + top_k=1, + handle_impossible_answer=False, + max_answer_len=15, +): + """ + Takes the raw output of any `ModelForQuestionAnswering` and first normalizes its outputs and then uses + `decode_spans()` to generate probabilities for each span to be the actual answer. + + Args: + start (`np.ndarray`): Individual start logits for each token. + end (`np.ndarray`): Individual end logits for each token. + p_mask (`np.ndarray`): A mask with 1 for values that cannot be in the answer + attention_mask (`np.ndarray`): The attention mask generated by the tokenizer + min_null_score(`float`): The minimum null (empty) answer score seen so far. + topk (`int`): Indicates how many possible answer span(s) to extract from the model output. + handle_impossible_answer(`bool`): Whether to allow null (empty) answers + max_answer_len (`int`): Maximum size of the answer to extract from the model's output. + """ + # Ensure padded tokens & question tokens cannot belong to the set of candidate answers. + undesired_tokens = np.abs(np.array(p_mask) - 1) + + if attention_mask is not None: + undesired_tokens = undesired_tokens & attention_mask + + # Generate mask + undesired_tokens_mask = undesired_tokens == 0.0 + + # Make sure non-context indexes in the tensor cannot contribute to the softmax + start = np.where(undesired_tokens_mask, -10000.0, start) + end = np.where(undesired_tokens_mask, -10000.0, end) + + # Normalize logits and spans to retrieve the answer + start = np.exp(start - start.max(axis=-1, keepdims=True)) + start = start / start.sum() + + end = np.exp(end - end.max(axis=-1, keepdims=True)) + end = end / end.sum() + + if handle_impossible_answer: + min_null_score = min(min_null_score, (start[0, 0] * end[0, 0]).item()) + + # Mask CLS + start[0, 0] = end[0, 0] = 0.0 + + starts, ends, scores = decode_spans(start, end, top_k, max_answer_len, undesired_tokens) + return starts, ends, scores, min_null_score + + +def apply_tesseract(image: "Image.Image", lang: str | None, tesseract_config: str | None): + """Applies Tesseract OCR on a document image, and returns recognized words + normalized bounding boxes.""" + # apply OCR + data = pytesseract.image_to_data(image, lang=lang, output_type="dict", config=tesseract_config) + words, left, top, width, height = data["text"], data["left"], data["top"], data["width"], data["height"] + + # filter empty words and corresponding coordinates + irrelevant_indices = [idx for idx, word in enumerate(words) if not word.strip()] + words = [word for idx, word in enumerate(words) if idx not in irrelevant_indices] + left = [coord for idx, coord in enumerate(left) if idx not in irrelevant_indices] + top = [coord for idx, coord in enumerate(top) if idx not in irrelevant_indices] + width = [coord for idx, coord in enumerate(width) if idx not in irrelevant_indices] + height = [coord for idx, coord in enumerate(height) if idx not in irrelevant_indices] + + # turn coordinates into (left, top, left+width, top+height) format + actual_boxes = [] + for x, y, w, h in zip(left, top, width, height): + actual_box = [x, y, x + w, y + h] + actual_boxes.append(actual_box) + + image_width, image_height = image.size + + # finally, normalize the bounding boxes + normalized_boxes = [] + for box in actual_boxes: + normalized_boxes.append(normalize_box(box, image_width, image_height)) + + if len(words) != len(normalized_boxes): + raise ValueError("Not as many words as there are bounding boxes") + + return words, normalized_boxes + + +class ModelType(ExplicitEnum): + LayoutLM = "layoutlm" + LayoutLMv2andv3 = "layoutlmv2andv3" + VisionEncoderDecoder = "vision_encoder_decoder" + + +@add_end_docstrings(build_pipeline_init_args(has_image_processor=True, has_tokenizer=True)) +class DocumentQuestionAnsweringPipeline(ChunkPipeline): + # TODO: Update task_summary docs to include an example with document QA and then update the first sentence + """ + Document Question Answering pipeline using any `AutoModelForDocumentQuestionAnswering`. The inputs/outputs are + similar to the (extractive) question answering pipeline; however, the pipeline takes an image (and optional OCR'd + words/boxes) as input instead of text context. + + Unless the model you're using explicitly sets these generation parameters in its configuration files + (`generation_config.json`), the following default values will be used: + - max_new_tokens: 256 + + Example: + + ```python + >>> from transformers import pipeline + + >>> document_qa = pipeline(model="impira/layoutlm-document-qa") + >>> document_qa( + ... image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png", + ... question="What is the invoice number?", + ... ) + [{'score': 0.425, 'answer': 'us-001', 'start': 16, 'end': 16}] + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) + + This document question answering pipeline can currently be loaded from [`pipeline`] using the following task + identifier: `"document-question-answering"`. + + The models that this pipeline can use are models that have been fine-tuned on a document question answering task. + See the up-to-date list of available models on + [huggingface.co/models](https://huggingface.co/models?filter=document-question-answering). + """ + + _pipeline_calls_generate = True + _load_processor = False + _load_image_processor = None + _load_feature_extractor = None + _load_tokenizer = True + # Make sure the docstring is updated when the default generation config is changed + _default_generation_config = GenerationConfig( + max_new_tokens=256, + ) + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if self.tokenizer is not None and not ( + self.tokenizer.__class__.__name__.endswith("Fast") or self.tokenizer.backend == "tokenizers" + ): + raise ValueError( + "`DocumentQuestionAnsweringPipeline` requires a fast tokenizer, but a slow tokenizer " + f"(`{self.tokenizer.__class__.__name__}`) is provided." + ) + + if self.model.config.__class__.__name__ == "VisionEncoderDecoderConfig": + self.model_type = ModelType.VisionEncoderDecoder + if self.model.config.encoder.model_type != "donut-swin": + raise ValueError("Currently, the only supported VisionEncoderDecoder model is Donut") + else: + self.check_model_type(MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES) + if self.model.config.__class__.__name__ == "LayoutLMConfig": + self.model_type = ModelType.LayoutLM + else: + self.model_type = ModelType.LayoutLMv2andv3 + + def _sanitize_parameters( + self, + padding=None, + doc_stride=None, + max_question_len=None, + lang: str | None = None, + tesseract_config: str | None = None, + max_answer_len=None, + max_seq_len=None, + top_k=None, + handle_impossible_answer=None, + timeout=None, + **kwargs, + ): + preprocess_params, postprocess_params = {}, {} + if padding is not None: + preprocess_params["padding"] = padding + if doc_stride is not None: + preprocess_params["doc_stride"] = doc_stride + if max_question_len is not None: + preprocess_params["max_question_len"] = max_question_len + if max_seq_len is not None: + preprocess_params["max_seq_len"] = max_seq_len + if lang is not None: + preprocess_params["lang"] = lang + if tesseract_config is not None: + preprocess_params["tesseract_config"] = tesseract_config + if timeout is not None: + preprocess_params["timeout"] = timeout + + if top_k is not None: + if top_k < 1: + raise ValueError(f"top_k parameter should be >= 1 (got {top_k})") + postprocess_params["top_k"] = top_k + if max_answer_len is not None: + if max_answer_len < 1: + raise ValueError(f"max_answer_len parameter should be >= 1 (got {max_answer_len})") + postprocess_params["max_answer_len"] = max_answer_len + if handle_impossible_answer is not None: + postprocess_params["handle_impossible_answer"] = handle_impossible_answer + + forward_params = {} + if getattr(self, "assistant_model", None) is not None: + forward_params["assistant_model"] = self.assistant_model + if getattr(self, "assistant_tokenizer", None) is not None: + forward_params["tokenizer"] = self.tokenizer + forward_params["assistant_tokenizer"] = self.assistant_tokenizer + + return preprocess_params, forward_params, postprocess_params + + @overload + def __call__( + self, + image: Union["Image.Image", str], + question: str, + word_boxes: tuple[str, list[float]] | None = None, + **kwargs: Any, + ) -> list[dict[str, Any]]: ... + + @overload + def __call__(self, image: dict[str, Any], **kwargs: Any) -> list[dict[str, Any]]: ... + + @overload + def __call__(self, image: list[dict[str, Any]], **kwargs: Any) -> list[list[dict[str, Any]]]: ... + + def __call__( + self, + image: Union["Image.Image", str, list[dict[str, Any]]], + question: str | None = None, + word_boxes: tuple[str, list[float]] | None = None, + **kwargs: Any, + ) -> dict[str, Any] | list[dict[str, Any]]: + """ + Answer the question(s) given as inputs by using the document(s). A document is defined as an image and an + optional list of (word, box) tuples which represent the text in the document. If the `word_boxes` are not + provided, it will use the Tesseract OCR engine (if available) to extract the words and boxes automatically for + LayoutLM-like models which require them as input. For Donut, no OCR is run. + + You can invoke the pipeline several ways: + + - `pipeline(image=image, question=question)` + - `pipeline(image=image, question=question, word_boxes=word_boxes)` + - `pipeline([{"image": image, "question": question}])` + - `pipeline([{"image": image, "question": question, "word_boxes": word_boxes}])` + + Args: + image (`str` or `PIL.Image`): + The pipeline handles three types of images: + + - A string containing a http link pointing to an image + - A string containing a local path to an image + - An image loaded in PIL directly + + The pipeline accepts either a single image or a batch of images. If given a single image, it can be + broadcasted to multiple questions. + question (`str`): + A question to ask of the document. + word_boxes (`list[str, tuple[float, float, float, float]]`, *optional*): + A list of words and bounding boxes (normalized 0->1000). If you provide this optional input, then the + pipeline will use these words and boxes instead of running OCR on the image to derive them for models + that need them (e.g. LayoutLM). This allows you to reuse OCR'd results across many invocations of the + pipeline without having to re-run it each time. + top_k (`int`, *optional*, defaults to 1): + The number of answers to return (will be chosen by order of likelihood). Note that we return less than + top_k answers if there are not enough options available within the context. + doc_stride (`int`, *optional*, defaults to 128): + If the words in the document are too long to fit with the question for the model, it will be split in + several chunks with some overlap. This argument controls the size of that overlap. + max_answer_len (`int`, *optional*, defaults to 15): + The maximum length of predicted answers (e.g., only answers with a shorter length are considered). + max_seq_len (`int`, *optional*, defaults to 384): + The maximum length of the total sentence (context + question) in tokens of each chunk passed to the + model. The context will be split in several chunks (using `doc_stride` as overlap) if needed. + max_question_len (`int`, *optional*, defaults to 64): + The maximum length of the question after tokenization. It will be truncated if needed. + handle_impossible_answer (`bool`, *optional*, defaults to `False`): + Whether or not we accept impossible as an answer. + lang (`str`, *optional*): + Language to use while running OCR. Defaults to english. + tesseract_config (`str`, *optional*): + Additional flags to pass to tesseract while running OCR. + timeout (`float`, *optional*, defaults to None): + The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and + the call may block forever. + + Return: + A `dict` or a list of `dict`: Each result comes as a dictionary with the following keys: + + - **score** (`float`) -- The probability associated to the answer. + - **start** (`int`) -- The start word index of the answer (in the OCR'd version of the input or provided + `word_boxes`). + - **end** (`int`) -- The end word index of the answer (in the OCR'd version of the input or provided + `word_boxes`). + - **answer** (`str`) -- The answer to the question. + - **words** (`list[int]`) -- The index of each word/box pair that is in the answer + """ + if isinstance(question, str): + inputs = {"question": question, "image": image} + if word_boxes is not None: + inputs["word_boxes"] = word_boxes + else: + inputs = image + return super().__call__(inputs, **kwargs) + + def preprocess( + self, + input, + padding="do_not_pad", + doc_stride=None, + max_seq_len=None, + word_boxes: tuple[str, list[float]] | None = None, + lang=None, + tesseract_config="", + timeout=None, + ): + # NOTE: This code mirrors the code in question answering and will be implemented in a follow up PR + # to support documents with enough tokens that overflow the model's window + if max_seq_len is None: + max_seq_len = self.tokenizer.model_max_length + + if doc_stride is None: + doc_stride = min(max_seq_len // 2, 256) + + image = None + image_features = {} + if input.get("image", None) is not None: + image = load_image(input["image"], timeout=timeout) + if self.image_processor is not None: + image_inputs = self.image_processor(images=image, return_tensors="pt") + image_inputs = image_inputs.to(self.dtype) + image_features.update(image_inputs) + elif self.feature_extractor is not None: + image_features.update(self.feature_extractor(images=image, return_tensors="pt")) + elif self.model_type == ModelType.VisionEncoderDecoder: + raise ValueError("If you are using a VisionEncoderDecoderModel, you must provide a feature extractor") + + words, boxes = None, None + if self.model_type != ModelType.VisionEncoderDecoder: + if "word_boxes" in input: + words = [x[0] for x in input["word_boxes"]] + boxes = [x[1] for x in input["word_boxes"]] + elif "words" in image_features and "boxes" in image_features: + words = image_features.pop("words")[0] + boxes = image_features.pop("boxes")[0] + elif image is not None: + if not TESSERACT_LOADED: + raise ValueError( + "If you provide an image without word_boxes, then the pipeline will run OCR using Tesseract," + " but pytesseract is not available" + ) + if TESSERACT_LOADED: + words, boxes = apply_tesseract(image, lang=lang, tesseract_config=tesseract_config) + else: + raise ValueError( + "You must provide an image or word_boxes. If you provide an image, the pipeline will automatically" + " run OCR to derive words and boxes" + ) + + if self.tokenizer.padding_side != "right": + raise ValueError( + "Document question answering only supports tokenizers whose padding side is 'right', not" + f" {self.tokenizer.padding_side}" + ) + + if self.model_type == ModelType.VisionEncoderDecoder: + task_prompt = f"{input['question']}" + # Adapted from https://huggingface.co/spaces/nielsr/donut-docvqa/blob/main/app.py + encoding = { + "inputs": image_features["pixel_values"], + "decoder_input_ids": self.tokenizer( + task_prompt, add_special_tokens=False, return_tensors="pt" + ).input_ids, + "return_dict_in_generate": True, + } + yield { + **encoding, + "p_mask": None, + "word_ids": None, + "words": None, + "output_attentions": True, + "is_last": True, + } + else: + tokenizer_kwargs = {} + if self.model_type == ModelType.LayoutLM: + tokenizer_kwargs["text"] = input["question"].split() + tokenizer_kwargs["text_pair"] = words + tokenizer_kwargs["is_split_into_words"] = True + else: + tokenizer_kwargs["text"] = [input["question"]] + tokenizer_kwargs["text_pair"] = [words] + tokenizer_kwargs["boxes"] = [boxes] + + encoding = self.tokenizer( + padding=padding, + max_length=max_seq_len, + stride=doc_stride, + return_token_type_ids=True, + truncation="only_second", + return_overflowing_tokens=True, + **tokenizer_kwargs, + ) + # TODO: check why slower `LayoutLMTokenizer` and `LayoutLMv2Tokenizer` don't have this key in outputs + # FIXME: ydshieh and/or Narsil + encoding.pop("overflow_to_sample_mapping", None) # We do not use this + + num_spans = len(encoding["input_ids"]) + + # p_mask: mask with 1 for token than cannot be in the answer (0 for token which can be in an answer) + # We put 0 on the tokens from the context and 1 everywhere else (question and special tokens) + # This logic mirrors the logic in the question_answering pipeline + p_mask = [[tok != 1 for tok in encoding.sequence_ids(span_id)] for span_id in range(num_spans)] + for span_idx in range(num_spans): + span_encoding = {k: torch.tensor(v[span_idx : span_idx + 1]) for (k, v) in encoding.items()} + if "pixel_values" in image_features: + span_encoding["image"] = image_features["pixel_values"] + + input_ids_span_idx = encoding["input_ids"][span_idx] + # keep the cls_token unmasked (some models use it to indicate unanswerable questions) + if self.tokenizer.cls_token_id is not None: + cls_indices = np.nonzero(np.array(input_ids_span_idx) == self.tokenizer.cls_token_id)[0] + for cls_index in cls_indices: + p_mask[span_idx][cls_index] = 0 + + # For each span, place a bounding box [0,0,0,0] for question and CLS tokens, [1000,1000,1000,1000] + # for SEP tokens, and the word's bounding box for words in the original document. + if "boxes" not in tokenizer_kwargs: + bbox = [] + for input_id, sequence_id, word_id in zip( + encoding.input_ids[span_idx], + encoding.sequence_ids(span_idx), + encoding.word_ids(span_idx), + ): + if sequence_id == 1: + bbox.append(boxes[word_id]) + elif input_id == self.tokenizer.sep_token_id: + bbox.append([1000] * 4) + else: + bbox.append([0] * 4) + + span_encoding["bbox"] = torch.tensor(bbox).unsqueeze(0) + yield { + **span_encoding, + "p_mask": p_mask[span_idx], + "word_ids": encoding.word_ids(span_idx), + "words": words, + "is_last": span_idx == num_spans - 1, + } + + def _forward(self, model_inputs, **generate_kwargs): + p_mask = model_inputs.pop("p_mask", None) + word_ids = model_inputs.pop("word_ids", None) + words = model_inputs.pop("words", None) + is_last = model_inputs.pop("is_last", False) + + if self.model_type == ModelType.VisionEncoderDecoder: + # User-defined `generation_config` passed to the pipeline call take precedence + if "generation_config" not in generate_kwargs: + generate_kwargs["generation_config"] = self.generation_config + + model_outputs = self.model.generate(**model_inputs, **generate_kwargs) + else: + model_outputs = self.model(**model_inputs) + + model_outputs = dict(model_outputs.items()) + model_outputs["p_mask"] = p_mask + model_outputs["word_ids"] = word_ids + model_outputs["words"] = words + model_outputs["attention_mask"] = model_inputs.get("attention_mask", None) + model_outputs["is_last"] = is_last + return model_outputs + + def postprocess(self, model_outputs, top_k=1, **kwargs): + if self.model_type == ModelType.VisionEncoderDecoder: + answers = [self.postprocess_encoder_decoder_single(o) for o in model_outputs] + else: + answers = self.postprocess_extractive_qa(model_outputs, top_k=top_k, **kwargs) + + answers = sorted(answers, key=lambda x: x.get("score", 0), reverse=True)[:top_k] + return answers + + def postprocess_encoder_decoder_single(self, model_outputs, **kwargs): + sequence = self.tokenizer.batch_decode(model_outputs["sequences"])[0] + + # TODO: A lot of this logic is specific to Donut and should probably be handled in the tokenizer + # (see https://github.com/huggingface/transformers/pull/18414/files#r961747408 for more context). + sequence = sequence.replace(self.tokenizer.eos_token, "").replace(self.tokenizer.pad_token, "") + sequence = re.sub(r"<.*?>", "", sequence, count=1).strip() # remove first task start token + ret = { + "answer": None, + } + + answer = re.search(r"(.*)", sequence) + if answer is not None: + ret["answer"] = answer.group(1).strip() + return ret + + def postprocess_extractive_qa( + self, model_outputs, top_k=1, handle_impossible_answer=False, max_answer_len=15, **kwargs + ): + min_null_score = 1000000 # large and positive + answers = [] + for output in model_outputs: + words = output["words"] + + if output["start_logits"].dtype in (torch.bfloat16, torch.float16): + output["start_logits"] = output["start_logits"].float() + if output["end_logits"].dtype in (torch.bfloat16, torch.float16): + output["end_logits"] = output["end_logits"].float() + + starts, ends, scores, min_null_score = select_starts_ends( + start=output["start_logits"], + end=output["end_logits"], + p_mask=output["p_mask"], + attention_mask=output["attention_mask"].numpy() + if output.get("attention_mask", None) is not None + else None, + min_null_score=min_null_score, + top_k=top_k, + handle_impossible_answer=handle_impossible_answer, + max_answer_len=max_answer_len, + ) + word_ids = output["word_ids"] + for start, end, score in zip(starts, ends, scores): + word_start, word_end = word_ids[start], word_ids[end] + if word_start is not None and word_end is not None: + answers.append( + { + "score": float(score), + "answer": " ".join(words[word_start : word_end + 1]), + "start": word_start, + "end": word_end, + } + ) + + if handle_impossible_answer: + answers.append({"score": min_null_score, "answer": "", "start": 0, "end": 0}) + + return answers diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/feature_extraction.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/feature_extraction.py new file mode 100644 index 0000000000000000000000000000000000000000..a37f147605f04347efa34f587d7fdebe8074f3b5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/feature_extraction.py @@ -0,0 +1,88 @@ +from typing import Any + +from ..utils import add_end_docstrings +from .base import GenericTensor, Pipeline, build_pipeline_init_args + + +@add_end_docstrings( + build_pipeline_init_args(has_tokenizer=True, supports_binary_output=False), + r""" + tokenize_kwargs (`dict`, *optional*): + Additional dictionary of keyword arguments passed along to the tokenizer. + return_tensors (`bool`, *optional*): + If `True`, returns a tensor according to the specified framework, otherwise returns a list.""", +) +class FeatureExtractionPipeline(Pipeline): + """ + Feature extraction pipeline uses no model head. This pipeline extracts the hidden states from the base + transformer, which can be used as features in downstream tasks. + + Example: + + ```python + >>> from transformers import pipeline + + >>> extractor = pipeline(model="google-bert/bert-base-uncased", task="feature-extraction") + >>> result = extractor("This is a simple test.", return_tensors=True) + >>> result.shape # This is a tensor of shape [1, sequence_length, hidden_dimension] representing the input string. + torch.Size([1, 8, 768]) + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) + + This feature extraction pipeline can currently be loaded from [`pipeline`] using the task identifier: + `"feature-extraction"`. + + All models may be used for this pipeline. See a list of all models, including community-contributed models on + [huggingface.co/models](https://huggingface.co/models). + """ + + _load_processor = False + _load_image_processor = False + _load_feature_extractor = False + _load_tokenizer = True + + def _sanitize_parameters(self, truncation=None, tokenize_kwargs=None, return_tensors=None, **kwargs): + if tokenize_kwargs is None: + tokenize_kwargs = {} + + if truncation is not None: + if "truncation" in tokenize_kwargs: + raise ValueError( + "truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)" + ) + tokenize_kwargs["truncation"] = truncation + + preprocess_params = tokenize_kwargs + + postprocess_params = {} + if return_tensors is not None: + postprocess_params["return_tensors"] = return_tensors + + return preprocess_params, {}, postprocess_params + + def preprocess(self, inputs, **tokenize_kwargs) -> dict[str, GenericTensor]: + model_inputs = self.tokenizer(inputs, return_tensors="pt", **tokenize_kwargs) + return model_inputs + + def _forward(self, model_inputs): + model_outputs = self.model(**model_inputs) + return model_outputs + + def postprocess(self, model_outputs, return_tensors=False): + # [0] is the first available tensor, logits or last_hidden_state. + if return_tensors: + return model_outputs[0] + return model_outputs[0].tolist() + + def __call__(self, *args: str | list[str], **kwargs: Any) -> Any | list[Any]: + """ + Extract the features of the input(s) text. + + Args: + args (`str` or `list[str]`): One or several texts (or one list of texts) to get the features of. + + Return: + A nested list of `float`: The features computed by the model. + """ + return super().__call__(*args, **kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/fill_mask.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/fill_mask.py new file mode 100644 index 0000000000000000000000000000000000000000..1ea7c487be76458ff66508a6506bc11437937cb1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/fill_mask.py @@ -0,0 +1,259 @@ +from typing import Any, overload + +import numpy as np + +from ..utils import add_end_docstrings, is_torch_available, logging +from .base import GenericTensor, Pipeline, PipelineException, build_pipeline_init_args + + +if is_torch_available(): + import torch + + +logger = logging.get_logger(__name__) + + +@add_end_docstrings( + build_pipeline_init_args(has_tokenizer=True), + r""" + top_k (`int`, *optional*, defaults to 5): + The number of predictions to return. + targets (`str` or `list[str]`, *optional*): + When passed, the model will limit the scores to the passed targets instead of looking up in the whole + vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting + token will be used (with a warning, and that might be slower). + tokenizer_kwargs (`dict`, *optional*): + Additional dictionary of keyword arguments passed along to the tokenizer.""", +) +class FillMaskPipeline(Pipeline): + _load_processor = False + _load_image_processor = False + _load_feature_extractor = False + _load_tokenizer = True + + """ + Masked language modeling prediction pipeline using any `ModelWithLMHead`. See the [masked language modeling + examples](../task_summary#masked-language-modeling) for more information. + + Example: + + ```python + >>> from transformers import pipeline + + >>> fill_masker = pipeline(model="google-bert/bert-base-uncased") + >>> fill_masker("This is a simple [MASK].") + [{'score': 0.042, 'token': 3291, 'token_str': 'problem', 'sequence': 'this is a simple problem.'}, {'score': 0.031, 'token': 3160, 'token_str': 'question', 'sequence': 'this is a simple question.'}, {'score': 0.03, 'token': 8522, 'token_str': 'equation', 'sequence': 'this is a simple equation.'}, {'score': 0.027, 'token': 2028, 'token_str': 'one', 'sequence': 'this is a simple one.'}, {'score': 0.024, 'token': 3627, 'token_str': 'rule', 'sequence': 'this is a simple rule.'}] + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) + + This mask filling pipeline can currently be loaded from [`pipeline`] using the following task identifier: + `"fill-mask"`. + + The models that this pipeline can use are models that have been trained with a masked language modeling objective, + which includes the bi-directional models in the library. See the up-to-date list of available models on + [huggingface.co/models](https://huggingface.co/models?filter=fill-mask). + + + + This pipeline only works for inputs with exactly one token masked. Experimental: We added support for multiple + masks. The returned values are raw model output, and correspond to disjoint probabilities where one might expect + joint probabilities (See [discussion](https://github.com/huggingface/transformers/pull/10222)). + + + + + + This pipeline now supports tokenizer_kwargs. For example try: + + ```python + >>> from transformers import pipeline + + >>> fill_masker = pipeline(model="google-bert/bert-base-uncased") + >>> tokenizer_kwargs = {"truncation": True} + >>> fill_masker( + ... "This is a simple [MASK]. " + "...with a large amount of repeated text appended. " * 100, + ... tokenizer_kwargs=tokenizer_kwargs, + ... ) + ``` + + + + + + """ + + def get_masked_index(self, input_ids: GenericTensor) -> np.ndarray: + masked_index = torch.nonzero(input_ids == self.tokenizer.mask_token_id, as_tuple=False) + return masked_index + + def _ensure_exactly_one_mask_token(self, input_ids: GenericTensor) -> np.ndarray: + masked_index = self.get_masked_index(input_ids) + numel = np.prod(masked_index.shape) + if numel < 1: + raise PipelineException( + "fill-mask", + self.model.base_model_prefix, + f"No mask_token ({self.tokenizer.mask_token}) found on the input", + ) + + def ensure_exactly_one_mask_token(self, model_inputs: GenericTensor): + if isinstance(model_inputs, list): + for model_input in model_inputs: + self._ensure_exactly_one_mask_token(model_input["input_ids"][0]) + else: + for input_ids in model_inputs["input_ids"]: + self._ensure_exactly_one_mask_token(input_ids) + + def preprocess( + self, inputs, return_tensors=None, tokenizer_kwargs=None, **preprocess_parameters + ) -> dict[str, GenericTensor]: + if return_tensors is None: + return_tensors = "pt" + if tokenizer_kwargs is None: + tokenizer_kwargs = {} + + model_inputs = self.tokenizer(inputs, return_tensors=return_tensors, **tokenizer_kwargs) + self.ensure_exactly_one_mask_token(model_inputs) + return model_inputs + + def _forward(self, model_inputs): + model_outputs = self.model(**model_inputs) + model_outputs["input_ids"] = model_inputs["input_ids"] + return model_outputs + + def postprocess(self, model_outputs, top_k=5, target_ids=None): + # Cap top_k if there are targets + if target_ids is not None and target_ids.shape[0] < top_k: + top_k = target_ids.shape[0] + input_ids = model_outputs["input_ids"][0] + outputs = model_outputs["logits"] + + masked_index = torch.nonzero(input_ids == self.tokenizer.mask_token_id, as_tuple=False).squeeze(-1) + # Fill mask pipeline supports only one ${mask_token} per sample + + logits = outputs[0, masked_index, :] + probs = logits.softmax(dim=-1) + if target_ids is not None: + probs = probs[..., target_ids] + + values, predictions = probs.topk(top_k) + + result = [] + single_mask = values.shape[0] == 1 + for i, (_values, _predictions) in enumerate(zip(values.tolist(), predictions.tolist())): + row = [] + for v, p in zip(_values, _predictions): + # Copy is important since we're going to modify this array in place + tokens = input_ids.numpy().copy() + if target_ids is not None: + p = target_ids[p].tolist() + + tokens[masked_index[i]] = p + # Filter padding out: + tokens = tokens[np.where(tokens != self.tokenizer.pad_token_id)] + # Originally we skip special tokens to give readable output. + # For multi masks though, the other [MASK] would be removed otherwise + # making the output look odd, so we add them back + sequence = self.tokenizer.decode(tokens, skip_special_tokens=single_mask) + proposition = {"score": v, "token": p, "token_str": self.tokenizer.decode([p]), "sequence": sequence} + row.append(proposition) + result.append(row) + if single_mask: + return result[0] + return result + + def get_target_ids(self, targets): + if isinstance(targets, str): + targets = [targets] + try: + vocab = self.tokenizer.get_vocab() + except Exception: + vocab = {} + target_ids = [] + for target in targets: + id_ = vocab.get(target) + if id_ is None: + input_ids = self.tokenizer( + target, + add_special_tokens=False, + return_attention_mask=False, + return_token_type_ids=False, + max_length=1, + truncation=True, + )["input_ids"] + if len(input_ids) == 0: + logger.warning( + f"The specified target token `{target}` does not exist in the model vocabulary. " + "We cannot replace it with anything meaningful, ignoring it" + ) + continue + id_ = input_ids[0] + # XXX: If users encounter this pass + # it becomes pretty slow, so let's make sure + # The warning enables them to fix the input to + # get faster performance. + logger.warning( + f"The specified target token `{target}` does not exist in the model vocabulary. " + f"Replacing with `{self.tokenizer.convert_ids_to_tokens(id_)}`." + ) + target_ids.append(id_) + target_ids = list(set(target_ids)) + if len(target_ids) == 0: + raise ValueError("At least one target must be provided when passed.") + target_ids = np.array(target_ids) + return target_ids + + def _sanitize_parameters(self, top_k=None, targets=None, tokenizer_kwargs=None): + preprocess_params = {} + + if tokenizer_kwargs is not None: + preprocess_params["tokenizer_kwargs"] = tokenizer_kwargs + + postprocess_params = {} + + if targets is not None: + target_ids = self.get_target_ids(targets) + postprocess_params["target_ids"] = target_ids + + if top_k is not None: + postprocess_params["top_k"] = top_k + + if self.tokenizer.mask_token_id is None: + raise PipelineException( + "fill-mask", self.model.base_model_prefix, "The tokenizer does not define a `mask_token`." + ) + return preprocess_params, {}, postprocess_params + + @overload + def __call__(self, inputs: str, **kwargs: Any) -> list[dict[str, Any]]: ... + + @overload + def __call__(self, inputs: list[str], **kwargs: Any) -> list[list[dict[str, Any]]]: ... + + def __call__(self, inputs: str | list[str], **kwargs: Any) -> list[dict[str, Any]] | list[list[dict[str, Any]]]: + """ + Fill the masked token in the text(s) given as inputs. + + Args: + inputs (`str` or `list[str]`): + One or several texts (or one list of prompts) with masked tokens. + targets (`str` or `list[str]`, *optional*): + When passed, the model will limit the scores to the passed targets instead of looking up in the whole + vocab. If the provided targets are not in the model vocab, they will be tokenized and the first + resulting token will be used (with a warning, and that might be slower). + top_k (`int`, *optional*): + When passed, overrides the number of predictions to return. + + Return: + A list or a list of list of `dict`: Each result comes as list of dictionaries with the following keys: + + - **sequence** (`str`) -- The corresponding input with the mask token prediction. + - **score** (`float`) -- The corresponding probability. + - **token** (`int`) -- The predicted token id (to replace the masked one). + - **token_str** (`str`) -- The predicted token (to replace the masked one). + """ + outputs = super().__call__(inputs, **kwargs) + if isinstance(inputs, list) and len(inputs) == 1: + return outputs[0] + return outputs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/image_classification.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/image_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..18a570df6e21f8e7ebd15d7771408cf324e306de --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/image_classification.py @@ -0,0 +1,229 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# 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. +from typing import Any, Union, overload + +import numpy as np + +from ..utils import ( + ExplicitEnum, + add_end_docstrings, + is_torch_available, + is_vision_available, + logging, + requires_backends, +) +from .base import Pipeline, build_pipeline_init_args + + +if is_vision_available(): + from PIL import Image + + from ..image_utils import load_image + +if is_torch_available(): + import torch + + from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES + +logger = logging.get_logger(__name__) + + +# Copied from transformers.pipelines.text_classification.sigmoid +def sigmoid(_outputs): + return 1.0 / (1.0 + np.exp(-_outputs)) + + +# Copied from transformers.pipelines.text_classification.softmax +def softmax(_outputs): + maxes = np.max(_outputs, axis=-1, keepdims=True) + shifted_exp = np.exp(_outputs - maxes) + return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True) + + +# Copied from transformers.pipelines.text_classification.ClassificationFunction +class ClassificationFunction(ExplicitEnum): + SIGMOID = "sigmoid" + SOFTMAX = "softmax" + NONE = "none" + + +@add_end_docstrings( + build_pipeline_init_args(has_image_processor=True), + r""" + function_to_apply (`str`, *optional*, defaults to `"default"`): + The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: + + - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model + has several labels, will apply the softmax function on the output. + - `"sigmoid"`: Applies the sigmoid function on the output. + - `"softmax"`: Applies the softmax function on the output. + - `"none"`: Does not apply any function on the output.""", +) +class ImageClassificationPipeline(Pipeline): + """ + Image classification pipeline using any `AutoModelForImageClassification`. This pipeline predicts the class of an + image. + + Example: + + ```python + >>> from transformers import pipeline + + >>> classifier = pipeline(model="microsoft/beit-base-patch16-224-pt22k-ft22k") + >>> classifier("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png") + [{'score': 0.442, 'label': 'macaw'}, {'score': 0.088, 'label': 'popinjay'}, {'score': 0.075, 'label': 'parrot'}, {'score': 0.073, 'label': 'parodist, lampooner'}, {'score': 0.046, 'label': 'poll, poll_parrot'}] + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) + + This image classification pipeline can currently be loaded from [`pipeline`] using the following task identifier: + `"image-classification"`. + + See the list of available models on + [huggingface.co/models](https://huggingface.co/models?filter=image-classification). + """ + + function_to_apply: ClassificationFunction = ClassificationFunction.NONE + _load_processor = False + _load_image_processor = True + _load_feature_extractor = False + _load_tokenizer = False + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + requires_backends(self, "vision") + self.check_model_type(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES) + + def _sanitize_parameters(self, top_k=None, function_to_apply=None, timeout=None): + preprocess_params = {} + if timeout is not None: + preprocess_params["timeout"] = timeout + postprocess_params = {} + if top_k is not None: + postprocess_params["top_k"] = top_k + if isinstance(function_to_apply, str): + function_to_apply = ClassificationFunction(function_to_apply.lower()) + if function_to_apply is not None: + postprocess_params["function_to_apply"] = function_to_apply + return preprocess_params, {}, postprocess_params + + @overload + def __call__(self, inputs: Union[str, "Image.Image"], **kwargs: Any) -> list[dict[str, Any]]: ... + + @overload + def __call__(self, inputs: list[str] | list["Image.Image"], **kwargs: Any) -> list[list[dict[str, Any]]]: ... + + def __call__( + self, inputs: Union[str, list[str], "Image.Image", list["Image.Image"]], **kwargs: Any + ) -> list[dict[str, Any]] | list[list[dict[str, Any]]]: + """ + Assign labels to the image(s) passed as inputs. + + Args: + inputs (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`): + The pipeline handles three types of images: + + - A string containing a http link pointing to an image + - A string containing a local path to an image + - An image loaded in PIL directly + + The pipeline accepts either a single image or a batch of images, which must then be passed as a string. + Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL + images. + function_to_apply (`str`, *optional*, defaults to `"default"`): + The function to apply to the model outputs in order to retrieve the scores. Accepts four different + values: + + If this argument is not specified, then it will apply the following functions according to the number + of labels: + + - If the model has a single label, will apply the sigmoid function on the output. + - If the model has several labels, will apply the softmax function on the output. + + Possible values are: + + - `"sigmoid"`: Applies the sigmoid function on the output. + - `"softmax"`: Applies the softmax function on the output. + - `"none"`: Does not apply any function on the output. + top_k (`int`, *optional*, defaults to 5): + The number of top labels that will be returned by the pipeline. If the provided number is higher than + the number of labels available in the model configuration, it will default to the number of labels. + timeout (`float`, *optional*, defaults to None): + The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and + the call may block forever. + + Return: + A dictionary or a list of dictionaries containing result. If the input is a single image, will return a + dictionary, if the input is a list of several images, will return a list of dictionaries corresponding to + the images. + + The dictionaries contain the following keys: + + - **label** (`str`) -- The label identified by the model. + - **score** (`int`) -- The score attributed by the model for that label. + """ + # After deprecation of this is completed, remove the default `None` value for `images` + if "images" in kwargs: + inputs = kwargs.pop("images") + if inputs is None: + raise ValueError("Cannot call the image-classification pipeline without an inputs argument!") + return super().__call__(inputs, **kwargs) + + def preprocess(self, image, timeout=None): + image = load_image(image, timeout=timeout) + model_inputs = self.image_processor(images=image, return_tensors="pt") + model_inputs = model_inputs.to(self.dtype) + return model_inputs + + def _forward(self, model_inputs): + model_outputs = self.model(**model_inputs) + return model_outputs + + def postprocess(self, model_outputs, function_to_apply=None, top_k=5): + if function_to_apply is None: + if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: + function_to_apply = ClassificationFunction.SIGMOID + elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: + function_to_apply = ClassificationFunction.SOFTMAX + elif hasattr(self.model.config, "function_to_apply") and function_to_apply is None: + function_to_apply = self.model.config.function_to_apply + else: + function_to_apply = ClassificationFunction.NONE + + if top_k > self.model.config.num_labels: + top_k = self.model.config.num_labels + + outputs = model_outputs["logits"][0] + if outputs.dtype in (torch.bfloat16, torch.float16): + outputs = outputs.to(torch.float32).numpy() + else: + outputs = outputs.numpy() + + if function_to_apply == ClassificationFunction.SIGMOID: + scores = sigmoid(outputs) + elif function_to_apply == ClassificationFunction.SOFTMAX: + scores = softmax(outputs) + elif function_to_apply == ClassificationFunction.NONE: + scores = outputs + else: + raise ValueError(f"Unrecognized `function_to_apply` argument: {function_to_apply}") + + dict_scores = [ + {"label": self.model.config.id2label[i], "score": score.item()} for i, score in enumerate(scores) + ] + dict_scores.sort(key=lambda x: x["score"], reverse=True) + if top_k is not None: + dict_scores = dict_scores[:top_k] + + return dict_scores diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/image_feature_extraction.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/image_feature_extraction.py new file mode 100644 index 0000000000000000000000000000000000000000..d049957a4138ac44a3a097832a4e754a3fddd0d7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/image_feature_extraction.py @@ -0,0 +1,115 @@ +from typing import Any, Union + +from ..utils import add_end_docstrings, is_vision_available +from .base import GenericTensor, Pipeline, build_pipeline_init_args + + +if is_vision_available(): + from PIL import Image + + from ..image_utils import load_image + + +@add_end_docstrings( + build_pipeline_init_args(has_image_processor=True), + """ + image_processor_kwargs (`dict`, *optional*): + Additional dictionary of keyword arguments passed along to the image processor e.g. + {"size": {"height": 100, "width": 100}} + pool (`bool`, *optional*, defaults to `False`): + Whether or not to return the pooled output. If `False`, the model will return the raw hidden states. + """, +) +class ImageFeatureExtractionPipeline(Pipeline): + """ + Image feature extraction pipeline uses no model head. This pipeline extracts the hidden states from the base + transformer, which can be used as features in downstream tasks. + + Example: + + ```python + >>> from transformers import pipeline + + >>> extractor = pipeline(model="google/vit-base-patch16-224", task="image-feature-extraction") + >>> result = extractor("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", return_tensors=True) + >>> result.shape # This is a tensor of shape [1, sequence_length, hidden_dimension] representing the input image. + torch.Size([1, 197, 768]) + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) + + This image feature extraction pipeline can currently be loaded from [`pipeline`] using the task identifier: + `"image-feature-extraction"`. + + All vision models may be used for this pipeline. See a list of all models, including community-contributed models on + [huggingface.co/models](https://huggingface.co/models). + """ + + _load_processor = False + _load_image_processor = True + _load_feature_extractor = False + _load_tokenizer = False + + def _sanitize_parameters(self, image_processor_kwargs=None, return_tensors=None, pool=None, **kwargs): + preprocess_params = {} if image_processor_kwargs is None else image_processor_kwargs + + postprocess_params = {} + if pool is not None: + postprocess_params["pool"] = pool + if return_tensors is not None: + postprocess_params["return_tensors"] = return_tensors + + if "timeout" in kwargs: + preprocess_params["timeout"] = kwargs["timeout"] + + return preprocess_params, {}, postprocess_params + + def preprocess(self, image, timeout=None, **image_processor_kwargs) -> dict[str, GenericTensor]: + image = load_image(image, timeout=timeout) + model_inputs = self.image_processor(image, return_tensors="pt", **image_processor_kwargs) + model_inputs = model_inputs.to(self.dtype) + return model_inputs + + def _forward(self, model_inputs): + model_outputs = self.model(**model_inputs) + return model_outputs + + def postprocess(self, model_outputs, pool=None, return_tensors=False): + pool = pool if pool is not None else False + + if pool: + if "pooler_output" not in model_outputs: + raise ValueError( + "No pooled output was returned. Make sure the model has a `pooler` layer when using the `pool` option." + ) + outputs = model_outputs["pooler_output"] + else: + # [0] is the first available tensor, logits or last_hidden_state. + outputs = model_outputs[0] + + if return_tensors: + return outputs + return outputs.tolist() + + def __call__(self, *args: Union[str, "Image.Image", list["Image.Image"], list[str]], **kwargs: Any) -> list[Any]: + """ + Extract the features of the input(s). + + Args: + images (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`): + The pipeline handles three types of images: + + - A string containing a http link pointing to an image + - A string containing a local path to an image + - An image loaded in PIL directly + + The pipeline accepts either a single image or a batch of images, which must then be passed as a string. + Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL + images. + timeout (`float`, *optional*, defaults to None): + The maximum time in seconds to wait for fetching images from the web. If None, no timeout is used and + the call may block forever. + Return: + A nested list of `float`: The features computed by the model. + """ + return super().__call__(*args, **kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/image_segmentation.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/image_segmentation.py new file mode 100644 index 0000000000000000000000000000000000000000..49854beb5a40b1c3017febba20b72678e81b9374 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/image_segmentation.py @@ -0,0 +1,223 @@ +from typing import Any, Union, overload + +import numpy as np + +from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends +from .base import Pipeline, build_pipeline_init_args + + +if is_vision_available(): + from PIL import Image + + from ..image_utils import load_image + +if is_torch_available(): + from ..models.auto.modeling_auto import ( + MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES, + MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING_NAMES, + MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, + MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES, + ) + + +logger = logging.get_logger(__name__) + + +@add_end_docstrings(build_pipeline_init_args(has_image_processor=True)) +class ImageSegmentationPipeline(Pipeline): + """ + Image segmentation pipeline using any `AutoModelForXXXSegmentation`. This pipeline predicts masks of objects and + their classes. + + Example: + + ```python + >>> from transformers import pipeline + + >>> segmenter = pipeline(model="facebook/detr-resnet-50-panoptic") + >>> segments = segmenter("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png") + >>> len(segments) + 2 + + >>> segments[0]["label"] + 'bird' + + >>> segments[1]["label"] + 'bird' + + >>> type(segments[0]["mask"]) # This is a black and white mask showing where is the bird on the original image. + + + >>> segments[0]["mask"].size + (768, 512) + ``` + + + This image segmentation pipeline can currently be loaded from [`pipeline`] using the following task identifier: + `"image-segmentation"`. + + See the list of available models on + [huggingface.co/models](https://huggingface.co/models?filter=image-segmentation). + """ + + _load_processor = False + _load_image_processor = True + _load_feature_extractor = False + _load_tokenizer = None # Oneformer uses it but no-one else does + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + requires_backends(self, "vision") + mapping = MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES.copy() + mapping.update(MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES) + mapping.update(MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING_NAMES) + mapping.update(MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES) + self.check_model_type(mapping) + + def _sanitize_parameters(self, **kwargs): + preprocess_kwargs = {} + postprocess_kwargs = {} + if "subtask" in kwargs: + postprocess_kwargs["subtask"] = kwargs["subtask"] + preprocess_kwargs["subtask"] = kwargs["subtask"] + if "threshold" in kwargs: + postprocess_kwargs["threshold"] = kwargs["threshold"] + if "mask_threshold" in kwargs: + postprocess_kwargs["mask_threshold"] = kwargs["mask_threshold"] + if "overlap_mask_area_threshold" in kwargs: + postprocess_kwargs["overlap_mask_area_threshold"] = kwargs["overlap_mask_area_threshold"] + if "timeout" in kwargs: + preprocess_kwargs["timeout"] = kwargs["timeout"] + + return preprocess_kwargs, {}, postprocess_kwargs + + @overload + def __call__(self, inputs: Union[str, "Image.Image"], **kwargs: Any) -> list[dict[str, Any]]: ... + + @overload + def __call__(self, inputs: list[str] | list["Image.Image"], **kwargs: Any) -> list[list[dict[str, Any]]]: ... + + def __call__( + self, inputs: Union[str, "Image.Image", list[str], list["Image.Image"]], **kwargs: Any + ) -> list[dict[str, Any]] | list[list[dict[str, Any]]]: + """ + Perform segmentation (detect masks & classes) in the image(s) passed as inputs. + + Args: + inputs (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`): + The pipeline handles three types of images: + + - A string containing an HTTP(S) link pointing to an image + - A string containing a local path to an image + - An image loaded in PIL directly + + The pipeline accepts either a single image or a batch of images. Images in a batch must all be in the + same format: all as HTTP(S) links, all as local paths, or all as PIL images. + subtask (`str`, *optional*): + Segmentation task to be performed, choose [`semantic`, `instance` and `panoptic`] depending on model + capabilities. If not set, the pipeline will attempt tp resolve in the following order: + `panoptic`, `instance`, `semantic`. + threshold (`float`, *optional*, defaults to 0.9): + Probability threshold to filter out predicted masks. + mask_threshold (`float`, *optional*, defaults to 0.5): + Threshold to use when turning the predicted masks into binary values. + overlap_mask_area_threshold (`float`, *optional*, defaults to 0.5): + Mask overlap threshold to eliminate small, disconnected segments. + timeout (`float`, *optional*, defaults to None): + The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and + the call may block forever. + + Return: + If the input is a single image, will return a list of dictionaries, if the input is a list of several images, + will return a list of list of dictionaries corresponding to each image. + + The dictionaries contain the mask, label and score (where applicable) of each detected object and contains + the following keys: + + - **label** (`str`) -- The class label identified by the model. + - **mask** (`PIL.Image`) -- A binary mask of the detected object as a Pil Image of shape (width, height) of + the original image. Returns a mask filled with zeros if no object is found. + - **score** (*optional* `float`) -- Optionally, when the model is capable of estimating a confidence of the + "object" described by the label and the mask. + """ + # After deprecation of this is completed, remove the default `None` value for `images` + if "images" in kwargs: + inputs = kwargs.pop("images") + if inputs is None: + raise ValueError("Cannot call the image-classification pipeline without an inputs argument!") + return super().__call__(inputs, **kwargs) + + def preprocess(self, image, subtask=None, timeout=None): + image = load_image(image, timeout=timeout) + target_size = [(image.height, image.width)] + if self.model.config.__class__.__name__ == "OneFormerConfig": + if subtask is None: + kwargs = {} + else: + kwargs = {"task_inputs": [subtask]} + inputs = self.image_processor(images=[image], return_tensors="pt", **kwargs) + inputs = inputs.to(self.dtype) + inputs["task_inputs"] = self.tokenizer( + inputs["task_inputs"], + padding="max_length", + max_length=self.model.config.task_seq_len, + return_tensors="pt", + )["input_ids"] + else: + inputs = self.image_processor(images=[image], return_tensors="pt") + inputs = inputs.to(self.dtype) + inputs["target_size"] = target_size + return inputs + + def _forward(self, model_inputs): + target_size = model_inputs.pop("target_size") + model_outputs = self.model(**model_inputs) + model_outputs["target_size"] = target_size + return model_outputs + + def postprocess( + self, model_outputs, subtask=None, threshold=0.9, mask_threshold=0.5, overlap_mask_area_threshold=0.5 + ): + fn = None + if subtask in {"panoptic", None} and hasattr(self.image_processor, "post_process_panoptic_segmentation"): + fn = self.image_processor.post_process_panoptic_segmentation + elif subtask in {"instance", None} and hasattr(self.image_processor, "post_process_instance_segmentation"): + fn = self.image_processor.post_process_instance_segmentation + + if fn is not None: + outputs = fn( + model_outputs, + threshold=threshold, + mask_threshold=mask_threshold, + overlap_mask_area_threshold=overlap_mask_area_threshold, + target_sizes=model_outputs["target_size"], + )[0] + + annotation = [] + segmentation = outputs["segmentation"] + + for segment in outputs["segments_info"]: + mask = (segmentation == segment["id"]) * 255 + mask = Image.fromarray(mask.numpy().astype(np.uint8), mode="L") + label = self.model.config.id2label[segment["label_id"]] + score = segment["score"] + annotation.append({"score": score, "label": label, "mask": mask}) + + elif subtask in {"semantic", None} and hasattr(self.image_processor, "post_process_semantic_segmentation"): + outputs = self.image_processor.post_process_semantic_segmentation( + model_outputs, target_sizes=model_outputs["target_size"] + )[0] + + annotation = [] + segmentation = outputs.numpy() + labels = np.unique(segmentation) + + for label in labels: + mask = (segmentation == label) * 255 + mask = Image.fromarray(mask.astype(np.uint8), mode="L") + label = self.model.config.id2label[label] + annotation.append({"score": None, "label": label, "mask": mask}) + else: + raise ValueError(f"Subtask {subtask} is not supported for model {type(self.model)}") + return annotation diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/image_text_to_text.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/image_text_to_text.py new file mode 100644 index 0000000000000000000000000000000000000000..7d28b91ab2ab9a8db3110f3aff05ded52454ec7b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/image_text_to_text.py @@ -0,0 +1,480 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# 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. + +import enum +from typing import Any, Union, overload + +from ..generation import GenerationConfig +from ..processing_utils import ProcessingKwargs, Unpack +from ..utils import ( + add_end_docstrings, + is_torch_available, + is_vision_available, + logging, + requires_backends, +) +from ..utils.chat_template_utils import Chat +from .base import Pipeline, build_pipeline_init_args + + +if is_vision_available(): + from PIL import Image + + from ..image_utils import load_images, valid_images + + +if is_torch_available(): + from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES + from .pt_utils import KeyDataset + +logger = logging.get_logger(__name__) + +IMAGE_TOKEN = "" + + +class ReturnType(enum.Enum): + TENSORS = 0 + NEW_TEXT = 1 + FULL_TEXT = 2 + + +@add_end_docstrings(build_pipeline_init_args(has_processor=True)) +class ImageTextToTextPipeline(Pipeline): + """ + Image-text-to-text pipeline using an `AutoModelForImageTextToText`. This pipeline generates text given an image and text. + When the underlying model is a conversational model, it can also accept one or more chats, + in which case the pipeline will operate in chat mode and will continue the chat(s) by adding its response(s). + Each chat takes the form of a list of dicts, where each dict contains "role" and "content" keys. + + Unless the model you're using explicitly sets these generation parameters in its configuration files + (`generation_config.json`), the following default values will be used: + - max_new_tokens: 256 + + Example: + + ```python + >>> from transformers import pipeline + + >>> pipe = pipeline(task="image-text-to-text", model="Salesforce/blip-image-captioning-base") + >>> pipe("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", text="A photo of") + [{'generated_text': 'a photo of two birds'}] + ``` + + ```python + >>> from transformers import pipeline + + >>> pipe = pipeline("image-text-to-text", model="llava-hf/llava-interleave-qwen-0.5b-hf") + >>> messages = [ + >>> { + >>> "role": "user", + >>> "content": [ + >>> { + >>> "type": "image", + >>> "url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg", + >>> }, + >>> {"type": "text", "text": "Describe this image."}, + >>> ], + >>> }, + >>> { + >>> "role": "assistant", + >>> "content": [ + >>> {"type": "text", "text": "There is a dog and"}, + >>> ], + >>> }, + >>> ] + >>> pipe(text=messages, max_new_tokens=20, return_full_text=False) + [{'input_text': [{'role': 'user', + 'content': [{'type': 'image', + 'url': 'https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg'}, + {'type': 'text', 'text': 'Describe this image.'}]}, + {'role': 'assistant', + 'content': [{'type': 'text', 'text': 'There is a dog and'}]}], + 'generated_text': ' a person in the image. The dog is sitting on the sand, and the person is sitting on'}] + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) + + This image-text to text pipeline can currently be loaded from pipeline() using the following task identifier: + "image-text-to-text". + + See the list of available models on + [huggingface.co/models](https://huggingface.co/models?pipeline_tag=image-text-to-text). + """ + + _load_processor = True + _load_image_processor = False + _load_feature_extractor = False + _load_tokenizer = False + + _pipeline_calls_generate = True + # Make sure the docstring is updated when the default generation config is changed + _default_generation_config = GenerationConfig( + max_new_tokens=256, + ) + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + requires_backends(self, "vision") + self.check_model_type(MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES) + + def _sanitize_parameters( + self, + max_new_tokens=None, + generate_kwargs=None, + timeout=None, + return_full_text=None, + return_tensors=None, + return_type=None, + clean_up_tokenization_spaces=None, + stop_sequence=None, + continue_final_message=None, + skip_special_tokens=None, + processor_kwargs=None, + **kwargs: Unpack[ProcessingKwargs], + ): + forward_kwargs = {} + preprocess_params = {} + postprocess_params = {} + + # Preprocess params + preprocess_params.update(kwargs) + if timeout is not None: + preprocess_params["timeout"] = timeout + if continue_final_message is not None: + preprocess_params["continue_final_message"] = continue_final_message + if processor_kwargs is not None: + preprocess_params["processor_kwargs"] = processor_kwargs + + # Forward kwargs + if generate_kwargs is not None: + forward_kwargs["generate_kwargs"] = generate_kwargs + if stop_sequence is not None: + stop_sequence_ids = self.processor.tokenizer.encode(stop_sequence, add_special_tokens=False) + if len(stop_sequence_ids) > 1: + logger.warning_once( + "Stopping on a multiple token sequence is not yet supported on transformers. The first token of" + " the stop sequence will be used as the stop sequence string in the interim." + ) + generate_kwargs["eos_token_id"] = stop_sequence_ids[0] + if generate_kwargs is not None: + forward_kwargs["generate_kwargs"] = generate_kwargs + if max_new_tokens is not None: + if "generate_kwargs" not in forward_kwargs: + forward_kwargs["generate_kwargs"] = {} + if "max_new_tokens" in forward_kwargs["generate_kwargs"]: + raise ValueError( + "'max_new_tokens' is defined twice, once in 'generate_kwargs' and once as a direct parameter," + " please use only one" + ) + forward_kwargs["generate_kwargs"]["max_new_tokens"] = max_new_tokens + + # Postprocess params + if return_full_text is not None and return_type is None: + if return_tensors is not None: + raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`") + return_type = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT + if return_tensors is not None and return_type is None: + return_type = ReturnType.TENSORS + if return_type is not None: + postprocess_params["return_type"] = return_type + if continue_final_message is not None: + postprocess_params["continue_final_message"] = continue_final_message + if clean_up_tokenization_spaces is not None: + postprocess_params["clean_up_tokenization_spaces"] = clean_up_tokenization_spaces + if skip_special_tokens is not None: + postprocess_params["skip_special_tokens"] = skip_special_tokens + + return preprocess_params, forward_kwargs, postprocess_params + + @overload + def __call__( + self, + image: Union[str, "Image.Image"] | None = None, + text: str | None = None, + **kwargs: Any, + ) -> list[dict[str, Any]]: ... + + @overload + def __call__( + self, + image: list[str] | list["Image.Image"] | None = None, + text: list[str] | None = None, + **kwargs: Any, + ) -> list[list[dict[str, Any]]]: ... + + def __call__( + self, + images: Union[ + str, list[str], list[list[str]], "Image.Image", list["Image.Image"], list[list["Image.Image"]], list[dict] + ] + | None = None, + text: str | list[str] | list[dict] | None = None, + **kwargs, + ) -> list[dict[str, Any]] | list[list[dict[str, Any]]]: + """ + Generate a text given text and the image(s) passed as inputs. + + Args: + images (`str`, `list[str]`, `PIL.Image, `list[PIL.Image]`, `list[dict[str, Union[str, PIL.Image]]]`): + The pipeline handles three types of images: + + - A string containing a HTTP(s) link pointing to an image + - A string containing a local path to an image + - An image loaded in PIL directly + + The pipeline accepts either a single image or a batch of images. Finally, this pipeline also supports + the chat format (see `text`) containing images and text in this argument. + text (str, list[str], `list[dict[str, Union[str, PIL.Image]]]`): + The text to be used for generation. If a list of strings is passed, the length of the list should be + the same as the number of images. Text can also follow the chat format: a list of dictionaries where + each dictionary represents a message in a conversation. Each dictionary should have two keys: 'role' + and 'content'. 'role' should be one of 'user', 'system' or 'assistant'. 'content' should be a list of + dictionary containing the text of the message and the type of the message. The type of the message + can be either 'text' or 'image'. If the type is 'image', no text is needed. + return_tensors (`bool`, *optional*, defaults to `False`): + Returns the tensors of predictions (as token indices) in the outputs. If set to + `True`, the decoded text is not returned. + return_text (`bool`, *optional*): + Returns the decoded texts in the outputs. + return_full_text (`bool`, *optional*, defaults to `True`): + If set to `False` only added text is returned, otherwise the full text is returned. Cannot be + specified at the same time as `return_text`. + clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`): + Whether or not to clean up the potential extra spaces in the text output. + continue_final_message( `bool`, *optional*): This indicates that you want the model to continue the + last message in the input chat rather than starting a new one, allowing you to "prefill" its response. + By default this is `True` when the final message in the input chat has the `assistant` role and + `False` otherwise, but you can manually override that behaviour by setting this flag. + + Return: + A list or a list of list of `dict`: Each result comes as a dictionary with the following key (cannot + return a combination of both `generated_text` and `generated_token_ids`): + + - **generated_text** (`str`, present when `return_text=True`) -- The generated text. + - **generated_token_ids** (`torch.Tensor`, present when `return_tensors=True`) -- The token + ids of the generated text. + - **input_text** (`str`) -- The input text. + """ + if images is None and text is None: + raise ValueError("You must at least provide either text or images.") + + def _is_chat(arg): + return isinstance(arg, (list, tuple, KeyDataset)) and isinstance(arg[0], (list, tuple, dict)) + + if _is_chat(text): + if images is not None: + raise ValueError( + "Invalid input: you passed `chat` and `images` as separate input arguments. " + "Images must be placed inside the chat message's `content`. For example, " + "'content': [" + " {'type': 'image', 'url': 'image_url'}, {'type': 'text', 'text': 'Describe the image.'}}" + "]" + ) + # We have one or more prompts in list-of-dicts format, so this is chat mode + if isinstance(text[0], dict): + return super().__call__(Chat(text), **kwargs) + else: + chats = [Chat(chat) for chat in text] # 🐈 🐈 🐈 + return super().__call__(chats, **kwargs) + + # Same as above, but the `images` argument contains the chat. This can happen e.g. is the user only passes a + # chat as a positional argument. + elif text is None and _is_chat(images): + # We have one or more prompts in list-of-dicts format, so this is chat mode + if isinstance(images[0], dict): + return super().__call__(Chat(images), **kwargs) + else: + chats = [Chat(image) for image in images] # 🐈 🐈 🐈 + return super().__call__(chats, **kwargs) + + elif images is not None and text is None and not valid_images(images): + """ + Supports the following format + - {"image": image, "text": text} + - [{"image": image, "text": text}] + - Generator and datasets + This is a common pattern in other multimodal pipelines, so we support it here as well. + """ + return super().__call__(images, **kwargs) + + # encourage the user to use the chat format if supported + if getattr(self.processor, "chat_template", None) is not None: + logger.warning_once( + "The input data was not formatted as a chat with dicts containing 'role' and 'content' keys, even " + "though this model supports chat. Consider using the chat format for better results. For more " + "information, see https://huggingface.co/docs/transformers/en/chat_templating" + ) + + # support text only generation + if images is None: + return super().__call__(text, **kwargs) + if text is None: + raise ValueError("You must provide text for this pipeline.") + + return super().__call__({"images": images, "text": text}, **kwargs) + + def preprocess(self, inputs=None, timeout=None, continue_final_message=None, **processing_kwargs): + if isinstance(inputs, Chat): + # If the user passes a chat that ends in an assistant message, we treat it as a prefill by default + # because very few models support multiple separate, consecutive assistant messages + if continue_final_message is None: + continue_final_message = inputs.messages[-1]["role"] == "assistant" + + # Processor kwargs are passed separately from jinja kwargs to chat template + # but it was added only in https://github.com/huggingface/transformers/pull/44881 + processor_kwargs = processing_kwargs.pop("processor_kwargs", None) or {} + + chat_template_kwargs = { + "continue_final_message": continue_final_message, + "return_tensors": "pt", + "tokenize": True, + "return_dict": True, + "add_generation_prompt": not continue_final_message, + "processor_kwargs": processor_kwargs, + **processing_kwargs, + } + + # Handle Mistral tokenizer which does not accept processing kwargs + if self.processor.tokenizer.__class__.__name__ == "MistralCommonBackend": + chat_template_kwargs = { + k: v for k, v in chat_template_kwargs.items() if k in ["padding", "truncation", "max_length"] + } + + model_inputs = self.processor.apply_chat_template( + inputs.messages, + **chat_template_kwargs, + ).to(dtype=self.dtype) + model_inputs["text"] = inputs + return model_inputs + + # In case we only have text inputs + if isinstance(inputs, (list, tuple, str)): + images = None + text = inputs + inputs_text = inputs + else: + images = load_images(inputs["images"], timeout=timeout) + text = inputs["text"] + inputs_text = inputs["text"] + + # if batched text inputs, we set padding to True unless specified otherwise + processor_kwargs = processing_kwargs.pop("processor_kwargs", None) or processing_kwargs + if isinstance(text, (list, tuple)) and len(text) > 1: + processor_kwargs.setdefault("padding", True) + model_inputs = self.processor(images=images, text=text, return_tensors="pt", **processor_kwargs).to( + dtype=self.dtype + ) + + model_inputs["text"] = inputs_text + + return model_inputs + + def _forward(self, model_inputs, generate_kwargs=None): + generate_kwargs = {} if generate_kwargs is None else generate_kwargs + prompt_text = model_inputs.pop("text") + input_ids = ( + model_inputs["input_ids"] if "input_ids" in model_inputs else model_inputs["decoder_input_ids"] + ) # for decoder-only models + + # User-defined `generation_config` passed to the pipeline call take precedence + if "generation_config" not in generate_kwargs: + generate_kwargs["generation_config"] = self.generation_config + + generated_sequence = self.model.generate(**model_inputs, **generate_kwargs) + + return {"generated_sequence": generated_sequence, "prompt_text": prompt_text, "input_ids": input_ids} + + def postprocess( + self, + model_outputs, + return_type=ReturnType.FULL_TEXT, + continue_final_message=None, + skip_special_tokens=None, + **postprocess_kwargs, + ): + input_texts = model_outputs["prompt_text"] + input_texts = [input_texts] if isinstance(input_texts, (str, Chat)) else input_texts + generated_sequence = model_outputs["generated_sequence"] + input_ids = model_outputs["input_ids"] + if return_type == ReturnType.TENSORS: + return [ + {"input_text": input_texts[i], "generated_token_ids": generated_sequence[i]} + for i in range(len(input_texts)) + ] + + # Decode inputs and outputs the same way to remove input text from generated text if present + skip_special_tokens = skip_special_tokens if skip_special_tokens is not None else True + if getattr(self.tokenizer, "response_schema", False): + skip_special_tokens = False + generated_texts = self.processor.post_process_image_text_to_text( + generated_sequence, skip_special_tokens=skip_special_tokens, **postprocess_kwargs + ) + decoded_inputs = self.processor.post_process_image_text_to_text( + input_ids, skip_special_tokens=skip_special_tokens, **postprocess_kwargs + ) + + # Force consistent behavior for including the input text in the output + if return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: + # Remove the input text from the generated text if the generated text starts with the input text + # (accounting for the possibility of a space between the input and generated text) + new_generated_texts = [] + for text_generated, decoded_input in zip(generated_texts, decoded_inputs): + # There can be added characters before the input text, so we need to find the beginning of the input text in the generated text + index_input_text = text_generated.find(decoded_input) + # Limit the search to 2 residual characters, like spaces or new lines, to avoid removing a large part of the answer + if 0 <= index_input_text <= 2: + # If the input text is found, we remove it + new_generated_texts.append(text_generated[index_input_text + len(decoded_input) :]) + else: + new_generated_texts.append(text_generated) + generated_texts = new_generated_texts + if return_type == ReturnType.FULL_TEXT: + full_texts = [] + for prompt_text, generated_text in zip(input_texts, generated_texts): + if isinstance(prompt_text, str): + generated_text = prompt_text + generated_text + elif isinstance(prompt_text, Chat): + if continue_final_message is None: + # If the user passes a chat ending in an assistant message, we treat it as a prefill by + # default because very few models support multiple separate, consecutive assistant messages + continue_final_message = prompt_text.messages[-1]["role"] == "assistant" + if continue_final_message: + # With assistant prefill, concat onto the end of the last message + new_text = dict(prompt_text.messages[-1]["content"][-1].items()) + new_text["text"] += generated_text + generated_text = list(prompt_text.messages)[:-1] + [ + { + "role": prompt_text.messages[-1]["role"], + "content": prompt_text.messages[-1]["content"][:-1] + [new_text], + } + ] + else: + # When we're not starting from a prefill, the output is a new assistant message + if getattr(self.tokenizer, "response_schema", False): + assistant_message = self.tokenizer.parse_response(generated_text) + else: + assistant_message = {"role": "assistant", "content": generated_text} + generated_text = list(prompt_text.messages) + [assistant_message] + full_texts.append(generated_text) + generated_texts = full_texts + + records = [ + { + "input_text": input_text.messages if isinstance(input_text, Chat) else input_text, + "generated_text": generated_text, + } + for input_text, generated_text in zip(input_texts, generated_texts) + ] + + return records diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/keypoint_matching.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/keypoint_matching.py new file mode 100644 index 0000000000000000000000000000000000000000..d75656a7db3b301476faf02401c0a5df5d2c5691 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/keypoint_matching.py @@ -0,0 +1,176 @@ +# Copyright 2025 The HuggingFace Team. All rights reserved. +# +# 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. + +from collections.abc import Sequence +from typing import Any, TypeAlias, TypedDict, Union + +from typing_extensions import overload + +from ..image_utils import is_pil_image +from ..utils import is_vision_available, requires_backends +from .base import Pipeline + + +if is_vision_available(): + from PIL import Image + + from ..image_utils import load_image + + +ImagePair: TypeAlias = Sequence[Union["Image.Image", str]] + + +class Keypoint(TypedDict): + x: float + y: float + + +class Match(TypedDict): + keypoint_image_0: Keypoint + keypoint_image_1: Keypoint + score: float + + +def validate_image_pairs(images: Any) -> Sequence[Sequence[ImagePair]]: + error_message = ( + "Input images must be a one of the following :", + " - A pair of images.", + " - A list of pairs of images.", + ) + + def _is_valid_image(image): + """images is a PIL Image or a string.""" + return is_pil_image(image) or isinstance(image, str) + + if isinstance(images, Sequence): + if len(images) == 2 and all((_is_valid_image(image)) for image in images): + return [images] + if all( + isinstance(image_pair, Sequence) + and len(image_pair) == 2 + and all(_is_valid_image(image) for image in image_pair) + for image_pair in images + ): + return images + raise ValueError(error_message) + + +class KeypointMatchingPipeline(Pipeline): + """ + Keypoint matching pipeline using any `AutoModelForKeypointMatching`. This pipeline matches keypoints between two images. + """ + + _load_processor = False + _load_image_processor = True + _load_feature_extractor = False + _load_tokenizer = False + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + requires_backends(self, "vision") + + def _sanitize_parameters(self, threshold=None, timeout=None): + preprocess_params = {} + if timeout is not None: + preprocess_params["timeout"] = timeout + postprocess_params = {} + if threshold is not None: + postprocess_params["threshold"] = threshold + return preprocess_params, {}, postprocess_params + + @overload + def __call__(self, inputs: ImagePair, threshold: float = 0.0, **kwargs: Any) -> list[Match]: ... + + @overload + def __call__(self, inputs: list[ImagePair], threshold: float = 0.0, **kwargs: Any) -> list[list[Match]]: ... + + def __call__( + self, + inputs: list[ImagePair] | ImagePair, + threshold: float = 0.0, + **kwargs: Any, + ) -> list[Match] | list[list[Match]]: + """ + Find matches between keypoints in two images. + + Args: + inputs (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`): + The pipeline handles three types of images: + + - A string containing a http link pointing to an image + - A string containing a local path to an image + - An image loaded in PIL directly + + The pipeline accepts either a single pair of images or a batch of image pairs, which must then be passed as a string. + Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL + images. + + threshold (`float`, *optional*, defaults to 0.0): + The threshold to use for keypoint matching. Keypoints matched with a lower matching score will be filtered out. + A value of 0 means that all matched keypoints will be returned. + + kwargs: + `timeout (`float`, *optional*, defaults to None)` + The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and + the call may block forever. + + Return: + Union[list[Match], list[list[Match]]]: + A list of matches or a list if a single image pair is provided, or of lists of matches if a batch + of image pairs is provided. Each match is a dictionary containing the following keys: + + - **keypoint_image_0** (`Keypoint`): The keypoint in the first image (x, y coordinates). + - **keypoint_image_1** (`Keypoint`): The keypoint in the second image (x, y coordinates). + - **score** (`float`): The matching score between the two keypoints. + """ + if inputs is None: + raise ValueError("Cannot call the keypoint-matching pipeline without an inputs argument!") + formatted_inputs = validate_image_pairs(inputs) + outputs = super().__call__(formatted_inputs, threshold=threshold, **kwargs) + if len(formatted_inputs) == 1: + return outputs[0] + return outputs + + def preprocess(self, images, timeout=None): + images = [load_image(image, timeout=timeout) for image in images] + model_inputs = self.image_processor(images=images, return_tensors="pt") + model_inputs = model_inputs.to(self.dtype) + target_sizes = [image.size for image in images] + preprocess_outputs = {"model_inputs": model_inputs, "target_sizes": target_sizes} + return preprocess_outputs + + def _forward(self, preprocess_outputs): + model_inputs = preprocess_outputs["model_inputs"] + model_outputs = self.model(**model_inputs) + forward_outputs = {"model_outputs": model_outputs, "target_sizes": [preprocess_outputs["target_sizes"]]} + return forward_outputs + + def postprocess(self, forward_outputs, threshold=0.0) -> list[Match]: + model_outputs = forward_outputs["model_outputs"] + target_sizes = forward_outputs["target_sizes"] + postprocess_outputs = self.image_processor.post_process_keypoint_matching( + model_outputs, target_sizes=target_sizes, threshold=threshold + ) + postprocess_outputs = postprocess_outputs[0] + pair_result = [] + for kp_0, kp_1, score in zip( + postprocess_outputs["keypoints0"], + postprocess_outputs["keypoints1"], + postprocess_outputs["matching_scores"], + ): + kp_0 = Keypoint(x=kp_0[0].item(), y=kp_0[1].item()) + kp_1 = Keypoint(x=kp_1[0].item(), y=kp_1[1].item()) + pair_result.append(Match(keypoint_image_0=kp_0, keypoint_image_1=kp_1, score=score.item())) + pair_result = sorted(pair_result, key=lambda x: x["score"], reverse=True) + return pair_result diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/mask_generation.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/mask_generation.py new file mode 100644 index 0000000000000000000000000000000000000000..920ce9d0a39cecc451b329c5a241cccaa4f5b5e7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/mask_generation.py @@ -0,0 +1,335 @@ +from collections import defaultdict +from typing import TYPE_CHECKING, Any, Union, overload + +from ..image_utils import load_image +from ..utils import ( + add_end_docstrings, + is_torch_available, + logging, + requires_backends, +) +from .base import ChunkPipeline, build_pipeline_init_args + + +if is_torch_available(): + import torch + + from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING_NAMES + +if TYPE_CHECKING: + from PIL import Image + +logger = logging.get_logger(__name__) + + +@add_end_docstrings( + build_pipeline_init_args(has_image_processor=True), + r""" + points_per_batch (*optional*, int, default to 64): + Sets the number of points run simultaneously by the model. Higher numbers may be faster but use more GPU + memory. + output_bboxes_mask (`bool`, *optional*, default to `False`): + Whether or not to output the bounding box predictions. + output_rle_masks (`bool`, *optional*, default to `False`): + Whether or not to output the masks in `RLE` format""", +) +class MaskGenerationPipeline(ChunkPipeline): + """ + Automatic mask generation for images using `SamForMaskGeneration`. This pipeline predicts binary masks for an + image, given an image. It is a `ChunkPipeline` because you can separate the points in a mini-batch in order to + avoid OOM issues. Use the `points_per_batch` argument to control the number of points that will be processed at the + same time. Default is `64`. + + The pipeline works in 3 steps: + 1. `preprocess`: A grid of 1024 points evenly separated is generated along with bounding boxes and point + labels. + For more details on how the points and bounding boxes are created, check the `_generate_crop_boxes` + function. The image is also preprocessed using the `image_processor`. This function `yields` a minibatch of + `points_per_batch`. + + 2. `forward`: feeds the outputs of `preprocess` to the model. The image embedding is computed only once. + Calls both `self.model.get_image_embeddings` and makes sure that the gradients are not computed, and the + tensors and models are on the same device. + + 3. `postprocess`: The most important part of the automatic mask generation happens here. Three steps + are induced: + - image_processor.postprocess_masks (run on each minibatch loop): takes in the raw output masks, + resizes them according + to the image size, and transforms there to binary masks. + - image_processor.filter_masks (on each minibatch loop): uses both `pred_iou_thresh` and + `stability_scores`. Also + applies a variety of filters based on non maximum suppression to remove bad masks. + - image_processor.postprocess_masks_for_amg applies the NSM on the mask to only keep relevant ones. + + Example: + + ```python + >>> from transformers import pipeline + + >>> generator = pipeline(model="facebook/sam-vit-base", task="mask-generation") + >>> outputs = generator( + ... "http://images.cocodataset.org/val2017/000000039769.jpg", + ... ) + + >>> outputs = generator( + ... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", points_per_batch=128 + ... ) + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) + + This segmentation pipeline can currently be loaded from [`pipeline`] using the following task identifier: + `"mask-generation"`. + + See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=mask-generation). + """ + + _load_processor = False + _load_image_processor = True + _load_feature_extractor = False + _load_tokenizer = False + + def __init__(self, **kwargs): + super().__init__(**kwargs) + requires_backends(self, "vision") + requires_backends(self, "torch") + + self.check_model_type(MODEL_FOR_MASK_GENERATION_MAPPING_NAMES) + + def _sanitize_parameters(self, **kwargs): + preprocess_kwargs = {} + postprocess_kwargs = {} + forward_params = {} + # preprocess args + if "points_per_batch" in kwargs: + preprocess_kwargs["points_per_batch"] = kwargs["points_per_batch"] + if "points_per_crop" in kwargs: + preprocess_kwargs["points_per_crop"] = kwargs["points_per_crop"] + if "crops_n_layers" in kwargs: + preprocess_kwargs["crops_n_layers"] = kwargs["crops_n_layers"] + if "crop_overlap_ratio" in kwargs: + preprocess_kwargs["crop_overlap_ratio"] = kwargs["crop_overlap_ratio"] + if "crop_n_points_downscale_factor" in kwargs: + preprocess_kwargs["crop_n_points_downscale_factor"] = kwargs["crop_n_points_downscale_factor"] + if "timeout" in kwargs: + preprocess_kwargs["timeout"] = kwargs["timeout"] + # postprocess args + if "pred_iou_thresh" in kwargs: + forward_params["pred_iou_thresh"] = kwargs["pred_iou_thresh"] + if "stability_score_offset" in kwargs: + forward_params["stability_score_offset"] = kwargs["stability_score_offset"] + if "mask_threshold" in kwargs: + forward_params["mask_threshold"] = kwargs["mask_threshold"] + if "stability_score_thresh" in kwargs: + forward_params["stability_score_thresh"] = kwargs["stability_score_thresh"] + if "max_hole_area" in kwargs: + forward_params["max_hole_area"] = kwargs["max_hole_area"] + if "max_sprinkle_area" in kwargs: + forward_params["max_sprinkle_area"] = kwargs["max_sprinkle_area"] + if "crops_nms_thresh" in kwargs: + postprocess_kwargs["crops_nms_thresh"] = kwargs["crops_nms_thresh"] + if "output_rle_mask" in kwargs: + postprocess_kwargs["output_rle_mask"] = kwargs["output_rle_mask"] + if "output_bboxes_mask" in kwargs: + postprocess_kwargs["output_bboxes_mask"] = kwargs["output_bboxes_mask"] + return preprocess_kwargs, forward_params, postprocess_kwargs + + @overload + def __call__(self, image: Union[str, "Image.Image"], *args: Any, **kwargs: Any) -> dict[str, Any]: ... + + @overload + def __call__(self, image: list[str] | list["Image.Image"], *args: Any, **kwargs: Any) -> list[dict[str, Any]]: ... + + def __call__( + self, image: Union[str, "Image.Image", list[str], list["Image.Image"]], *args: Any, **kwargs: Any + ) -> dict[str, Any] | list[dict[str, Any]]: + """ + Generates binary segmentation masks + + Args: + image (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`): + Image or list of images. + mask_threshold (`float`, *optional*, defaults to 0.0): + Threshold to use when turning the predicted masks into binary values. + pred_iou_thresh (`float`, *optional*, defaults to 0.88): + A filtering threshold in `[0,1]` applied on the model's predicted mask quality. + stability_score_thresh (`float`, *optional*, defaults to 0.95): + A filtering threshold in `[0,1]`, using the stability of the mask under changes to the cutoff used to + binarize the model's mask predictions. + stability_score_offset (`int`, *optional*, defaults to 1): + The amount to shift the cutoff when calculated the stability score. + crops_nms_thresh (`float`, *optional*, defaults to 0.7): + The box IoU cutoff used by non-maximal suppression to filter duplicate masks. + crops_n_layers (`int`, *optional*, defaults to 0): + If `crops_n_layers>0`, mask prediction will be run again on crops of the image. Sets the number of + layers to run, where each layer has 2**i_layer number of image crops. + crop_overlap_ratio (`float`, *optional*, defaults to `512 / 1500`): + Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of + the image length. Later layers with more crops scale down this overlap. + crop_n_points_downscale_factor (`int`, *optional*, defaults to `1`): + The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n. + timeout (`float`, *optional*, defaults to None): + The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and + the call may block forever. + + Return: + `Dict`: A dictionary with the following keys: + - **mask** (`PIL.Image`) -- A binary mask of the detected object as a PIL Image of shape `(width, + height)` of the original image. Returns a mask filled with zeros if no object is found. + - **score** (*optional* `float`) -- Optionally, when the model is capable of estimating a confidence of + the "object" described by the label and the mask. + + """ + num_workers = kwargs.pop("num_workers", None) + batch_size = kwargs.pop("batch_size", None) + return super().__call__(image, *args, num_workers=num_workers, batch_size=batch_size, **kwargs) + + def preprocess( + self, + image, + points_per_batch=64, + crops_n_layers: int = 0, + crop_overlap_ratio: float = 512 / 1500, + points_per_crop: int = 32, + crop_n_points_downscale_factor: int = 1, + timeout: float | None = None, + ): + image = load_image(image, timeout=timeout) + target_size = self.image_processor.size.get("longest_edge", self.image_processor.size.get("height")) + crop_boxes, grid_points, cropped_images, input_labels = self.image_processor.generate_crop_boxes( + image, target_size, crops_n_layers, crop_overlap_ratio, points_per_crop, crop_n_points_downscale_factor + ) + model_inputs = self.image_processor(images=cropped_images, return_tensors="pt") + model_inputs = model_inputs.to(self.dtype) + + with self.device_placement(): + inference_context = self.get_inference_context() + with inference_context(): + model_inputs = self._ensure_tensor_on_device(model_inputs, device=self.device) + embeddings = self.model.get_image_embeddings(model_inputs.pop("pixel_values")) + + # Handle both SAM (single tensor) and SAM-HQ (tuple) outputs + if isinstance(embeddings, tuple): + image_embeddings, intermediate_embeddings = embeddings + model_inputs["intermediate_embeddings"] = intermediate_embeddings + else: + image_embeddings = embeddings + # TODO: Identifying the model by the type of its returned embeddings is brittle. + # Consider using a more robust method for distinguishing model types here. + + model_inputs["image_embeddings"] = image_embeddings + + n_points = grid_points.shape[1] + points_per_batch = points_per_batch if points_per_batch is not None else n_points + + if points_per_batch <= 0: + raise ValueError( + "Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. " + "To return all points at once, set points_per_batch to None" + ) + + for i in range(0, n_points, points_per_batch): + batched_points = grid_points[:, i : i + points_per_batch, :, :] + labels = input_labels[:, i : i + points_per_batch] + is_last = i == n_points - points_per_batch + yield { + "input_points": batched_points, + "input_labels": labels, + "input_boxes": crop_boxes, + "is_last": is_last, + **model_inputs, + } + + def _forward( + self, + model_inputs, + pred_iou_thresh=0.88, + stability_score_thresh=0.95, + mask_threshold=0, + stability_score_offset=1, + max_hole_area=None, + max_sprinkle_area=None, + ): + input_boxes = model_inputs.pop("input_boxes") + is_last = model_inputs.pop("is_last") + original_sizes = model_inputs.pop("original_sizes").tolist() + reshaped_input_sizes = model_inputs.pop("reshaped_input_sizes", None) + reshaped_input_sizes = reshaped_input_sizes.tolist() if reshaped_input_sizes is not None else None + + model_outputs = self.model(**model_inputs) + + # post processing happens here in order to avoid CPU GPU copies of ALL the masks + low_resolution_masks = model_outputs["pred_masks"] + postprocess_kwargs = {} + if max_hole_area is not None: + postprocess_kwargs["max_hole_area"] = max_hole_area + if max_sprinkle_area is not None and max_sprinkle_area > 0: + postprocess_kwargs["max_sprinkle_area"] = max_sprinkle_area + if postprocess_kwargs: + low_resolution_masks = self.image_processor.post_process_masks( + low_resolution_masks, + original_sizes, + mask_threshold=mask_threshold, + reshaped_input_sizes=reshaped_input_sizes, + binarize=False, + **postprocess_kwargs, + ) + masks = self.image_processor.post_process_masks( + low_resolution_masks, + original_sizes, + mask_threshold=mask_threshold, + reshaped_input_sizes=reshaped_input_sizes, + binarize=False, + ) + iou_scores = model_outputs["iou_scores"] + masks, iou_scores, boxes = self.image_processor.filter_masks( + masks[0], + iou_scores[0], + original_sizes[0], + input_boxes[0], + pred_iou_thresh, + stability_score_thresh, + mask_threshold, + stability_score_offset, + ) + return { + "masks": masks, + "is_last": is_last, + "boxes": boxes, + "iou_scores": iou_scores, + } + + def postprocess( + self, + model_outputs, + output_rle_mask=False, + output_bboxes_mask=False, + crops_nms_thresh=0.7, + ): + all_scores = [] + all_masks = [] + all_boxes = [] + for model_output in model_outputs: + all_scores.append(model_output.pop("iou_scores")) + all_masks.extend(model_output.pop("masks")) + all_boxes.append(model_output.pop("boxes")) + + all_scores = torch.cat(all_scores) + all_boxes = torch.cat(all_boxes) + output_masks, iou_scores, rle_mask, bounding_boxes = self.image_processor.post_process_for_mask_generation( + all_masks, all_scores, all_boxes, crops_nms_thresh + ) + + extra = defaultdict(list) + for output in model_outputs: + for k, v in output.items(): + extra[k].append(v) + + optional = {} + if output_rle_mask: + optional["rle_mask"] = rle_mask + + if output_bboxes_mask: + optional["bounding_boxes"] = bounding_boxes + + return {"masks": output_masks, "scores": iou_scores, **optional, **extra} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/object_detection.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/object_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..0a4fba996d7d364283371c17e9cf6adbc43d0c23 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/object_detection.py @@ -0,0 +1,197 @@ +from typing import TYPE_CHECKING, Any, Union, overload + +from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends +from .base import Pipeline, build_pipeline_init_args + + +if is_vision_available(): + from ..image_utils import load_image + + +if is_torch_available(): + import torch + + from ..models.auto.modeling_auto import ( + MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, + ) + +if TYPE_CHECKING: + from PIL import Image + +logger = logging.get_logger(__name__) + + +@add_end_docstrings(build_pipeline_init_args(has_image_processor=True)) +class ObjectDetectionPipeline(Pipeline): + """ + Object detection pipeline using any `AutoModelForObjectDetection`. This pipeline predicts bounding boxes of objects + and their classes. + + Example: + + ```python + >>> from transformers import pipeline + + >>> detector = pipeline(model="facebook/detr-resnet-50") + >>> detector("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png") + [{'score': 0.997, 'label': 'bird', 'box': {'xmin': 69, 'ymin': 171, 'xmax': 396, 'ymax': 507}}, {'score': 0.999, 'label': 'bird', 'box': {'xmin': 398, 'ymin': 105, 'xmax': 767, 'ymax': 507}}] + + >>> # x, y are expressed relative to the top left hand corner. + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) + + This object detection pipeline can currently be loaded from [`pipeline`] using the following task identifier: + `"object-detection"`. + + See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=object-detection). + """ + + _load_processor = False + _load_image_processor = True + _load_feature_extractor = False + _load_tokenizer = None + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + requires_backends(self, "vision") + mapping = MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES.copy() + mapping.update(MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES) + self.check_model_type(mapping) + + def _sanitize_parameters(self, **kwargs): + preprocess_params = {} + if "timeout" in kwargs: + preprocess_params["timeout"] = kwargs["timeout"] + postprocess_kwargs = {} + if "threshold" in kwargs: + postprocess_kwargs["threshold"] = kwargs["threshold"] + return preprocess_params, {}, postprocess_kwargs + + @overload + def __call__(self, image: Union[str, "Image.Image"], *args: Any, **kwargs: Any) -> list[dict[str, Any]]: ... + + @overload + def __call__( + self, image: list[str] | list["Image.Image"], *args: Any, **kwargs: Any + ) -> list[list[dict[str, Any]]]: ... + + def __call__(self, *args, **kwargs) -> list[dict[str, Any]] | list[list[dict[str, Any]]]: + """ + Detect objects (bounding boxes & classes) in the image(s) passed as inputs. + + Args: + inputs (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`): + The pipeline handles three types of images: + + - A string containing an HTTP(S) link pointing to an image + - A string containing a local path to an image + - An image loaded in PIL directly + + The pipeline accepts either a single image or a batch of images. Images in a batch must all be in the + same format: all as HTTP(S) links, all as local paths, or all as PIL images. + threshold (`float`, *optional*, defaults to 0.5): + The probability necessary to make a prediction. + timeout (`float`, *optional*, defaults to None): + The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and + the call may block forever. + + Return: + A list of dictionaries or a list of list of dictionaries containing the result. If the input is a single + image, will return a list of dictionaries, if the input is a list of several images, will return a list of + list of dictionaries corresponding to each image. + + The dictionaries contain the following keys: + + - **label** (`str`) -- The class label identified by the model. + - **score** (`float`) -- The score attributed by the model for that label. + - **box** (`list[dict[str, int]]`) -- The bounding box of detected object in image's original size. + """ + # After deprecation of this is completed, remove the default `None` value for `images` + if "images" in kwargs and "inputs" not in kwargs: + kwargs["inputs"] = kwargs.pop("images") + return super().__call__(*args, **kwargs) + + def preprocess(self, image, timeout=None): + image = load_image(image, timeout=timeout) + target_size = torch.IntTensor([[image.height, image.width]]) + inputs = self.image_processor(images=[image], return_tensors="pt") + inputs = inputs.to(self.dtype) + if self.tokenizer is not None: + inputs = self.tokenizer(text=inputs["words"], boxes=inputs["boxes"], return_tensors="pt") + inputs["target_size"] = target_size + return inputs + + def _forward(self, model_inputs): + target_size = model_inputs.pop("target_size") + outputs = self.model(**model_inputs) + model_outputs = outputs.__class__({"target_size": target_size, **outputs}) + if self.tokenizer is not None: + model_outputs["bbox"] = model_inputs["bbox"] + return model_outputs + + def postprocess(self, model_outputs, threshold=0.5): + target_size = model_outputs["target_size"] + if self.tokenizer is not None: + # This is a LayoutLMForTokenClassification variant. + # The OCR got the boxes and the model classified the words. + height, width = target_size[0].tolist() + + def unnormalize(bbox): + return self._get_bounding_box( + torch.Tensor( + [ + (width * bbox[0] / 1000), + (height * bbox[1] / 1000), + (width * bbox[2] / 1000), + (height * bbox[3] / 1000), + ] + ) + ) + + scores, classes = model_outputs["logits"].squeeze(0).softmax(dim=-1).max(dim=-1) + labels = [self.model.config.id2label[prediction] for prediction in classes.tolist()] + boxes = [unnormalize(bbox) for bbox in model_outputs["bbox"].squeeze(0)] + keys = ["score", "label", "box"] + annotation = [dict(zip(keys, vals)) for vals in zip(scores.tolist(), labels, boxes) if vals[0] > threshold] + else: + # This is a regular ForObjectDetectionModel + raw_annotations = self.image_processor.post_process_object_detection(model_outputs, threshold, target_size) + raw_annotation = raw_annotations[0] + scores = raw_annotation["scores"] + labels = raw_annotation["labels"] + boxes = raw_annotation["boxes"] + + raw_annotation["scores"] = scores.tolist() + raw_annotation["labels"] = [self.model.config.id2label[label.item()] for label in labels] + raw_annotation["boxes"] = [self._get_bounding_box(box) for box in boxes] + + # {"scores": [...], ...} --> [{"score":x, ...}, ...] + keys = ["score", "label", "box"] + annotation = [ + dict(zip(keys, vals)) + for vals in zip(raw_annotation["scores"], raw_annotation["labels"], raw_annotation["boxes"]) + ] + + return annotation + + def _get_bounding_box(self, box: "torch.Tensor") -> dict[str, int]: + """ + Turns list [xmin, xmax, ymin, ymax] into dict { "xmin": xmin, ... } + + Args: + box (`torch.Tensor`): Tensor containing the coordinates in corners format. + + Returns: + bbox (`dict[str, int]`): Dict containing the coordinates in corners format. + """ + xmin, ymin, xmax, ymax = box.int().tolist() + bbox = { + "xmin": xmin, + "ymin": ymin, + "xmax": xmax, + "ymax": ymax, + } + return bbox diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/pt_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/pt_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3857805962a93f796e407ed88c89495b46fd0bd0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/pt_utils.py @@ -0,0 +1,323 @@ +import numpy as np +import torch +from torch.utils.data import Dataset, IterableDataset + +from ..utils.generic import ModelOutput + + +class PipelineDataset(Dataset): + def __init__(self, dataset, process, params): + self.dataset = dataset + self.process = process + self.params = params + + def __len__(self): + return len(self.dataset) + + def __getitem__(self, i): + item = self.dataset[i] + processed = self.process(item, **self.params) + return processed + + +class PipelineIterator(IterableDataset): + def __init__(self, loader, infer, params, loader_batch_size=None): + """ + Roughly equivalent to + + ``` + for item in loader: + yield infer(item, **params) + ``` + + Arguments: + loader (`torch.utils.data.DataLoader` or `Iterable`): + The iterator that will be used to apply `infer` on. + infer (any function): + The function to apply of each element of `loader`. + params (`dict`): + The parameters passed to `infer` along with every item + loader_batch_size (`int`, *optional*): + If specified, the items of `loader` are supposed to come as batch, and are loader_batched here + making it roughly behave as + + + ``` + for items in loader: + for i in loader_batch_size: + item = items[i] + yield infer(item, **params) + ```""" + self.loader = loader + self.infer = infer + self.params = params + if loader_batch_size == 1: + # Let's spare some time by deactivating altogether + loader_batch_size = None + self.loader_batch_size = loader_batch_size + + # Internal bookkeeping + self._loader_batch_index = None + self._loader_batch_data = None + + def __len__(self): + return len(self.loader) + + def __iter__(self): + self.iterator = iter(self.loader) + return self + + def loader_batch_item(self): + """ + Return item located at `loader_batch_index` within the current `loader_batch_data`. + """ + if isinstance(self._loader_batch_data, torch.Tensor): + # Batch data is simple tensor, just fetch the slice + result = self._loader_batch_data[self._loader_batch_index].unsqueeze(0) + else: + # Batch data is assumed to be BaseModelOutput (or dict) + loader_batched = {} + for k, element in self._loader_batch_data.items(): + if isinstance(element, ModelOutput): + # Convert ModelOutput to tuple first + element = element.to_tuple() + if isinstance(element[0], torch.Tensor): + loader_batched[k] = tuple(el[self._loader_batch_index].unsqueeze(0) for el in element) + elif isinstance(element[0], np.ndarray): + loader_batched[k] = tuple(np.expand_dims(el[self._loader_batch_index], 0) for el in element) + continue + if k in {"hidden_states", "attentions"} and isinstance(element, tuple): + # Those are stored as lists of tensors so need specific unbatching. + if isinstance(element[0], torch.Tensor): + loader_batched[k] = tuple(el[self._loader_batch_index].unsqueeze(0) for el in element) + elif isinstance(element[0], np.ndarray): + loader_batched[k] = tuple(np.expand_dims(el[self._loader_batch_index], 0) for el in element) + continue + if k == "past_key_values": + continue + if element is None: + # This can happen for optional data that get passed around + loader_batched[k] = None + elif isinstance(element[self._loader_batch_index], torch.Tensor): + # Take correct batch data, but make it looked like batch_size=1 + # For compatibility with other methods within transformers + + loader_batched[k] = element[self._loader_batch_index].unsqueeze(0) + elif isinstance(element[self._loader_batch_index], np.ndarray): + # Take correct batch data, but make it looked like batch_size=1 + # For compatibility with other methods within transformers + loader_batched[k] = np.expand_dims(element[self._loader_batch_index], 0) + else: + # This is typically a list, so no need to `unsqueeze`. + loader_batched[k] = element[self._loader_batch_index] + # Recreate the element by reusing the original class to make it look + # batch_size=1 + result = self._loader_batch_data.__class__(loader_batched) + self._loader_batch_index += 1 + return result + + def __next__(self): + if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: + # We are currently unrolling a batch so we just need to return + # the current item within a batch + return self.loader_batch_item() + + # We're out of items within a batch + item = next(self.iterator) + processed = self.infer(item, **self.params) + # We now have a batch of "inferred things". + if self.loader_batch_size is not None: + # Try to infer the size of the batch + if isinstance(processed, torch.Tensor): + first_tensor = processed + elif isinstance(processed, tuple): + first_tensor = processed[0] + else: + key = list(processed.keys())[0] + first_tensor = processed[key] + + if isinstance(first_tensor, list): + observed_batch_size = len(first_tensor) + else: + observed_batch_size = first_tensor.shape[0] + if 0 < observed_batch_size < self.loader_batch_size: + # could be last batch so we can't unroll as many + # elements. + self.loader_batch_size = observed_batch_size + # Setting internal index to unwrap the batch + self._loader_batch_data = processed[0] if isinstance(processed, tuple) else processed + self._loader_batch_index = 0 + return self.loader_batch_item() + else: + # We're not unrolling batches + return processed + + +class PipelineChunkIterator(PipelineIterator): + def __init__(self, loader, infer, params, loader_batch_size=None): + """ + Roughly equivalent to + + ``` + for iterator in loader: + for item in iterator: + yield infer(item, **params) + ``` + + Arguments: + loader (`torch.utils.data.DataLoader` or `Iterable`): + The iterator that will be used to apply `infer` on. + infer (any function): + The function to apply of each element of `loader`. + params (`dict`): + The parameters passed to `infer` along with every item + """ + super().__init__(loader, infer, params) + + def __iter__(self): + self.iterator = iter(self.loader) + self.subiterator = None + return self + + def __next__(self): + if self.subiterator is None: + "Subiterator None means we haven't started a `preprocess` iterator. so start it" + self.subiterator = self.infer(next(self.iterator), **self.params) + try: + # Try to return next item + processed = next(self.subiterator) + except StopIteration: + # When a preprocess iterator ends, we can start looking at the next item + # ChunkIterator will keep feeding until ALL elements of iterator + # all have created their subiterator and have been iterating against. + # + # Another way to look at it, is we're basically flattening lists of lists + # into a single list, but with generators + self.subiterator = self.infer(next(self.iterator), **self.params) + processed = next(self.subiterator) + return processed + + +class PipelinePackIterator(PipelineIterator): + """ + Roughly equivalent to + + ``` + packed = [] + for item in loader: + packed.append(item) + if item["is_last"]: + yield packed + packed = [] + ``` + + but it also handles cases where `item` are batched (meaning it's a dict of Tensor with first dimension > 1. In + that case it does + + ``` + packed = [] + for batch in loader: + # item is batched + for item in batch: + packed.append(item) + if item["is_last"]: + yield packed + packed = [] + ``` + + Arguments: + loader (`torch.utils.data.DataLoader` or `Iterable`): + The iterator that will be used to apply `infer` on. + infer (any function): + The function to apply of each element of `loader`. + params (`dict`): + The parameters passed to `infer` along with every item + loader_batch_size (`int`, *optional*): + If specified, the items of `loader` are supposed to come as batch, and are loader_batched here making + it roughly behave as + + + ``` + for items in loader: + for i in loader_batch_size: + item = items[i] + yield infer(item, **params) + ```""" + + def __iter__(self): + self.iterator = iter(self.loader) + return self + + def __next__(self): + # Extremely similar to PipelineIterator in its unpacking mechanism + # BUT, we have an extra required item which is the presence of `is_last` + # That is because everything is flattened by `PipelineChunkIterator` we + # need to keep track of how to regroup here in the original `process` + # boundaries so that `process` and `postprocess` see the same data. + + # This iterator accumulates items (possibly while unbatching) until it + # its a `is_last` and then just passes it on to the caller. + is_last = False + accumulator = [] + if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: + while self._loader_batch_index < self.loader_batch_size: + item = self.loader_batch_item() + is_last = item.pop("is_last") + accumulator.append(item) + if is_last: + return accumulator + + while not is_last: + processed = self.infer(next(self.iterator), **self.params) + if self.loader_batch_size is not None: + if isinstance(processed, torch.Tensor): + first_tensor = processed + else: + key = list(processed.keys())[0] + first_tensor = processed[key] + if isinstance(first_tensor, list): + observed_batch_size = len(first_tensor) + else: + observed_batch_size = first_tensor.shape[0] + if 0 < observed_batch_size < self.loader_batch_size: + # could be last batch so we can't unroll as many + # elements. + self.loader_batch_size = observed_batch_size + self._loader_batch_data = processed + self._loader_batch_index = 0 + while self._loader_batch_index < self.loader_batch_size: + item = self.loader_batch_item() + is_last = item.pop("is_last") + accumulator.append(item) + if is_last: + return accumulator + else: + item = processed + is_last = item.pop("is_last") + accumulator.append(item) + return accumulator + + +class KeyDataset(Dataset): + def __init__(self, dataset: Dataset, key: str): + self.dataset = dataset + self.key = key + + def __len__(self): + return len(self.dataset) + + def __getitem__(self, i): + return self.dataset[i][self.key] + + +class KeyPairDataset(Dataset): + def __init__(self, dataset: Dataset, key1: str, key2: str): + self.dataset = dataset + self.key1 = key1 + self.key2 = key2 + + def __len__(self): + return len(self.dataset) + + def __getitem__(self, i): + return {"text": self.dataset[i][self.key1], "text_pair": self.dataset[i][self.key2]} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/table_question_answering.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/table_question_answering.py new file mode 100644 index 0000000000000000000000000000000000000000..96bcc863cbe791dde19497d876df754d4fdaf683 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/table_question_answering.py @@ -0,0 +1,382 @@ +import collections +import types + +import numpy as np + +from ..generation import GenerationConfig +from ..utils import ( + add_end_docstrings, + is_torch_available, + requires_backends, +) +from .base import ArgumentHandler, Dataset, Pipeline, PipelineException, build_pipeline_init_args + + +if is_torch_available(): + import torch + + from ..models.auto.modeling_auto import ( + MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, + MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES, + ) + + +class TableQuestionAnsweringArgumentHandler(ArgumentHandler): + """ + Handles arguments for the TableQuestionAnsweringPipeline + """ + + def __call__(self, table=None, query=None, **kwargs): + # Returns tqa_pipeline_inputs of shape: + # [ + # {"table": pd.DataFrame, "query": list[str]}, + # ..., + # {"table": pd.DataFrame, "query" : list[str]} + # ] + requires_backends(self, "pandas") + import pandas as pd + + if table is None: + raise ValueError("Keyword argument `table` cannot be None.") + elif query is None: + if isinstance(table, dict) and table.get("query") is not None and table.get("table") is not None: + tqa_pipeline_inputs = [table] + elif isinstance(table, list) and len(table) > 0: + if not all(isinstance(d, dict) for d in table): + raise ValueError( + f"Keyword argument `table` should be a list of dict, but is {(type(d) for d in table)}" + ) + + if table[0].get("query") is not None and table[0].get("table") is not None: + tqa_pipeline_inputs = table + else: + raise ValueError( + "If keyword argument `table` is a list of dictionaries, each dictionary should have a `table`" + f" and `query` key, but only dictionary has keys {table[0].keys()} `table` and `query` keys." + ) + elif Dataset is not None and isinstance(table, Dataset) or isinstance(table, types.GeneratorType): + return table + else: + raise ValueError( + "Invalid input. Keyword argument `table` should be either of type `dict` or `list`, but " + f"is {type(table)})" + ) + else: + tqa_pipeline_inputs = [{"table": table, "query": query}] + + for tqa_pipeline_input in tqa_pipeline_inputs: + if not isinstance(tqa_pipeline_input["table"], pd.DataFrame): + if tqa_pipeline_input["table"] is None: + raise ValueError("Table cannot be None.") + + tqa_pipeline_input["table"] = pd.DataFrame(tqa_pipeline_input["table"]) + + return tqa_pipeline_inputs + + +@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True)) +class TableQuestionAnsweringPipeline(Pipeline): + """ + Table Question Answering pipeline using a `ModelForTableQuestionAnswering`. This pipeline is only available in + PyTorch. + + Unless the model you're using explicitly sets these generation parameters in its configuration files + (`generation_config.json`), the following default values will be used: + - max_new_tokens: 256 + + Example: + + ```python + >>> from transformers import pipeline + + >>> oracle = pipeline(model="google/tapas-base-finetuned-wtq") + >>> table = { + ... "Repository": ["Transformers", "Datasets", "Tokenizers"], + ... "Stars": ["36542", "4512", "3934"], + ... "Contributors": ["651", "77", "34"], + ... "Programming language": ["Python", "Python", "Rust, Python and NodeJS"], + ... } + >>> oracle(query="How many stars does the transformers repository have?", table=table) + {'answer': 'AVERAGE > 36542', 'coordinates': [(0, 1)], 'cells': ['36542'], 'aggregator': 'AVERAGE'} + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) + + This tabular question answering pipeline can currently be loaded from [`pipeline`] using the following task + identifier: `"table-question-answering"`. + + The models that this pipeline can use are models that have been fine-tuned on a tabular question answering task. + See the up-to-date list of available models on + [huggingface.co/models](https://huggingface.co/models?filter=table-question-answering). + """ + + default_input_names = "table,query" + + _pipeline_calls_generate = True + _load_processor = False + _load_image_processor = False + _load_feature_extractor = False + _load_tokenizer = True + # Make sure the docstring is updated when the default generation config is changed + _default_generation_config = GenerationConfig( + max_new_tokens=256, + ) + + def __init__(self, args_parser=TableQuestionAnsweringArgumentHandler(), **kwargs): + super().__init__(**kwargs) + self._args_parser = args_parser + + mapping = MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES.copy() + mapping.update(MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES) + self.check_model_type(mapping) + + self.aggregate = getattr(self.model.config, "aggregation_labels", None) and getattr( + self.model.config, "num_aggregation_labels", None + ) + self.type = "tapas" if hasattr(self.model.config, "aggregation_labels") else None + + def batch_inference(self, **inputs): + return self.model(**inputs) + + def sequential_inference(self, **inputs): + """ + Inference used for models that need to process sequences in a sequential fashion, like the SQA models which + handle conversational query related to a table. + """ + all_logits = [] + all_aggregations = [] + prev_answers = None + batch_size = inputs["input_ids"].shape[0] + + input_ids = inputs["input_ids"].to(self.device) + attention_mask = inputs["attention_mask"].to(self.device) + token_type_ids = inputs["token_type_ids"].to(self.device) + token_type_ids_example = None + + for index in range(batch_size): + # If sequences have already been processed, the token type IDs will be created according to the previous + # answer. + if prev_answers is not None: + prev_labels_example = token_type_ids_example[:, 3] # shape (seq_len,) + model_labels = np.zeros_like(prev_labels_example.cpu().numpy()) # shape (seq_len,) + + token_type_ids_example = token_type_ids[index] # shape (seq_len, 7) + for i in range(model_labels.shape[0]): + segment_id = token_type_ids_example[:, 0].tolist()[i] + col_id = token_type_ids_example[:, 1].tolist()[i] - 1 + row_id = token_type_ids_example[:, 2].tolist()[i] - 1 + + if row_id >= 0 and col_id >= 0 and segment_id == 1: + model_labels[i] = int(prev_answers[(col_id, row_id)]) + + token_type_ids_example[:, 3] = torch.from_numpy(model_labels).type(torch.long).to(self.device) + + input_ids_example = input_ids[index] + attention_mask_example = attention_mask[index] # shape (seq_len,) + token_type_ids_example = token_type_ids[index] # shape (seq_len, 7) + outputs = self.model( + input_ids=input_ids_example.unsqueeze(0), + attention_mask=attention_mask_example.unsqueeze(0), + token_type_ids=token_type_ids_example.unsqueeze(0), + ) + logits = outputs.logits + + if self.aggregate: + all_aggregations.append(outputs.logits_aggregation) + + all_logits.append(logits) + + dist_per_token = torch.distributions.Bernoulli(logits=logits) + probabilities = dist_per_token.probs * attention_mask_example.type(torch.float32).to( + dist_per_token.probs.device + ) + + coords_to_probs = collections.defaultdict(list) + for i, p in enumerate(probabilities.squeeze().tolist()): + segment_id = token_type_ids_example[:, 0].tolist()[i] + col = token_type_ids_example[:, 1].tolist()[i] - 1 + row = token_type_ids_example[:, 2].tolist()[i] - 1 + if col >= 0 and row >= 0 and segment_id == 1: + coords_to_probs[(col, row)].append(p) + + prev_answers = {key: np.array(coords_to_probs[key]).mean() > 0.5 for key in coords_to_probs} + + logits_batch = torch.cat(tuple(all_logits), 0) + + return (logits_batch,) if not self.aggregate else (logits_batch, torch.cat(tuple(all_aggregations), 0)) + + def __call__(self, *args, **kwargs): + r""" + Answers queries according to a table. The pipeline accepts several types of inputs which are detailed below: + + - `pipeline(table, query)` + - `pipeline(table, [query])` + - `pipeline(table=table, query=query)` + - `pipeline(table=table, query=[query])` + - `pipeline({"table": table, "query": query})` + - `pipeline({"table": table, "query": [query]})` + - `pipeline([{"table": table, "query": query}, {"table": table, "query": query}])` + + The `table` argument should be a dict or a DataFrame built from that dict, containing the whole table: + + Example: + + ```python + data = { + "actors": ["brad pitt", "leonardo di caprio", "george clooney"], + "age": ["56", "45", "59"], + "number of movies": ["87", "53", "69"], + "date of birth": ["7 february 1967", "10 june 1996", "28 november 1967"], + } + ``` + + This dictionary can be passed in as such, or can be converted to a pandas DataFrame: + + Example: + + ```python + import pandas as pd + + table = pd.DataFrame.from_dict(data) + ``` + + Args: + table (`pd.DataFrame` or `Dict`): + Pandas DataFrame or dictionary that will be converted to a DataFrame containing all the table values. + See above for an example of dictionary. + query (`str` or `list[str]`): + Query or list of queries that will be sent to the model alongside the table. + sequential (`bool`, *optional*, defaults to `False`): + Whether to do inference sequentially or as a batch. Batching is faster, but models like SQA require the + inference to be done sequentially to extract relations within sequences, given their conversational + nature. + padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): + Activates and controls padding. Accepts the following values: + + - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single + sequence if provided). + - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum + acceptable input length for the model if that argument is not provided. + - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different + lengths). + + truncation (`bool`, `str` or [`TapasTruncationStrategy`], *optional*, defaults to `False`): + Activates and controls truncation. Accepts the following values: + + - `True` or `'drop_rows_to_fit'`: Truncate to a maximum length specified with the argument `max_length` + or to the maximum acceptable input length for the model if that argument is not provided. This will + truncate row by row, removing rows from the table. + - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths + greater than the model maximum admissible input size). + + + Return: + A dictionary or a list of dictionaries containing results: Each result is a dictionary with the following + keys: + + - **answer** (`str`) -- The answer of the query given the table. If there is an aggregator, the answer will + be preceded by `AGGREGATOR >`. + - **coordinates** (`list[tuple[int, int]]`) -- Coordinates of the cells of the answers. + - **cells** (`list[str]`) -- List of strings made up of the answer cell values. + - **aggregator** (`str`) -- If the model has an aggregator, this returns the aggregator. + """ + pipeline_inputs = self._args_parser(*args, **kwargs) + + results = super().__call__(pipeline_inputs, **kwargs) + if len(results) == 1: + return results[0] + return results + + def _sanitize_parameters(self, sequential=None, padding=None, truncation=None, **kwargs): + preprocess_params = {} + if padding is not None: + preprocess_params["padding"] = padding + if truncation is not None: + preprocess_params["truncation"] = truncation + + forward_params = {} + if sequential is not None: + forward_params["sequential"] = sequential + + if getattr(self, "assistant_model", None) is not None: + forward_params["assistant_model"] = self.assistant_model + if getattr(self, "assistant_tokenizer", None) is not None: + forward_params["tokenizer"] = self.tokenizer + forward_params["assistant_tokenizer"] = self.assistant_tokenizer + + return preprocess_params, forward_params, {} + + def preprocess(self, pipeline_input, padding=True, truncation=None): + if truncation is None: + if self.type == "tapas": + truncation = "drop_rows_to_fit" + else: + truncation = "do_not_truncate" + + table, query = pipeline_input["table"], pipeline_input["query"] + if table.empty: + raise ValueError("table is empty") + if query is None or query == "": + raise ValueError("query is empty") + inputs = self.tokenizer(table, query, return_tensors="pt", truncation=truncation, padding=padding) + inputs["table"] = table + return inputs + + def _forward(self, model_inputs, sequential=False, **generate_kwargs): + table = model_inputs.pop("table") + + if self.type == "tapas": + if sequential: + outputs = self.sequential_inference(**model_inputs) + else: + outputs = self.batch_inference(**model_inputs) + else: + # User-defined `generation_config` passed to the pipeline call take precedence + if "generation_config" not in generate_kwargs: + generate_kwargs["generation_config"] = self.generation_config + + outputs = self.model.generate(**model_inputs, **generate_kwargs) + model_outputs = {"model_inputs": model_inputs, "table": table, "outputs": outputs} + return model_outputs + + def postprocess(self, model_outputs): + inputs = model_outputs["model_inputs"] + table = model_outputs["table"] + outputs = model_outputs["outputs"] + if self.type == "tapas": + if self.aggregate: + logits, logits_agg = outputs[:2] + predictions = self.tokenizer.convert_logits_to_predictions(inputs, logits, logits_agg) + answer_coordinates_batch, agg_predictions = predictions + aggregators = {i: self.model.config.aggregation_labels[pred] for i, pred in enumerate(agg_predictions)} + + no_agg_label_index = self.model.config.no_aggregation_label_index + aggregators_prefix = { + i: aggregators[i] + " > " for i, pred in enumerate(agg_predictions) if pred != no_agg_label_index + } + else: + logits = outputs[0] + predictions = self.tokenizer.convert_logits_to_predictions(inputs, logits) + answer_coordinates_batch = predictions[0] + aggregators = {} + aggregators_prefix = {} + answers = [] + for index, coordinates in enumerate(answer_coordinates_batch): + cells = [table.iat[coordinate] for coordinate in coordinates] + aggregator = aggregators.get(index, "") + aggregator_prefix = aggregators_prefix.get(index, "") + answer = { + "answer": aggregator_prefix + ", ".join(cells), + "coordinates": coordinates, + "cells": [table.iat[coordinate] for coordinate in coordinates], + } + if aggregator: + answer["aggregator"] = aggregator + + answers.append(answer) + if len(answer) == 0: + raise PipelineException("Table question answering", self.model.name_or_path, "Empty answer") + else: + answers = [{"answer": answer} for answer in self.tokenizer.batch_decode(outputs, skip_special_tokens=True)] + + return answers if len(answers) > 1 else answers[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/text_classification.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/text_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..ab9a5d8efbc4ae9f60e0d39782f418863d773b7a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/text_classification.py @@ -0,0 +1,219 @@ +import inspect +from typing import Any + +import numpy as np + +from ..utils import ExplicitEnum, add_end_docstrings, is_torch_available +from .base import GenericTensor, Pipeline, build_pipeline_init_args + + +if is_torch_available(): + from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES + + +def sigmoid(_outputs): + return 1.0 / (1.0 + np.exp(-_outputs)) + + +def softmax(_outputs): + maxes = np.max(_outputs, axis=-1, keepdims=True) + shifted_exp = np.exp(_outputs - maxes) + return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True) + + +class ClassificationFunction(ExplicitEnum): + SIGMOID = "sigmoid" + SOFTMAX = "softmax" + NONE = "none" + + +@add_end_docstrings( + build_pipeline_init_args(has_tokenizer=True), + r""" + function_to_apply (`str`, *optional*, defaults to `"default"`): + The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: + + - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model + has several labels, will apply the softmax function on the output. In case of regression tasks, will not + apply any function on the output. + - `"sigmoid"`: Applies the sigmoid function on the output. + - `"softmax"`: Applies the softmax function on the output. + - `"none"`: Does not apply any function on the output.""", +) +class TextClassificationPipeline(Pipeline): + """ + Text classification pipeline using any `ModelForSequenceClassification`. See the [sequence classification + examples](../task_summary#sequence-classification) for more information. + + Example: + + ```python + >>> from transformers import pipeline + + >>> classifier = pipeline(model="distilbert/distilbert-base-uncased-finetuned-sst-2-english") + >>> classifier("This movie is disgustingly good !") + [{'label': 'POSITIVE', 'score': 1.0}] + + >>> classifier("Director tried too much.") + [{'label': 'NEGATIVE', 'score': 0.996}] + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) + + This text classification pipeline can currently be loaded from [`pipeline`] using the following task identifier: + `"sentiment-analysis"` (for classifying sequences according to positive or negative sentiments). + + If multiple classification labels are available (`model.config.num_labels >= 2`), the pipeline will run a softmax + over the results. If there is a single label, the pipeline will run a sigmoid over the result. In case of regression + tasks (`model.config.problem_type == "regression"`), will not apply any function on the output. + + The models that this pipeline can use are models that have been fine-tuned on a sequence classification task. See + the up-to-date list of available models on + [huggingface.co/models](https://huggingface.co/models?filter=text-classification). + """ + + _load_processor = False + _load_image_processor = False + _load_feature_extractor = False + _load_tokenizer = True + + function_to_apply = ClassificationFunction.NONE + + def __init__(self, **kwargs): + super().__init__(**kwargs) + + self.check_model_type(MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES) + + def _sanitize_parameters(self, function_to_apply=None, top_k="", **tokenizer_kwargs): + # Using "" as default argument because we're going to use `top_k=None` in user code to declare + # "No top_k" + preprocess_params = tokenizer_kwargs + + postprocess_params = {} + + if isinstance(top_k, int) or top_k is None: + postprocess_params["top_k"] = top_k + postprocess_params["_legacy"] = False + + if isinstance(function_to_apply, str): + function_to_apply = ClassificationFunction[function_to_apply.upper()] + + if function_to_apply is not None: + postprocess_params["function_to_apply"] = function_to_apply + return preprocess_params, {}, postprocess_params + + def __call__( + self, + inputs: str | list[str] | dict[str, str] | list[dict[str, str]], + **kwargs: Any, + ) -> list[dict[str, Any]]: + """ + Classify the text(s) given as inputs. + + Args: + inputs (`str` or `list[str]` or `dict[str]`, or `list[dict[str]]`): + One or several texts to classify. In order to use text pairs for your classification, you can send a + dictionary containing `{"text", "text_pair"}` keys, or a list of those. + top_k (`int`, *optional*, defaults to `1`): + How many results to return. + function_to_apply (`str`, *optional*, defaults to `"default"`): + The function to apply to the model outputs in order to retrieve the scores. Accepts four different + values: + + If this argument is not specified, then it will apply the following functions according to the number + of labels: + + - If problem type is regression, will not apply any function on the output. + - If the model has a single label, will apply the sigmoid function on the output. + - If the model has several labels, will apply the softmax function on the output. + + Possible values are: + + - `"sigmoid"`: Applies the sigmoid function on the output. + - `"softmax"`: Applies the softmax function on the output. + - `"none"`: Does not apply any function on the output. + + Return: + A list of `dict`: Each result comes as list of dictionaries with the following keys: + + - **label** (`str`) -- The label predicted. + - **score** (`float`) -- The corresponding probability. + + If `top_k` is used, one such dictionary is returned per label. + """ + inputs = (inputs,) + result = super().__call__(*inputs, **kwargs) + # TODO try and retrieve it in a nicer way from _sanitize_parameters. + _legacy = "top_k" not in kwargs + if isinstance(inputs[0], str) and _legacy: + # This pipeline is odd, and return a list when single item is run + return [result] + else: + return result + + def preprocess(self, inputs, **tokenizer_kwargs) -> dict[str, GenericTensor]: + return_tensors = "pt" + if isinstance(inputs, dict): + return self.tokenizer(**inputs, return_tensors=return_tensors, **tokenizer_kwargs) + elif isinstance(inputs, list) and len(inputs) == 1 and isinstance(inputs[0], list) and len(inputs[0]) == 2: + # It used to be valid to use a list of list of list for text pairs, keeping this path for BC + return self.tokenizer( + text=inputs[0][0], text_pair=inputs[0][1], return_tensors=return_tensors, **tokenizer_kwargs + ) + elif isinstance(inputs, list): + # This is likely an invalid usage of the pipeline attempting to pass text pairs. + raise ValueError( + "The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a" + ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.' + ) + return self.tokenizer(inputs, return_tensors=return_tensors, **tokenizer_kwargs) + + def _forward(self, model_inputs): + # `XXXForSequenceClassification` models should not use `use_cache=True` even if it's supported + model_forward = self.model.forward + if "use_cache" in inspect.signature(model_forward).parameters: + model_inputs["use_cache"] = False + return self.model(**model_inputs) + + def postprocess(self, model_outputs, function_to_apply=None, top_k=1, _legacy=True): + # `_legacy` is used to determine if we're running the naked pipeline and in backward + # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running + # the more natural result containing the list. + # Default value before `set_parameters` + if function_to_apply is None: + if self.model.config.problem_type == "regression": + function_to_apply = ClassificationFunction.NONE + elif self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: + function_to_apply = ClassificationFunction.SIGMOID + elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: + function_to_apply = ClassificationFunction.SOFTMAX + elif hasattr(self.model.config, "function_to_apply") and function_to_apply is None: + function_to_apply = self.model.config.function_to_apply + else: + function_to_apply = ClassificationFunction.NONE + + outputs = model_outputs["logits"][0] + + # To enable using fp16 and bf16 + outputs = outputs.float().numpy() + + if function_to_apply == ClassificationFunction.SIGMOID: + scores = sigmoid(outputs) + elif function_to_apply == ClassificationFunction.SOFTMAX: + scores = softmax(outputs) + elif function_to_apply == ClassificationFunction.NONE: + scores = outputs + else: + raise ValueError(f"Unrecognized `function_to_apply` argument: {function_to_apply}") + + if top_k == 1 and _legacy: + return {"label": self.model.config.id2label[scores.argmax().item()], "score": scores.max().item()} + + dict_scores = [ + {"label": self.model.config.id2label[i], "score": score.item()} for i, score in enumerate(scores) + ] + if not _legacy: + dict_scores.sort(key=lambda x: x["score"], reverse=True) + if top_k is not None: + dict_scores = dict_scores[:top_k] + return dict_scores diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/text_generation.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/text_generation.py new file mode 100644 index 0000000000000000000000000000000000000000..6a0b2966d07cbfba9aaf2738f5453a336278c136 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/text_generation.py @@ -0,0 +1,508 @@ +import enum +from typing import Any, overload + +from ..generation import GenerationConfig +from ..utils import ModelOutput, add_end_docstrings, is_torch_available +from ..utils.chat_template_utils import Chat, ChatType +from .base import Pipeline, build_pipeline_init_args + + +if is_torch_available(): + import torch + + from ..models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES + + +class ReturnType(enum.Enum): + TENSORS = 0 + NEW_TEXT = 1 + FULL_TEXT = 2 + + +@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True)) +class TextGenerationPipeline(Pipeline): + """ + Language generation pipeline using any `ModelWithLMHead` or `ModelForCausalLM`. This pipeline predicts the words + that will follow a specified text prompt. When the underlying model is a conversational model, it can also accept + one or more chats, in which case the pipeline will operate in chat mode and will continue the chat(s) by adding + its response(s). Each chat takes the form of a list of dicts, where each dict contains "role" and "content" keys. + + Unless the model you're using explicitly sets these generation parameters in its configuration files + (`generation_config.json`), the following default values will be used: + - max_new_tokens: 256 + - do_sample: True + - temperature: 0.7 + + Examples: + + ```python + >>> from transformers import pipeline + + >>> generator = pipeline(model="openai-community/gpt2") + >>> generator("I can't believe you did such a ", do_sample=False) + [{'generated_text': "I can't believe you did such a icky thing to me. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I"}] + + >>> # These parameters will return suggestions, and only the newly created text making it easier for prompting suggestions. + >>> outputs = generator("My tart needs some", num_return_sequences=4, return_full_text=False) + ``` + + ```python + >>> from transformers import pipeline + + >>> generator = pipeline(model="HuggingFaceH4/zephyr-7b-beta") + >>> # Zephyr-beta is a conversational model, so let's pass it a chat instead of a single string + >>> generator([{"role": "user", "content": "What is the capital of France? Answer in one word."}], do_sample=False, max_new_tokens=2) + [{'generated_text': [{'role': 'user', 'content': 'What is the capital of France? Answer in one word.'}, {'role': 'assistant', 'content': 'Paris'}]}] + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial). You can pass text + generation parameters to this pipeline to control stopping criteria, decoding strategy, and more. Learn more about + text generation parameters in [Text generation strategies](../generation_strategies) and [Text + generation](text_generation). + + This language generation pipeline can currently be loaded from [`pipeline`] using the following task identifier: + `"text-generation"`. + + The models that this pipeline can use are models that have been trained with an autoregressive language modeling + objective. See the list of available [text completion models](https://huggingface.co/models?filter=text-generation) + and the list of [conversational models](https://huggingface.co/models?other=conversational) + on [huggingface.co/models]. + """ + + # Prefix text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia + # in https://github.com/rusiaaman/XLNet-gen#methodology + # and https://medium.com/@amanrusia/xlnet-speaks-comparison-to-gpt-2-ea1a4e9ba39e + + XL_PREFIX = """ + In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The + voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western + Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision + and denounces one of the men as a horse thief. Although his father initially slaps him for making such an + accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of + the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop, + begging for his blessing. + """ + + _pipeline_calls_generate = True + _load_processor = False + _load_image_processor = False + _load_feature_extractor = False + _load_tokenizer = True + + # Make sure the docstring is updated when the default generation config is changed + _default_generation_config = GenerationConfig( + max_new_tokens=256, + do_sample=True, # free-form text generation often uses sampling + temperature=0.7, + ) + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.check_model_type(MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) + # Decoder-only models require left-padding for correct batched generation. + # Only override when there is no feature_extractor, to avoid padding_side conflicts + # (e.g., WhisperForCausalLM has a feature_extractor that pads on the right). + if self.tokenizer is not None and self.tokenizer.padding_side == "right": + self.tokenizer.padding_side = "left" + + if "prefix" not in self._preprocess_params: + # This is very specific. The logic is quite complex and needs to be done + # as a "default". + # It also defines both some preprocess_kwargs and generate_kwargs + # which is why we cannot put them in their respective methods. + prefix = None + if self.prefix is not None: + prefix = self.prefix + if prefix is None and self.model.__class__.__name__ in [ + "XLNetLMHeadModel", + "TransfoXLLMHeadModel", + ]: + # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. + prefix = self.XL_PREFIX + if prefix is not None: + # Recalculate some generate_kwargs linked to prefix. + preprocess_params, forward_params, _ = self._sanitize_parameters(prefix=prefix, **self._forward_params) + self._preprocess_params = {**self._preprocess_params, **preprocess_params} + self._forward_params = {**self._forward_params, **forward_params} + + def _sanitize_parameters( + self, + return_full_text=None, + return_tensors=None, + return_text=None, + return_type=None, + clean_up_tokenization_spaces=None, + prefix=None, + handle_long_generation=None, + stop_sequence=None, + truncation=None, + max_length=None, + continue_final_message=None, + skip_special_tokens=None, + tokenizer_encode_kwargs=None, + tools=None, + documents=None, + **generate_kwargs, + ): + # preprocess kwargs + preprocess_params = {} + add_special_tokens = False + if "add_special_tokens" in generate_kwargs: + add_special_tokens = preprocess_params["add_special_tokens"] = generate_kwargs.pop("add_special_tokens") + + if "padding" in generate_kwargs: + preprocess_params["padding"] = generate_kwargs.pop("padding") + + if truncation is not None: + preprocess_params["truncation"] = truncation + + if max_length is not None: + preprocess_params["max_length"] = max_length + generate_kwargs["max_length"] = max_length + + if tools is not None: + preprocess_params["tools"] = tools + if documents is not None: + preprocess_params["documents"] = documents + + if prefix is not None: + preprocess_params["prefix"] = prefix + if prefix: + prefix_inputs = self.tokenizer( + prefix, padding=False, add_special_tokens=add_special_tokens, return_tensors="pt" + ) + generate_kwargs["prefix_length"] = prefix_inputs["input_ids"].shape[-1] + + if handle_long_generation is not None: + if handle_long_generation != "hole": + raise ValueError( + f"{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected" + " [None, 'hole']" + ) + preprocess_params["handle_long_generation"] = handle_long_generation + + if continue_final_message is not None: + preprocess_params["continue_final_message"] = continue_final_message + + if tokenizer_encode_kwargs is not None: + preprocess_params["tokenizer_encode_kwargs"] = tokenizer_encode_kwargs + + preprocess_params.update(generate_kwargs) + + # forward kwargs + if stop_sequence is not None: + stop_sequence_ids = self.tokenizer.encode(stop_sequence, add_special_tokens=False) + generate_kwargs["eos_token_id"] = stop_sequence_ids + forward_params = generate_kwargs + if self.assistant_model is not None: + forward_params["assistant_model"] = self.assistant_model + if self.assistant_tokenizer is not None: + forward_params["tokenizer"] = self.tokenizer + forward_params["assistant_tokenizer"] = self.assistant_tokenizer + + # postprocess kwargs + postprocess_params = {} + if return_full_text is not None and return_type is None: + if return_text is not None: + raise ValueError("`return_text` is mutually exclusive with `return_full_text`") + if return_tensors is not None: + raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`") + return_type = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT + if return_tensors is not None and return_type is None: + if return_text is not None: + raise ValueError("`return_text` is mutually exclusive with `return_tensors`") + return_type = ReturnType.TENSORS + if return_type is not None: + postprocess_params["return_type"] = return_type + if clean_up_tokenization_spaces is not None: + postprocess_params["clean_up_tokenization_spaces"] = clean_up_tokenization_spaces + if continue_final_message is not None: + postprocess_params["continue_final_message"] = continue_final_message + if skip_special_tokens is not None: + postprocess_params["skip_special_tokens"] = skip_special_tokens + + return preprocess_params, forward_params, postprocess_params + + # overriding _parse_and_tokenize to allow for unusual language-modeling tokenizer arguments + def _parse_and_tokenize(self, *args, **kwargs): + """ + Parse arguments and tokenize + """ + # Parse arguments + if self.model.__class__.__name__ == "TransfoXLLMHeadModel": + kwargs.update({"add_space_before_punct_symbol": True}) + + return super()._parse_and_tokenize(*args, **kwargs) + + @overload + def __call__(self, text_inputs: str, **kwargs: Any) -> list[dict[str, str]]: ... + + @overload + def __call__(self, text_inputs: list[str], **kwargs: Any) -> list[list[dict[str, str]]]: ... + + @overload + def __call__(self, text_inputs: ChatType, **kwargs: Any) -> list[dict[str, ChatType]]: ... + + @overload + def __call__(self, text_inputs: list[ChatType], **kwargs: Any) -> list[list[dict[str, ChatType]]]: ... + + def __call__(self, text_inputs, **kwargs): + """ + Complete the prompt(s) given as inputs. + + Args: + text_inputs (`str`, `list[str]`, `ChatType`, or `list[ChatType]`): + One or several prompts (or one list of prompts) to complete. If strings or a list of string are + passed, this pipeline will continue each prompt. Alternatively, a "chat", in the form of a list + of dicts with "role" and "content" keys, can be passed, or a list of such chats. When chats are passed, + the model's chat template will be used to format them before passing them to the model. + return_tensors (`bool`, *optional*, defaults to `False`): + Returns the tensors of predictions (as token indices) in the outputs. If set to + `True`, the decoded text is not returned. + return_text (`bool`, *optional*): + Returns the decoded texts in the outputs. + return_full_text (`bool`, *optional*, defaults to `True`): + If set to `False` only added text is returned, otherwise the full text is returned. Cannot be + specified at the same time as `return_text`. + clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`): + Whether or not to clean up the potential extra spaces in the text output. + continue_final_message( `bool`, *optional*): This indicates that you want the model to continue the + last message in the input chat rather than starting a new one, allowing you to "prefill" its response. + By default this is `True` when the final message in the input chat has the `assistant` role and + `False` otherwise, but you can manually override that behaviour by setting this flag. + prefix (`str`, *optional*): + Prefix added to prompt. + handle_long_generation (`str`, *optional*): + By default, this pipelines does not handle long generation (ones that exceed in one form or the other + the model maximum length). There is no perfect way to address this (more info + :https://github.com/huggingface/transformers/issues/14033#issuecomment-948385227). This provides common + strategies to work around that problem depending on your use case. + + - `None` : default strategy where nothing in particular happens + - `"hole"`: Truncates left of input, and leaves a gap wide enough to let generation happen (might + truncate a lot of the prompt and not suitable when generation exceed the model capacity) + tokenizer_encode_kwargs (`dict`, *optional*): + Additional keyword arguments to pass along to the encoding step of the tokenizer. If the text input is + a chat, it is passed to `apply_chat_template`. Otherwise, it is passed to `__call__`. + generate_kwargs (`dict`, *optional*): + Additional keyword arguments to pass along to the generate method of the model (see the generate method + [here](./text_generation)). + + Return: + A list or a list of lists of `dict`: Returns one of the following dictionaries (cannot return a combination + of both `generated_text` and `generated_token_ids`): + + - **generated_text** (`str`, present when `return_text=True`) -- The generated text. + - **generated_token_ids** (`torch.Tensor`, present when `return_tensors=True`) -- The token + ids of the generated text. + """ + return super().__call__(text_inputs, **kwargs) + + def preprocess( + self, + prompt_text, + prefix="", + handle_long_generation=None, + add_special_tokens=None, + truncation=None, + padding=None, + max_length=None, + continue_final_message=None, + tokenizer_encode_kwargs=None, + tools=None, + documents=None, + **generate_kwargs, + ): + # Only set non-None tokenizer kwargs, so as to rely on the tokenizer's defaults + tokenizer_kwargs = { + "add_special_tokens": add_special_tokens, + "truncation": truncation, + "padding": padding, + "max_length": max_length, # NOTE: `max_length` is also a `generate` arg. Use `tokenizer_encode_kwargs` to avoid a name clash + } + tokenizer_kwargs = {key: value for key, value in tokenizer_kwargs.items() if value is not None} + tokenizer_kwargs.update(tokenizer_encode_kwargs or {}) + + if isinstance(prompt_text, Chat): + tokenizer_kwargs.pop("add_special_tokens", None) # ignore add_special_tokens on chats + # If the user passes a chat that ends in an assistant message, we treat it as a prefill by default + # because very few models support multiple separate, consecutive assistant messages + if continue_final_message is None: + continue_final_message = prompt_text.messages[-1]["role"] == "assistant" + inputs = self.tokenizer.apply_chat_template( + prompt_text.messages, + add_generation_prompt=not continue_final_message, + continue_final_message=continue_final_message, + return_dict=True, + return_tensors="pt", + tools=tools, + documents=documents, + **tokenizer_kwargs, + ) + else: + inputs = self.tokenizer(prefix + prompt_text, return_tensors="pt", **tokenizer_kwargs) + + inputs["prompt_text"] = prompt_text + + if handle_long_generation == "hole": + cur_len = inputs["input_ids"].shape[-1] + if "max_new_tokens" in generate_kwargs: + new_tokens = generate_kwargs["max_new_tokens"] + else: + new_tokens = generate_kwargs.get("max_length", self.generation_config.max_length) - cur_len + if new_tokens < 0: + raise ValueError("We cannot infer how many new tokens are expected") + if cur_len + new_tokens > self.tokenizer.model_max_length: + keep_length = self.tokenizer.model_max_length - new_tokens + if keep_length <= 0: + raise ValueError( + "We cannot use `hole` to handle this generation the number of desired tokens exceeds the" + " models max length" + ) + + inputs["input_ids"] = inputs["input_ids"][:, -keep_length:] + if "attention_mask" in inputs: + inputs["attention_mask"] = inputs["attention_mask"][:, -keep_length:] + + return inputs + + def _forward(self, model_inputs, **generate_kwargs): + input_ids = model_inputs["input_ids"] + attention_mask = model_inputs.get("attention_mask", None) + # Allow empty prompts + if input_ids.shape[1] == 0: + input_ids = None + attention_mask = None + in_b = 1 + else: + in_b = input_ids.shape[0] + prompt_text = model_inputs.pop("prompt_text") + + # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying + # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. + prefix_length = generate_kwargs.pop("prefix_length", 0) + if prefix_length > 0: + has_max_new_tokens = "max_new_tokens" in generate_kwargs or ( + "generation_config" in generate_kwargs + and generate_kwargs["generation_config"].max_new_tokens is not None + ) + if not has_max_new_tokens: + generate_kwargs["max_length"] = generate_kwargs.get("max_length") or self.generation_config.max_length + generate_kwargs["max_length"] += prefix_length + has_min_new_tokens = "min_new_tokens" in generate_kwargs or ( + "generation_config" in generate_kwargs + and generate_kwargs["generation_config"].min_new_tokens is not None + ) + if not has_min_new_tokens and "min_length" in generate_kwargs: + generate_kwargs["min_length"] += prefix_length + + # User-defined `generation_config` passed to the pipeline call take precedence + if "generation_config" not in generate_kwargs: + generate_kwargs["generation_config"] = self.generation_config + + output = self.model.generate(input_ids=input_ids, attention_mask=attention_mask, **generate_kwargs) + + if isinstance(output, ModelOutput): + generated_sequence = output.sequences + other_outputs = {k: v for k, v in output.items() if k not in {"sequences", "past_key_values"}} + out_b = generated_sequence.shape[0] + + for key, value in other_outputs.items(): + if isinstance(value, torch.Tensor) and value.shape[0] == out_b: + other_outputs[key] = value.reshape(in_b, out_b // in_b, *value.shape[1:]) + if isinstance(value, tuple) and len(value[0]) == out_b: + value = torch.stack(value).swapaxes(0, 1) + other_outputs[key] = value + else: + generated_sequence = output + other_outputs = {} + + out_b = generated_sequence.shape[0] + generated_sequence = generated_sequence.reshape(in_b, out_b // in_b, *generated_sequence.shape[1:]) + + model_outputs = { + "generated_sequence": generated_sequence, + "input_ids": input_ids, + "prompt_text": prompt_text, + } + if other_outputs: + model_outputs.update({"additional_outputs": other_outputs}) + return model_outputs + + def postprocess( + self, + model_outputs, + return_type=ReturnType.FULL_TEXT, + clean_up_tokenization_spaces=True, + continue_final_message=None, + skip_special_tokens=None, + ): + generated_sequence = model_outputs["generated_sequence"][0] + input_ids = model_outputs["input_ids"] + prompt_text = model_outputs["prompt_text"] + generated_sequence = generated_sequence.numpy().tolist() + records = [] + other_outputs = model_outputs.get("additional_outputs", {}) + split_keys = {} + if other_outputs: + for k, v in other_outputs.items(): + if isinstance(v, torch.Tensor) and v.shape[0] == len(generated_sequence): + split_keys[k] = v.numpy().tolist() + + skip_special_tokens = skip_special_tokens if skip_special_tokens is not None else True + if getattr(self.tokenizer, "response_schema", False): + skip_special_tokens = False + for idx, sequence in enumerate(generated_sequence): + if return_type == ReturnType.TENSORS: + record = {"generated_token_ids": sequence} + elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: + # Decode text + text = self.tokenizer.decode( + sequence, + skip_special_tokens=skip_special_tokens, + clean_up_tokenization_spaces=clean_up_tokenization_spaces, + ) + + # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used + if input_ids is None: + prompt_length = 0 + else: + prompt_length = len( + self.tokenizer.decode( + input_ids[0], + skip_special_tokens=skip_special_tokens, + clean_up_tokenization_spaces=clean_up_tokenization_spaces, + ) + ) + + all_text = text[prompt_length:] + if return_type == ReturnType.FULL_TEXT: + if isinstance(prompt_text, str): + all_text = prompt_text + all_text + elif isinstance(prompt_text, Chat): + if continue_final_message is None: + # If the user passes a chat ending in an assistant message, we treat it as a prefill by + # default because very few models support multiple separate, consecutive assistant messages + continue_final_message = prompt_text.messages[-1]["role"] == "assistant" + if continue_final_message: + # With assistant prefill, concat onto the end of the last message + all_text = list(prompt_text.messages)[:-1] + [ + { + "role": prompt_text.messages[-1]["role"], + "content": prompt_text.messages[-1]["content"] + all_text, + } + ] + else: + # When we're not starting from a prefill, the output is a new assistant message + if getattr(self.tokenizer, "response_schema", False): + assistant_message = self.tokenizer.parse_response(all_text) + else: + # If there's no schema, then we have to assume it's all content + assistant_message = {"role": "assistant", "content": all_text} + all_text = list(prompt_text.messages) + [assistant_message] + record = {"generated_text": all_text} + for key, values in split_keys.items(): + record[key] = values[idx] + records.append(record) + + return records diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/text_to_audio.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/text_to_audio.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d70912dd634802fe6e8816e7cbb5acc36f5ed0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/text_to_audio.py @@ -0,0 +1,316 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# 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.from typing import List, Union + +from typing import Any, TypedDict, overload + +from ..audio_utils import AudioInput +from ..generation import GenerationConfig +from ..utils import is_torch_available +from ..utils.chat_template_utils import Chat, ChatType +from .base import Pipeline + + +if is_torch_available(): + import torch + + from ..models.auto.modeling_auto import MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING + from ..models.speecht5.modeling_speecht5 import SpeechT5HifiGan + +DEFAULT_VOCODER_ID = "microsoft/speecht5_hifigan" + + +class AudioOutput(TypedDict, total=False): + """ + audio (`AudioInput`): + The generated audio waveform. + sampling_rate (`int`): + The sampling rate of the generated audio waveform. + """ + + audio: AudioInput + sampling_rate: int + + +class TextToAudioPipeline(Pipeline): + """ + Text-to-audio generation pipeline using any `AutoModelForTextToWaveform` or `AutoModelForTextToSpectrogram`. This + pipeline generates an audio file from an input text and optional other conditional inputs. + + Unless the model you're using explicitly sets these generation parameters in its configuration files + (`generation_config.json`), the following default values will be used: + - max_new_tokens: 256 + + Example: + + ```python + >>> from transformers import pipeline + + >>> pipe = pipeline(model="suno/bark-small") + >>> output = pipe("Hey it's HuggingFace on the phone!") + + >>> audio = output["audio"] + >>> sampling_rate = output["sampling_rate"] + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) + + + + You can specify parameters passed to the model by using [`TextToAudioPipeline.__call__.forward_params`] or + [`TextToAudioPipeline.__call__.generate_kwargs`]. + + Example: + + ```python + >>> from transformers import pipeline + + >>> music_generator = pipeline(task="text-to-audio", model="facebook/musicgen-small") + + >>> # diversify the music generation by adding randomness with a high temperature and set a maximum music length + >>> generate_kwargs = { + ... "do_sample": True, + ... "temperature": 0.7, + ... "max_new_tokens": 35, + ... } + + >>> outputs = music_generator("Techno music with high melodic riffs", generate_kwargs=generate_kwargs) + ``` + + + + This pipeline can currently be loaded from [`pipeline`] using the following task identifiers: `"text-to-speech"` or + `"text-to-audio"`. + + See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=text-to-speech). + """ + + _pipeline_calls_generate = True + _load_processor = None # prioritize processors as some models require it + _load_image_processor = False + _load_feature_extractor = False + _load_tokenizer = True + + # Make sure the docstring is updated when the default generation config is changed + _default_generation_config = GenerationConfig( + max_new_tokens=256, + ) + + def __init__(self, *args, vocoder=None, sampling_rate=None, **kwargs): + super().__init__(*args, **kwargs) + + self.vocoder = None + if self.model.__class__ in MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING.values(): + self.vocoder = ( + SpeechT5HifiGan.from_pretrained(DEFAULT_VOCODER_ID).to(self.model.device) + if vocoder is None + else vocoder + ) + + if self.model.config.model_type in ["musicgen", "speecht5"]: + # MusicGen and SpeechT5 expect to use their tokenizer instead + self.processor = None + + self.sampling_rate = sampling_rate + if self.vocoder is not None: + self.sampling_rate = self.vocoder.config.sampling_rate + + if self.sampling_rate is None: + # get sampling_rate from config and generation config + + config = self.model.config + gen_config = self.model.__dict__.get("generation_config", None) + if gen_config is not None: + config.update({k: v for k, v in gen_config.to_dict().items() if v is not None}) + + for sampling_rate_name in ["sample_rate", "sampling_rate"]: + sampling_rate = getattr(config, sampling_rate_name, None) + if sampling_rate is not None: + self.sampling_rate = sampling_rate + elif getattr(config, "codec_config", None) is not None: + sampling_rate = getattr(config.codec_config, sampling_rate_name, None) + if sampling_rate is not None: + self.sampling_rate = sampling_rate + + # last fallback to get the sampling rate based on processor + if self.sampling_rate is None and self.processor is not None and hasattr(self.processor, "feature_extractor"): + self.sampling_rate = self.processor.feature_extractor.sampling_rate + + def preprocess(self, text, **kwargs): + if isinstance(text, str): + text = [text] + + if self.model.config.model_type == "bark": + # bark Tokenizer is called with BarkProcessor which uses those kwargs + # Check if generation_config has semantic_config (BarkGenerationConfig) or use default + max_length = 256 + if hasattr(self.generation_config, "semantic_config"): + max_length = getattr(self.generation_config.semantic_config, "max_input_semantic_length", 256) + new_kwargs = { + "max_length": max_length, + "add_special_tokens": False, + "return_attention_mask": True, + "return_token_type_ids": False, + } + + # priority is given to kwargs + new_kwargs.update(kwargs) + kwargs = new_kwargs + + preprocessor = self.processor if self.processor is not None else self.tokenizer + if isinstance(text, Chat): + output = preprocessor.apply_chat_template( + text.messages, + tokenize=True, + return_dict=True, + **kwargs, + ) + else: + # Add speaker ID if needed and user didn't insert at start of text + if self.model.config.model_type == "csm": + text = [f"[0]{t}" if not t.startswith("[") else t for t in text] + kwargs.setdefault("add_special_tokens", True) + if self.model.config.model_type == "dia": + text = [f"[S1] {t}" if not t.startswith("[") else t for t in text] + output = preprocessor(text, **kwargs, return_tensors="pt") + + return output + + def _forward(self, model_inputs, **kwargs): + # we expect some kwargs to be additional tensors which need to be on the right device + kwargs = self._ensure_tensor_on_device(kwargs, device=self.device) + forward_params = kwargs["forward_params"] + generate_kwargs = kwargs["generate_kwargs"] + + if self.model.can_generate(): + # we expect some kwargs to be additional tensors which need to be on the right device + generate_kwargs = self._ensure_tensor_on_device(generate_kwargs, device=self.device) + + # User-defined `generation_config` passed to the pipeline call take precedence + if "generation_config" not in generate_kwargs: + generate_kwargs["generation_config"] = self.generation_config + + # generate_kwargs get priority over forward_params + forward_params.update(generate_kwargs) + + # ensure dict output to facilitate postprocessing + forward_params.update({"return_dict_in_generate": True}) + + if self.model.config.model_type in ["csm"]: + # NOTE (ebezzam): CSM does not have the audio tokenizer in the processor therefore `output_audio=True` + # needed for decoding to audio + if "output_audio" not in forward_params: + forward_params["output_audio"] = True + + output = self.model.generate(**model_inputs, **forward_params) + else: + if len(generate_kwargs): + raise ValueError( + "You're using the `TextToAudioPipeline` with a forward-only model, but `generate_kwargs` is non " + "empty. For forward-only TTA models, please use `forward_params` instead of `generate_kwargs`. " + f"For reference, the `generate_kwargs` used here are: {generate_kwargs.keys()}" + ) + output = self.model(**model_inputs, **forward_params)[0] + + if self.vocoder is not None: + # in that case, the output is a spectrogram that needs to be converted into a waveform + output = self.vocoder(output) + + return output + + @overload + def __call__(self, text_inputs: str, **forward_params: Any) -> AudioOutput: ... + + @overload + def __call__(self, text_inputs: list[str], **forward_params: Any) -> list[AudioOutput]: ... + + @overload + def __call__(self, text_inputs: ChatType, **forward_params: Any) -> AudioOutput: ... + + @overload + def __call__(self, text_inputs: list[ChatType], **forward_params: Any) -> list[AudioOutput]: ... + + def __call__(self, text_inputs, **forward_params): + """ + Generates speech/audio from the inputs. See the [`TextToAudioPipeline`] documentation for more information. + + Args: + text_inputs (`str`, `list[str]`, `ChatType`, or `list[ChatType]`): + One or several texts to generate. If strings or a list of string are passed, this pipeline will + generate the corresponding text. Alternatively, a "chat", in the form of a list of dicts with "role" + and "content" keys, can be passed, or a list of such chats. When chats are passed, the model's chat + template will be used to format them before passing them to the model. + forward_params (`dict`, *optional*): + Parameters passed to the model generation/forward method. `forward_params` are always passed to the + underlying model. + generate_kwargs (`dict`, *optional*): + The dictionary of ad-hoc parametrization of `generate_config` to be used for the generation call. For a + complete overview of generate, check the [following + guide](https://huggingface.co/docs/transformers/en/main_classes/text_generation). `generate_kwargs` are + only passed to the underlying model if the latter is a generative model. + + Return: + `AudioOutput` or a list of `AudioOutput`, which is a `TypedDict` with two keys: + + - **audio** (`np.ndarray` of shape `(nb_channels, audio_length)`) -- The generated audio waveform. + - **sampling_rate** (`int`) -- The sampling rate of the generated audio waveform. + """ + return super().__call__(text_inputs, **forward_params) + + def _sanitize_parameters( + self, + preprocess_params=None, + forward_params=None, + generate_kwargs=None, + ): + if getattr(self, "assistant_model", None) is not None: + generate_kwargs["assistant_model"] = self.assistant_model + if getattr(self, "assistant_tokenizer", None) is not None: + generate_kwargs["tokenizer"] = self.tokenizer + generate_kwargs["assistant_tokenizer"] = self.assistant_tokenizer + + params = { + "forward_params": forward_params if forward_params else {}, + "generate_kwargs": generate_kwargs if generate_kwargs else {}, + } + + if preprocess_params is None: + preprocess_params = {} + postprocess_params = {} + + return preprocess_params, params, postprocess_params + + def postprocess(self, audio): + needs_decoding = False + if isinstance(audio, dict): + if "audio" in audio: + audio = audio["audio"] + else: + needs_decoding = True + audio = audio["sequences"] + elif isinstance(audio, tuple): + audio = audio[0] + + if needs_decoding and self.processor is not None: + audio = self.processor.decode(audio) + + if isinstance(audio, list): + audio = [el.to(device="cpu", dtype=torch.float).numpy().squeeze() for el in audio] + audio = audio if len(audio) > 1 else audio[0] + else: + audio = audio.to(device="cpu", dtype=torch.float).numpy().squeeze() + + return AudioOutput( + audio=audio, + sampling_rate=self.sampling_rate, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/token_classification.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/token_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..7deca9dc900ac006932996acee4ba2bf3e1f2ab1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/token_classification.py @@ -0,0 +1,622 @@ +import types +import warnings +from typing import Any, overload + +import numpy as np + +from ..models.bert.tokenization_bert_legacy import BasicTokenizer +from ..utils import ( + ExplicitEnum, + add_end_docstrings, + is_torch_available, +) +from .base import ArgumentHandler, ChunkPipeline, Dataset, build_pipeline_init_args + + +if is_torch_available(): + import torch + + from ..models.auto.modeling_auto import MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES + + +class TokenClassificationArgumentHandler(ArgumentHandler): + """ + Handles arguments for token classification. + """ + + def __call__(self, inputs: str | list[str], **kwargs): + is_split_into_words = kwargs.get("is_split_into_words", False) + delimiter = kwargs.get("delimiter") + + if inputs is not None and isinstance(inputs, (list, tuple)) and len(inputs) > 0: + inputs = list(inputs) + batch_size = len(inputs) + elif isinstance(inputs, str): + inputs = [inputs] + batch_size = 1 + elif Dataset is not None and isinstance(inputs, Dataset) or isinstance(inputs, types.GeneratorType): + return inputs, is_split_into_words, None, delimiter + else: + raise ValueError("At least one input is required.") + + offset_mapping = kwargs.get("offset_mapping") + if offset_mapping: + if isinstance(offset_mapping, list) and isinstance(offset_mapping[0], tuple): + offset_mapping = [offset_mapping] + if len(offset_mapping) != batch_size: + raise ValueError("offset_mapping should have the same batch size as the input") + return inputs, is_split_into_words, offset_mapping, delimiter + + +class AggregationStrategy(ExplicitEnum): + """All the valid aggregation strategies for TokenClassificationPipeline""" + + NONE = "none" + SIMPLE = "simple" + FIRST = "first" + AVERAGE = "average" + MAX = "max" + + +@add_end_docstrings( + build_pipeline_init_args(has_tokenizer=True), + r""" + ignore_labels (`list[str]`, defaults to `["O"]`): + A list of labels to ignore. + stride (`int`, *optional*): + If stride is provided, the pipeline is applied on all the text. The text is split into chunks of size + model_max_length. Works only with fast tokenizers and `aggregation_strategy` different from `NONE`. The + value of this argument defines the number of overlapping tokens between chunks. In other words, the model + will shift forward by `tokenizer.model_max_length - stride` tokens each step. + aggregation_strategy (`str`, *optional*, defaults to `"none"`): + The strategy to fuse (or not) tokens based on the model prediction. + + - "none" : Will simply not do any aggregation and simply return raw results from the model + - "simple" : Will attempt to group entities following the default schema. (A, B-TAG), (B, I-TAG), (C, + I-TAG), (D, B-TAG2) (E, B-TAG2) will end up being [{"word": ABC, "entity": "TAG"}, {"word": "D", + "entity": "TAG2"}, {"word": "E", "entity": "TAG2"}] Notice that two consecutive B tags will end up as + different entities. On word based languages, we might end up splitting words undesirably : Imagine + Microsoft being tagged as [{"word": "Micro", "entity": "ENTERPRISE"}, {"word": "soft", "entity": + "NAME"}]. Look for FIRST, MAX, AVERAGE for ways to mitigate that and disambiguate words (on languages + that support that meaning, which is basically tokens separated by a space). These mitigations will + only work on real words, "New york" might still be tagged with two different entities. + - "first" : (works only on word based models) Will use the `SIMPLE` strategy except that words, cannot + end up with different tags. Words will simply use the tag of the first token of the word when there + is ambiguity. + - "average" : (works only on word based models) Will use the `SIMPLE` strategy except that words, + cannot end up with different tags. scores will be averaged first across tokens, and then the maximum + label is applied. + - "max" : (works only on word based models) Will use the `SIMPLE` strategy except that words, cannot + end up with different tags. Word entity will simply be the token with the maximum score.""", +) +class TokenClassificationPipeline(ChunkPipeline): + """ + Named Entity Recognition pipeline using any `ModelForTokenClassification`. See the [named entity recognition + examples](../task_summary#named-entity-recognition) for more information. + + Example: + + ```python + >>> from transformers import pipeline + + >>> token_classifier = pipeline(model="Jean-Baptiste/camembert-ner", aggregation_strategy="simple") + >>> sentence = "Je m'appelle jean-baptiste et je vis à montréal" + >>> tokens = token_classifier(sentence) + >>> tokens + [{'entity_group': 'PER', 'score': 0.9931, 'word': 'jean-baptiste', 'start': 12, 'end': 26}, {'entity_group': 'LOC', 'score': 0.998, 'word': 'montréal', 'start': 38, 'end': 47}] + + >>> token = tokens[0] + >>> # Start and end provide an easy way to highlight words in the original text. + >>> sentence[token["start"] : token["end"]] + ' jean-baptiste' + + >>> # Some models use the same idea to do part of speech. + >>> syntaxer = pipeline(model="vblagoje/bert-english-uncased-finetuned-pos", aggregation_strategy="simple") + >>> syntaxer("My name is Sarah and I live in London") + [{'entity_group': 'PRON', 'score': 0.999, 'word': 'my', 'start': 0, 'end': 2}, {'entity_group': 'NOUN', 'score': 0.997, 'word': 'name', 'start': 3, 'end': 7}, {'entity_group': 'AUX', 'score': 0.994, 'word': 'is', 'start': 8, 'end': 10}, {'entity_group': 'PROPN', 'score': 0.999, 'word': 'sarah', 'start': 11, 'end': 16}, {'entity_group': 'CCONJ', 'score': 0.999, 'word': 'and', 'start': 17, 'end': 20}, {'entity_group': 'PRON', 'score': 0.999, 'word': 'i', 'start': 21, 'end': 22}, {'entity_group': 'VERB', 'score': 0.998, 'word': 'live', 'start': 23, 'end': 27}, {'entity_group': 'ADP', 'score': 0.999, 'word': 'in', 'start': 28, 'end': 30}, {'entity_group': 'PROPN', 'score': 0.999, 'word': 'london', 'start': 31, 'end': 37}] + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) + + This token recognition pipeline can currently be loaded from [`pipeline`] using the following task identifier: + `"ner"` (for predicting the classes of tokens in a sequence: person, organisation, location or miscellaneous). + + The models that this pipeline can use are models that have been fine-tuned on a token classification task. See the + up-to-date list of available models on + [huggingface.co/models](https://huggingface.co/models?filter=token-classification). + """ + + default_input_names = "sequences" + + _load_processor = False + _load_image_processor = False + _load_feature_extractor = False + _load_tokenizer = True + + def __init__(self, args_parser=TokenClassificationArgumentHandler(), **kwargs): + super().__init__(**kwargs) + + self.check_model_type(MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES) + + self._basic_tokenizer = BasicTokenizer(do_lower_case=False) + self._args_parser = args_parser + + def _sanitize_parameters( + self, + ignore_labels=None, + aggregation_strategy: AggregationStrategy | None = None, + offset_mapping: list[tuple[int, int]] | None = None, + is_split_into_words: bool = False, + stride: int | None = None, + delimiter: str | None = None, + ): + preprocess_params = {} + preprocess_params["is_split_into_words"] = is_split_into_words + + if is_split_into_words: + preprocess_params["delimiter"] = " " if delimiter is None else delimiter + + if offset_mapping is not None: + preprocess_params["offset_mapping"] = offset_mapping + + postprocess_params = {} + if aggregation_strategy is not None: + if isinstance(aggregation_strategy, str): + aggregation_strategy = AggregationStrategy[aggregation_strategy.upper()] + if ( + aggregation_strategy + in {AggregationStrategy.FIRST, AggregationStrategy.MAX, AggregationStrategy.AVERAGE} + and not self.tokenizer.is_fast + ): + raise ValueError( + "Slow tokenizers cannot handle subwords. Please set the `aggregation_strategy` option" + ' to `"simple"` or use a fast tokenizer.' + ) + postprocess_params["aggregation_strategy"] = aggregation_strategy + if ignore_labels is not None: + postprocess_params["ignore_labels"] = ignore_labels + if stride is not None: + if stride >= self.tokenizer.model_max_length: + raise ValueError( + "`stride` must be less than `tokenizer.model_max_length` (or even lower if the tokenizer adds special tokens)" + ) + if aggregation_strategy == AggregationStrategy.NONE: + raise ValueError( + "`stride` was provided to process all the text but `aggregation_strategy=" + f'"{aggregation_strategy}"`, please select another one instead.' + ) + else: + if self.tokenizer.is_fast: + tokenizer_params = { + "return_overflowing_tokens": True, + "padding": True, + "stride": stride, + } + preprocess_params["tokenizer_params"] = tokenizer_params + else: + raise ValueError( + "`stride` was provided to process all the text but you're using a slow tokenizer." + " Please use a fast tokenizer." + ) + return preprocess_params, {}, postprocess_params + + @overload + def __call__(self, inputs: str, **kwargs: Any) -> list[dict[str, str]]: ... + + @overload + def __call__(self, inputs: list[str], **kwargs: Any) -> list[list[dict[str, str]]]: ... + + def __call__(self, inputs: str | list[str], **kwargs: Any) -> list[dict[str, str]] | list[list[dict[str, str]]]: + """ + Classify each token of the text(s) given as inputs. + + Args: + inputs (`str` or `List[str]`): + One or several texts (or one list of texts) for token classification. Can be pre-tokenized when + `is_split_into_words=True`. + + Return: + A list or a list of list of `dict`: Each result comes as a list of dictionaries (one for each token in the + corresponding input, or each entity if this pipeline was instantiated with an aggregation_strategy) with + the following keys: + + - **word** (`str`) -- The token/word classified. This is obtained by decoding the selected tokens. If you + want to have the exact string in the original sentence, use `start` and `end`. + - **score** (`float`) -- The corresponding probability for `entity`. + - **entity** (`str`) -- The entity predicted for that token/word (it is named *entity_group* when + *aggregation_strategy* is not `"none"`. + - **index** (`int`, only present when `aggregation_strategy="none"`) -- The index of the corresponding + token in the sentence. + - **start** (`int`, *optional*) -- The index of the start of the corresponding entity in the sentence. Only + exists if the offsets are available within the tokenizer + - **end** (`int`, *optional*) -- The index of the end of the corresponding entity in the sentence. Only + exists if the offsets are available within the tokenizer + """ + + _inputs, is_split_into_words, offset_mapping, delimiter = self._args_parser(inputs, **kwargs) + kwargs["is_split_into_words"] = is_split_into_words + kwargs["delimiter"] = delimiter + if is_split_into_words and not all(isinstance(input, list) for input in inputs): + return super().__call__([inputs], **kwargs) + if offset_mapping: + kwargs["offset_mapping"] = offset_mapping + + return super().__call__(inputs, **kwargs) + + def preprocess(self, sentence, offset_mapping=None, **preprocess_params): + tokenizer_params = preprocess_params.pop("tokenizer_params", {}) + truncation = self.tokenizer.model_max_length and self.tokenizer.model_max_length > 0 + + word_to_chars_map = None + is_split_into_words = preprocess_params["is_split_into_words"] + if is_split_into_words: + delimiter = preprocess_params["delimiter"] + if not isinstance(sentence, list): + raise ValueError("When `is_split_into_words=True`, `sentence` must be a list of tokens.") + words = sentence + sentence = delimiter.join(words) # Recreate the sentence string for later display and slicing + # This map will allow to convert back word => char indices + word_to_chars_map = [] + delimiter_len = len(delimiter) + char_offset = 0 + for word in words: + word_to_chars_map.append((char_offset, char_offset + len(word))) + char_offset += len(word) + delimiter_len + + # We use `words` as the actual input for the tokenizer + text_to_tokenize = words + tokenizer_params["is_split_into_words"] = True + else: + if not isinstance(sentence, str): + raise ValueError("When `is_split_into_words=False`, `sentence` must be an untokenized string.") + text_to_tokenize = sentence + + inputs = self.tokenizer( + text_to_tokenize, + return_tensors="pt", + truncation=truncation, + return_special_tokens_mask=True, + return_offsets_mapping=self.tokenizer.is_fast, + **tokenizer_params, + ) + + if is_split_into_words and not self.tokenizer.is_fast: + raise ValueError("is_split_into_words=True is only supported with fast tokenizers.") + + inputs.pop("overflow_to_sample_mapping", None) + num_chunks = len(inputs["input_ids"]) + + for i in range(num_chunks): + model_inputs = {k: v[i].unsqueeze(0) for k, v in inputs.items()} + if offset_mapping is not None: + model_inputs["offset_mapping"] = offset_mapping + + model_inputs["sentence"] = sentence if i == 0 else None + model_inputs["is_last"] = i == num_chunks - 1 + if word_to_chars_map is not None: + model_inputs["word_ids"] = inputs.word_ids(i) + model_inputs["word_to_chars_map"] = word_to_chars_map + + yield model_inputs + + def _forward(self, model_inputs): + # Forward + special_tokens_mask = model_inputs.pop("special_tokens_mask") + offset_mapping = model_inputs.pop("offset_mapping", None) + sentence = model_inputs.pop("sentence") + is_last = model_inputs.pop("is_last") + word_ids = model_inputs.pop("word_ids", None) + word_to_chars_map = model_inputs.pop("word_to_chars_map", None) + + output = self.model(**model_inputs) + logits = output["logits"] if isinstance(output, dict) else output[0] + + return { + "logits": logits, + "special_tokens_mask": special_tokens_mask, + "offset_mapping": offset_mapping, + "sentence": sentence, + "is_last": is_last, + "word_ids": word_ids, + "word_to_chars_map": word_to_chars_map, + **model_inputs, + } + + def postprocess(self, all_outputs, aggregation_strategy=AggregationStrategy.NONE, ignore_labels=None): + if ignore_labels is None: + ignore_labels = ["O"] + all_entities = [] + + # Get map from the first output, it's the same for all chunks + word_to_chars_map = all_outputs[0].get("word_to_chars_map") + + for model_outputs in all_outputs: + if model_outputs["logits"][0].dtype in (torch.bfloat16, torch.float16): + logits = model_outputs["logits"][0].to(torch.float32).numpy() + else: + logits = model_outputs["logits"][0].numpy() + + sentence = all_outputs[0]["sentence"] + input_ids = model_outputs["input_ids"][0] + offset_mapping = ( + model_outputs["offset_mapping"][0] if model_outputs["offset_mapping"] is not None else None + ) + special_tokens_mask = model_outputs["special_tokens_mask"][0].numpy() + word_ids = model_outputs.get("word_ids") + + maxes = np.max(logits, axis=-1, keepdims=True) + shifted_exp = np.exp(logits - maxes) + scores = shifted_exp / shifted_exp.sum(axis=-1, keepdims=True) + + pre_entities = self.gather_pre_entities( + sentence, + input_ids, + scores, + offset_mapping, + special_tokens_mask, + aggregation_strategy, + word_ids=word_ids, + word_to_chars_map=word_to_chars_map, + ) + grouped_entities = self.aggregate(pre_entities, aggregation_strategy) + # Filter anything that is in self.ignore_labels + entities = [ + entity + for entity in grouped_entities + if entity.get("entity", None) not in ignore_labels + and entity.get("entity_group", None) not in ignore_labels + ] + all_entities.extend(entities) + num_chunks = len(all_outputs) + if num_chunks > 1: + all_entities = self.aggregate_overlapping_entities(all_entities) + return all_entities + + def aggregate_overlapping_entities(self, entities): + if len(entities) == 0: + return entities + entities = sorted(entities, key=lambda x: x["start"]) + aggregated_entities = [] + previous_entity = entities[0] + for entity in entities: + if previous_entity["start"] <= entity["start"] < previous_entity["end"]: + current_length = entity["end"] - entity["start"] + previous_length = previous_entity["end"] - previous_entity["start"] + if ( + current_length > previous_length + or current_length == previous_length + and entity["score"] > previous_entity["score"] + ): + previous_entity = entity + else: + aggregated_entities.append(previous_entity) + previous_entity = entity + aggregated_entities.append(previous_entity) + return aggregated_entities + + def gather_pre_entities( + self, + sentence: str, + input_ids: np.ndarray, + scores: np.ndarray, + offset_mapping: list[tuple[int, int]] | None, + special_tokens_mask: np.ndarray, + aggregation_strategy: AggregationStrategy, + word_ids: list[int | None] | None = None, + word_to_chars_map: list[tuple[int, int]] | None = None, + ) -> list[dict]: + """Fuse various numpy arrays into dicts with all the information needed for aggregation""" + pre_entities = [] + for idx, token_scores in enumerate(scores): + # Filter special_tokens + if special_tokens_mask[idx]: + continue + + word = self.tokenizer.convert_ids_to_tokens(int(input_ids[idx])) + if offset_mapping is not None: + start_ind, end_ind = offset_mapping[idx] + + # If the input is pre-tokenized, we need to rescale the offsets to the absolute sentence. + if word_ids is not None and word_to_chars_map is not None: + word_index = word_ids[idx] + if word_index is not None: + start_char, _ = word_to_chars_map[word_index] + start_ind += start_char + end_ind += start_char + + if not isinstance(start_ind, int): + start_ind = start_ind.item() + end_ind = end_ind.item() + word_ref = sentence[start_ind:end_ind] + if getattr(self.tokenizer, "_tokenizer", None) and getattr( + self.tokenizer._tokenizer.model, "continuing_subword_prefix", None + ): + # This is a BPE, word aware tokenizer, there is a correct way + # to fuse tokens + is_subword = len(word) != len(word_ref) + else: + # This is a fallback heuristic. This will fail most likely on any kind of text + punctuation mixtures that will be considered "words". Non word aware models cannot do better than this unfortunately. + if aggregation_strategy in { + AggregationStrategy.FIRST, + AggregationStrategy.AVERAGE, + AggregationStrategy.MAX, + }: + warnings.warn( + "Tokenizer does not support real words, using fallback heuristic", + UserWarning, + ) + is_subword = start_ind > 0 and " " not in sentence[start_ind - 1 : start_ind + 1] + + if int(input_ids[idx]) == self.tokenizer.unk_token_id: + word = word_ref + is_subword = False + else: + start_ind = None + end_ind = None + is_subword = False + + pre_entity = { + "word": word, + "scores": token_scores, + "start": start_ind, + "end": end_ind, + "index": idx, + "is_subword": is_subword, + } + pre_entities.append(pre_entity) + return pre_entities + + def aggregate(self, pre_entities: list[dict], aggregation_strategy: AggregationStrategy) -> list[dict]: + if aggregation_strategy in {AggregationStrategy.NONE, AggregationStrategy.SIMPLE}: + entities = [] + for pre_entity in pre_entities: + entity_idx = pre_entity["scores"].argmax() + score = pre_entity["scores"][entity_idx] + entity = { + "entity": self.model.config.id2label[entity_idx], + "score": score, + "index": pre_entity["index"], + "word": pre_entity["word"], + "start": pre_entity["start"], + "end": pre_entity["end"], + } + entities.append(entity) + else: + entities = self.aggregate_words(pre_entities, aggregation_strategy) + + if aggregation_strategy == AggregationStrategy.NONE: + return entities + return self.group_entities(entities) + + def aggregate_word(self, entities: list[dict], aggregation_strategy: AggregationStrategy) -> dict: + word = self.tokenizer.convert_tokens_to_string([entity["word"] for entity in entities]) + if aggregation_strategy == AggregationStrategy.FIRST: + scores = entities[0]["scores"] + idx = scores.argmax() + score = scores[idx] + entity = self.model.config.id2label[idx] + elif aggregation_strategy == AggregationStrategy.MAX: + max_entity = max(entities, key=lambda entity: entity["scores"].max()) + scores = max_entity["scores"] + idx = scores.argmax() + score = scores[idx] + entity = self.model.config.id2label[idx] + elif aggregation_strategy == AggregationStrategy.AVERAGE: + scores = np.stack([entity["scores"] for entity in entities]) + average_scores = np.nanmean(scores, axis=0) + entity_idx = average_scores.argmax() + entity = self.model.config.id2label[entity_idx] + score = average_scores[entity_idx] + else: + raise ValueError("Invalid aggregation_strategy") + new_entity = { + "entity": entity, + "score": score, + "word": word, + "start": entities[0]["start"], + "end": entities[-1]["end"], + } + return new_entity + + def aggregate_words(self, entities: list[dict], aggregation_strategy: AggregationStrategy) -> list[dict]: + """ + Override tokens from a given word that disagree to force agreement on word boundaries. + + Example: micro|soft| com|pany| B-ENT I-NAME I-ENT I-ENT will be rewritten with first strategy as microsoft| + company| B-ENT I-ENT + """ + if aggregation_strategy in { + AggregationStrategy.NONE, + AggregationStrategy.SIMPLE, + }: + raise ValueError("NONE and SIMPLE strategies are invalid for word aggregation") + + word_entities = [] + word_group = None + for entity in entities: + if word_group is None: + word_group = [entity] + elif entity["is_subword"]: + word_group.append(entity) + else: + word_entities.append(self.aggregate_word(word_group, aggregation_strategy)) + word_group = [entity] + # Last item + if word_group is not None: + word_entities.append(self.aggregate_word(word_group, aggregation_strategy)) + return word_entities + + def group_sub_entities(self, entities: list[dict]) -> dict: + """ + Group together the adjacent tokens with the same entity predicted. + + Args: + entities (`dict`): The entities predicted by the pipeline. + """ + # Get the first entity in the entity group + entity = entities[0]["entity"].split("-", 1)[-1] + scores = np.nanmean([entity["score"] for entity in entities]) + tokens = [entity["word"] for entity in entities] + + entity_group = { + "entity_group": entity, + "score": np.mean(scores), + "word": self.tokenizer.convert_tokens_to_string(tokens), + "start": entities[0]["start"], + "end": entities[-1]["end"], + } + return entity_group + + def get_tag(self, entity_name: str) -> tuple[str, str]: + if entity_name.startswith("B-"): + bi = "B" + tag = entity_name[2:] + elif entity_name.startswith("I-"): + bi = "I" + tag = entity_name[2:] + else: + # It's not in B-, I- format + # Default to I- for continuation. + bi = "I" + tag = entity_name + return bi, tag + + def group_entities(self, entities: list[dict]) -> list[dict]: + """ + Find and group together the adjacent tokens with the same entity predicted. + + Args: + entities (`dict`): The entities predicted by the pipeline. + """ + + entity_groups = [] + entity_group_disagg = [] + + for entity in entities: + if not entity_group_disagg: + entity_group_disagg.append(entity) + continue + + # If the current entity is similar and adjacent to the previous entity, + # append it to the disaggregated entity group + # The split is meant to account for the "B" and "I" prefixes + # Shouldn't merge if both entities are B-type + bi, tag = self.get_tag(entity["entity"]) + last_bi, last_tag = self.get_tag(entity_group_disagg[-1]["entity"]) + + if tag == last_tag and bi != "B": + # Modify subword type to be previous_type + entity_group_disagg.append(entity) + else: + # If the current entity is different from the previous entity + # aggregate the disaggregated entity group + entity_groups.append(self.group_sub_entities(entity_group_disagg)) + entity_group_disagg = [entity] + if entity_group_disagg: + # it's the last entity, add it to the entity groups + entity_groups.append(self.group_sub_entities(entity_group_disagg)) + + return entity_groups + + +NerPipeline = TokenClassificationPipeline diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/video_classification.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/video_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..4e2ff77cbe625707f1860064dc08cf22941bceeb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/video_classification.py @@ -0,0 +1,183 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# 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. +from io import BytesIO +from typing import Any, overload + +import httpx + +from ..utils import ( + add_end_docstrings, + is_av_available, + is_torch_available, + logging, + requires_backends, +) +from .base import Pipeline, build_pipeline_init_args + + +if is_av_available(): + import av + import numpy as np + + +if is_torch_available(): + from ..models.auto.modeling_auto import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES + +logger = logging.get_logger(__name__) + + +@add_end_docstrings(build_pipeline_init_args(has_image_processor=True)) +class VideoClassificationPipeline(Pipeline): + """ + Video classification pipeline using any `AutoModelForVideoClassification`. This pipeline predicts the class of a + video. + + This video classification pipeline can currently be loaded from [`pipeline`] using the following task identifier: + `"video-classification"`. + + See the list of available models on + [huggingface.co/models](https://huggingface.co/models?filter=video-classification). + """ + + _load_processor = False + _load_image_processor = True + _load_feature_extractor = False + _load_tokenizer = False + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + requires_backends(self, "av") + self.check_model_type(MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES) + + def _sanitize_parameters(self, top_k=None, num_frames=None, frame_sampling_rate=None, function_to_apply=None): + preprocess_params = {} + if frame_sampling_rate is not None: + preprocess_params["frame_sampling_rate"] = frame_sampling_rate + if num_frames is not None: + preprocess_params["num_frames"] = num_frames + + postprocess_params = {} + if top_k is not None: + postprocess_params["top_k"] = top_k + if function_to_apply is not None: + if function_to_apply not in ["softmax", "sigmoid", "none"]: + raise ValueError( + f"Invalid value for `function_to_apply`: {function_to_apply}. " + "Valid options are ['softmax', 'sigmoid', 'none']" + ) + postprocess_params["function_to_apply"] = function_to_apply + else: + postprocess_params["function_to_apply"] = "softmax" + return preprocess_params, {}, postprocess_params + + @overload + def __call__(self, inputs: str, **kwargs: Any) -> list[dict[str, Any]]: ... + + @overload + def __call__(self, inputs: list[str], **kwargs: Any) -> list[list[dict[str, Any]]]: ... + + def __call__(self, inputs: str | list[str] | None, **kwargs): + """ + Assign labels to the video(s) passed as inputs. + + Args: + inputs (`str`, `list[str]`): + The pipeline handles three types of videos: + + - A string containing a http link pointing to a video + - A string containing a local path to a video + + The pipeline accepts either a single video or a batch of videos, which must then be passed as a string. + Videos in a batch must all be in the same format: all as http links or all as local paths. + top_k (`int`, *optional*, defaults to 5): + The number of top labels that will be returned by the pipeline. If the provided number is higher than + the number of labels available in the model configuration, it will default to the number of labels. + num_frames (`int`, *optional*, defaults to `self.model.config.num_frames`): + The number of frames sampled from the video to run the classification on. If not provided, will default + to the number of frames specified in the model configuration. + frame_sampling_rate (`int`, *optional*, defaults to 1): + The sampling rate used to select frames from the video. If not provided, will default to 1, i.e. every + frame will be used. + function_to_apply(`str`, *optional*, defaults to "softmax"): + The function to apply to the model output. By default, the pipeline will apply the softmax function to + the output of the model. Valid options: ["softmax", "sigmoid", "none"]. Note that passing Python's + built-in `None` will default to "softmax", so you need to pass the string "none" to disable any + post-processing. + + Return: + A list of dictionaries or a list of list of dictionaries containing result. If the input is a single video, + will return a list of `top_k` dictionaries, if the input is a list of several videos, will return a list of list of + `top_k` dictionaries corresponding to the videos. + + The dictionaries contain the following keys: + + - **label** (`str`) -- The label identified by the model. + - **score** (`int`) -- The score attributed by the model for that label. + """ + if inputs is None: + raise ValueError("Cannot call the video-classification pipeline without an inputs argument!") + return super().__call__(inputs, **kwargs) + + def preprocess(self, video, num_frames=None, frame_sampling_rate=1): + if num_frames is None: + num_frames = self.model.config.num_frames + + if video.startswith("http://") or video.startswith("https://"): + video = BytesIO(httpx.get(video, follow_redirects=True).content) + + container = av.open(video) + + start_idx = 0 + end_idx = num_frames * frame_sampling_rate - 1 + indices = np.linspace(start_idx, end_idx, num=num_frames, dtype=np.int64) + + video = read_video_pyav(container, indices) + video = list(video) + + model_inputs = self.image_processor(video, return_tensors="pt") + model_inputs = model_inputs.to(self.dtype) + return model_inputs + + def _forward(self, model_inputs): + model_outputs = self.model(**model_inputs) + return model_outputs + + def postprocess(self, model_outputs, top_k=5, function_to_apply="softmax"): + if top_k > self.model.config.num_labels: + top_k = self.model.config.num_labels + + if function_to_apply == "softmax": + probs = model_outputs.logits[0].softmax(-1) + elif function_to_apply == "sigmoid": + probs = model_outputs.logits[0].sigmoid() + else: + probs = model_outputs.logits[0] + scores, ids = probs.topk(top_k) + + scores = scores.tolist() + ids = ids.tolist() + return [{"score": score, "label": self.model.config.id2label[_id]} for score, _id in zip(scores, ids)] + + +def read_video_pyav(container, indices): + frames = [] + container.seek(0) + start_index = indices[0] + end_index = indices[-1] + for i, frame in enumerate(container.decode(video=0)): + if i > end_index: + break + if i >= start_index and i in indices: + frames.append(frame) + return np.stack([x.to_ndarray(format="rgb24") for x in frames]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/zero_shot_audio_classification.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/zero_shot_audio_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..03c1a8d1c1337bce8897451d72337ae9cfac2dc2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/zero_shot_audio_classification.py @@ -0,0 +1,160 @@ +# Copyright 2023 The HuggingFace Inc. team. +# +# 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. +from collections import UserDict +from typing import Any + +import httpx +import numpy as np + +from ..utils import ( + add_end_docstrings, + logging, +) +from .audio_classification import ffmpeg_read +from .base import Pipeline, build_pipeline_init_args + + +logger = logging.get_logger(__name__) + + +@add_end_docstrings(build_pipeline_init_args(has_feature_extractor=True, has_tokenizer=True)) +class ZeroShotAudioClassificationPipeline(Pipeline): + """ + Zero shot audio classification pipeline using `ClapModel`. This pipeline predicts the class of an audio when you + provide an audio and a set of `candidate_labels`. + + + + The default `hypothesis_template` is : `"This is a sound of {}."`. Make sure you update it for your usage. + + + + Example: + ```python + >>> from transformers import pipeline + >>> from datasets import load_dataset + + >>> dataset = load_dataset("ashraq/esc50") + >>> audio = next(iter(dataset["train"]["audio"]))["array"] + >>> classifier = pipeline(task="zero-shot-audio-classification", model="laion/clap-htsat-unfused") + >>> classifier(audio, candidate_labels=["Sound of a dog", "Sound of vacuum cleaner"]) + [{'score': 0.9996, 'label': 'Sound of a dog'}, {'score': 0.0004, 'label': 'Sound of vacuum cleaner'}] + ``` + + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) This audio + classification pipeline can currently be loaded from [`pipeline`] using the following task identifier: + `"zero-shot-audio-classification"`. See the list of available models on + [huggingface.co/models](https://huggingface.co/models?filter=zero-shot-audio-classification). + """ + + _load_processor = False + _load_image_processor = False + _load_feature_extractor = True + _load_tokenizer = True + + def __init__(self, **kwargs): + super().__init__(**kwargs) + + def __call__(self, audios: np.ndarray | bytes | str | dict, **kwargs: Any) -> list[dict[str, Any]]: + """ + Assign labels to the audio(s) passed as inputs. + + Args: + audios (`str`, `list[str]`, `np.array` or `list[np.array]`): + The pipeline handles three types of inputs: + - A string containing a http link pointing to an audio + - A string containing a local path to an audio + - An audio loaded in numpy + candidate_labels (`list[str]`): + The candidate labels for this audio. They will be formatted using *hypothesis_template*. + hypothesis_template (`str`, *optional*, defaults to `"This is a sound of {}"`): + The format used in conjunction with *candidate_labels* to attempt the audio classification by + replacing the placeholder with the candidate_labels. Pass "{}" if *candidate_labels* are + already formatted. + Return: + A list of dictionaries containing one entry per proposed label. Each dictionary contains the + following keys: + - **label** (`str`) -- One of the suggested *candidate_labels*. + - **score** (`float`) -- The score attributed by the model to that label. It is a value between + 0 and 1, computed as the `softmax` of `logits_per_audio`. + """ + return super().__call__(audios, **kwargs) + + def _sanitize_parameters(self, **kwargs): + preprocess_params = {} + if "candidate_labels" in kwargs: + preprocess_params["candidate_labels"] = kwargs["candidate_labels"] + if "hypothesis_template" in kwargs: + preprocess_params["hypothesis_template"] = kwargs["hypothesis_template"] + + return preprocess_params, {}, {} + + def preprocess(self, audio, candidate_labels=None, hypothesis_template="This is a sound of {}."): + if isinstance(audio, str): + if audio.startswith("http://") or audio.startswith("https://"): + # We need to actually check for a real protocol, otherwise it's impossible to use a local file + # like http_huggingface_co.png + audio = httpx.get(audio, follow_redirects=True).content + else: + with open(audio, "rb") as f: + audio = f.read() + + if isinstance(audio, bytes): + audio = ffmpeg_read(audio, self.feature_extractor.sampling_rate) + + if not isinstance(audio, np.ndarray): + raise TypeError("We expect a numpy ndarray as input") + if len(audio.shape) != 1: + raise ValueError("We expect a single channel audio input for ZeroShotAudioClassificationPipeline") + + inputs = self.feature_extractor( + [audio], sampling_rate=self.feature_extractor.sampling_rate, return_tensors="pt" + ) + inputs = inputs.to(self.dtype) + inputs["candidate_labels"] = candidate_labels + sequences = [hypothesis_template.format(x) for x in candidate_labels] + text_inputs = self.tokenizer(sequences, return_tensors="pt", padding=True) + inputs["text_inputs"] = [text_inputs] + return inputs + + def _forward(self, model_inputs): + candidate_labels = model_inputs.pop("candidate_labels") + text_inputs = model_inputs.pop("text_inputs") + if isinstance(text_inputs[0], UserDict): + text_inputs = text_inputs[0] + else: + # Batching case. + text_inputs = text_inputs[0][0] + + outputs = self.model(**text_inputs, **model_inputs) + + model_outputs = { + "candidate_labels": candidate_labels, + "logits": outputs.logits_per_audio, + } + return model_outputs + + def postprocess(self, model_outputs): + candidate_labels = model_outputs.pop("candidate_labels") + logits = model_outputs["logits"][0] + + probs = logits.softmax(dim=0) + scores = probs.tolist() + + result = [ + {"score": score, "label": candidate_label} + for score, candidate_label in sorted(zip(scores, candidate_labels), key=lambda x: -x[0]) + ] + return result diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/zero_shot_classification.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/zero_shot_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..d88772310de8606235e3e7384476b12723b2c7cd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/zero_shot_classification.py @@ -0,0 +1,261 @@ +import inspect + +import numpy as np + +from ..tokenization_python import TruncationStrategy +from ..utils import add_end_docstrings, logging +from .base import ArgumentHandler, ChunkPipeline, build_pipeline_init_args + + +logger = logging.get_logger(__name__) + + +class ZeroShotClassificationArgumentHandler(ArgumentHandler): + """ + Handles arguments for zero-shot for text classification by turning each possible label into an NLI + premise/hypothesis pair. + """ + + def _parse_labels(self, labels): + if isinstance(labels, str): + labels = [label.strip() for label in labels.split(",") if label.strip()] + return labels + + def __call__(self, sequences, labels, hypothesis_template): + if len(labels) == 0 or len(sequences) == 0: + raise ValueError("You must include at least one label and at least one sequence.") + if hypothesis_template.format(labels[0]) == hypothesis_template: + raise ValueError( + f'The provided hypothesis_template "{hypothesis_template}" was not able to be formatted with the target labels. ' + "Make sure the passed template includes formatting syntax such as {} where the label should go." + ) + + if isinstance(sequences, str): + sequences = [sequences] + + sequence_pairs = [] + for sequence in sequences: + sequence_pairs.extend([[sequence, hypothesis_template.format(label)] for label in labels]) + + return sequence_pairs, sequences + + +@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True)) +class ZeroShotClassificationPipeline(ChunkPipeline): + """ + NLI-based zero-shot classification pipeline using a `ModelForSequenceClassification` trained on NLI (natural + language inference) tasks. Equivalent of `text-classification` pipelines, but these models don't require a + hardcoded number of potential classes, they can be chosen at runtime. It usually means it's slower but it is + **much** more flexible. + + Any combination of sequences and labels can be passed and each combination will be posed as a premise/hypothesis + pair and passed to the pretrained model. Then, the logit for *entailment* is taken as the logit for the candidate + label being valid. Any NLI model can be used, but the id of the *entailment* label must be included in the model + config's :attr:*~transformers.PreTrainedConfig.label2id*. + + Example: + + ```python + >>> from transformers import pipeline + + >>> oracle = pipeline(model="facebook/bart-large-mnli") + >>> oracle( + ... "I have a problem with my iphone that needs to be resolved asap!!", + ... candidate_labels=["urgent", "not urgent", "phone", "tablet", "computer"], + ... ) + {'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['urgent', 'phone', 'computer', 'not urgent', 'tablet'], 'scores': [0.504, 0.479, 0.013, 0.003, 0.002]} + + >>> oracle( + ... "I have a problem with my iphone that needs to be resolved asap!!", + ... candidate_labels=["english", "german"], + ... ) + {'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['english', 'german'], 'scores': [0.814, 0.186]} + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) + + This NLI pipeline can currently be loaded from [`pipeline`] using the following task identifier: + `"zero-shot-classification"`. + + The models that this pipeline can use are models that have been fine-tuned on an NLI task. See the up-to-date list + of available models on [huggingface.co/models](https://huggingface.co/models?search=nli). + """ + + _load_processor = False + _load_image_processor = False + _load_feature_extractor = False + _load_tokenizer = True + + def __init__(self, args_parser=ZeroShotClassificationArgumentHandler(), **kwargs): + self._args_parser = args_parser + super().__init__(**kwargs) + if self.entailment_id == -1: + logger.warning( + "Failed to determine 'entailment' label id from the label2id mapping in the model config. Setting to " + "-1. Define a descriptive label2id mapping in the model config to ensure correct outputs." + ) + + @property + def entailment_id(self): + for label, ind in self.model.config.label2id.items(): + if label.lower().startswith("entail"): + return ind + return -1 + + def _parse_and_tokenize( + self, sequence_pairs, padding=True, add_special_tokens=True, truncation=TruncationStrategy.ONLY_FIRST, **kwargs + ): + """ + Parse arguments and tokenize only_first so that hypothesis (label) is not truncated + """ + return_tensors = "pt" + if self.tokenizer.pad_token is None: + # Override for tokenizers not supporting padding + logger.error( + "Tokenizer was not supporting padding necessary for zero-shot, attempting to use " + " `pad_token=eos_token`" + ) + self.tokenizer.pad_token = self.tokenizer.eos_token + try: + inputs = self.tokenizer( + sequence_pairs, + add_special_tokens=add_special_tokens, + return_tensors=return_tensors, + padding=padding, + truncation=truncation, + ) + except Exception as e: + if "too short" in str(e): + # tokenizers might yell that we want to truncate + # to a value that is not even reached by the input. + # In that case we don't want to truncate. + # It seems there's not a really better way to catch that + # exception. + + inputs = self.tokenizer( + sequence_pairs, + add_special_tokens=add_special_tokens, + return_tensors=return_tensors, + padding=padding, + truncation=TruncationStrategy.DO_NOT_TRUNCATE, + ) + else: + raise e + + return inputs + + def _sanitize_parameters(self, **kwargs): + preprocess_params = {} + if "candidate_labels" in kwargs: + preprocess_params["candidate_labels"] = self._args_parser._parse_labels(kwargs["candidate_labels"]) + if "hypothesis_template" in kwargs: + preprocess_params["hypothesis_template"] = kwargs["hypothesis_template"] + + postprocess_params = {} + if "multi_label" in kwargs: + postprocess_params["multi_label"] = kwargs["multi_label"] + return preprocess_params, {}, postprocess_params + + def __call__( + self, + sequences: str | list[str], + *args, + **kwargs, + ): + """ + Classify the sequence(s) given as inputs. See the [`ZeroShotClassificationPipeline`] documentation for more + information. + + Args: + sequences (`str` or `list[str]`): + The sequence(s) to classify, will be truncated if the model input is too large. + candidate_labels (`str` or `list[str]`): + The set of possible class labels to classify each sequence into. Can be a single label, a string of + comma-separated labels, or a list of labels. + hypothesis_template (`str`, *optional*, defaults to `"This example is {}."`): + The template used to turn each label into an NLI-style hypothesis. This template must include a {} or + similar syntax for the candidate label to be inserted into the template. For example, the default + template is `"This example is {}."` With the candidate label `"sports"`, this would be fed into the + model like `" sequence to classify This example is sports . "`. The default template + works well in many cases, but it may be worthwhile to experiment with different templates depending on + the task setting. + multi_label (`bool`, *optional*, defaults to `False`): + Whether or not multiple candidate labels can be true. If `False`, the scores are normalized such that + the sum of the label likelihoods for each sequence is 1. If `True`, the labels are considered + independent and probabilities are normalized for each candidate by doing a softmax of the entailment + score vs. the contradiction score. + + Return: + A `dict` or a list of `dict`: Each result comes as a dictionary with the following keys: + + - **sequence** (`str`) -- The sequence for which this is the output. + - **labels** (`list[str]`) -- The labels sorted by order of likelihood. + - **scores** (`list[float]`) -- The probabilities for each of the labels. + """ + if len(args) == 0: + pass + elif len(args) == 1 and "candidate_labels" not in kwargs: + kwargs["candidate_labels"] = args[0] + else: + raise ValueError(f"Unable to understand extra arguments {args}") + + return super().__call__(sequences, **kwargs) + + def preprocess(self, inputs, candidate_labels=None, hypothesis_template="This example is {}."): + sequence_pairs, sequences = self._args_parser(inputs, candidate_labels, hypothesis_template) + + for i, (candidate_label, sequence_pair) in enumerate(zip(candidate_labels, sequence_pairs)): + model_input = self._parse_and_tokenize([sequence_pair]) + + yield { + "candidate_label": candidate_label, + "sequence": sequences[0], + "is_last": i == len(candidate_labels) - 1, + **model_input, + } + + def _forward(self, inputs): + candidate_label = inputs["candidate_label"] + sequence = inputs["sequence"] + model_inputs = {k: inputs[k] for k in self.tokenizer.model_input_names} + # `XXXForSequenceClassification` models should not use `use_cache=True` even if it's supported + model_forward = self.model.forward + if "use_cache" in inspect.signature(model_forward).parameters: + model_inputs["use_cache"] = False + outputs = self.model(**model_inputs) + + model_outputs = { + "candidate_label": candidate_label, + "sequence": sequence, + "is_last": inputs["is_last"], + **outputs, + } + return model_outputs + + def postprocess(self, model_outputs, multi_label=False): + candidate_labels = [outputs["candidate_label"] for outputs in model_outputs] + sequences = [outputs["sequence"] for outputs in model_outputs] + logits = np.concatenate([output["logits"].float().numpy() for output in model_outputs]) + N = logits.shape[0] + n = len(candidate_labels) + num_sequences = N // n + reshaped_outputs = logits.reshape((num_sequences, n, -1)) + + if multi_label or len(candidate_labels) == 1: + # softmax over the entailment vs. contradiction dim for each label independently + entailment_id = self.entailment_id + contradiction_id = -1 if entailment_id == 0 else 0 + entail_contr_logits = reshaped_outputs[..., [contradiction_id, entailment_id]] + scores = np.exp(entail_contr_logits) / np.exp(entail_contr_logits).sum(-1, keepdims=True) + scores = scores[..., 1] + else: + # softmax the "entailment" logits over all candidate labels + entail_logits = reshaped_outputs[..., self.entailment_id] + scores = np.exp(entail_logits) / np.exp(entail_logits).sum(-1, keepdims=True) + + top_inds = list(reversed(scores[0].argsort())) + return { + "sequence": sequences[0], + "labels": [candidate_labels[i] for i in top_inds], + "scores": scores[0, top_inds].tolist(), + } diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/zero_shot_image_classification.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/zero_shot_image_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..d129c5836538904b2259e14e23e25267f529165c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/zero_shot_image_classification.py @@ -0,0 +1,195 @@ +from collections import UserDict +from typing import Any, Union, overload + +from ..utils import ( + add_end_docstrings, + is_torch_available, + is_vision_available, + logging, + requires_backends, +) +from .base import Pipeline, build_pipeline_init_args + + +if is_vision_available(): + from PIL import Image + + from ..image_utils import load_image + +if is_torch_available(): + import torch + + from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES + + +logger = logging.get_logger(__name__) + + +@add_end_docstrings(build_pipeline_init_args(has_image_processor=True)) +class ZeroShotImageClassificationPipeline(Pipeline): + """ + Zero shot image classification pipeline using `CLIPModel`. This pipeline predicts the class of an image when you + provide an image and a set of `candidate_labels`. + + Example: + + ```python + >>> from transformers import pipeline + + >>> classifier = pipeline(model="google/siglip-so400m-patch14-384") + >>> classifier( + ... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", + ... candidate_labels=["animals", "humans", "landscape"], + ... ) + [{'score': 0.965, 'label': 'animals'}, {'score': 0.03, 'label': 'humans'}, {'score': 0.005, 'label': 'landscape'}] + + >>> classifier( + ... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", + ... candidate_labels=["black and white", "photorealist", "painting"], + ... ) + [{'score': 0.996, 'label': 'black and white'}, {'score': 0.003, 'label': 'photorealist'}, {'score': 0.0, 'label': 'painting'}] + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) + + This image classification pipeline can currently be loaded from [`pipeline`] using the following task identifier: + `"zero-shot-image-classification"`. + + See the list of available models on + [huggingface.co/models](https://huggingface.co/models?filter=zero-shot-image-classification). + """ + + _load_processor = False + _load_image_processor = True + _load_feature_extractor = False + _load_tokenizer = True + + def __init__(self, **kwargs): + super().__init__(**kwargs) + + requires_backends(self, "vision") + self.check_model_type(MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES) + + @overload + def __call__( + self, image: Union[str, "Image.Image"], candidate_labels: list[str], **kwargs: Any + ) -> list[dict[str, Any]]: ... + + @overload + def __call__( + self, image: list[str] | list["Image.Image"], candidate_labels: list[str], **kwargs: Any + ) -> list[list[dict[str, Any]]]: ... + + def __call__( + self, + image: Union[str, list[str], "Image.Image", list["Image.Image"]], + candidate_labels: list[str], + **kwargs: Any, + ) -> list[dict[str, Any]] | list[list[dict[str, Any]]]: + """ + Assign labels to the image(s) passed as inputs. + + Args: + image (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`): + The pipeline handles three types of images: + + - A string containing a http link pointing to an image + - A string containing a local path to an image + - An image loaded in PIL directly + + candidate_labels (`list[str]`): + The candidate labels for this image. They will be formatted using *hypothesis_template*. + + hypothesis_template (`str`, *optional*, defaults to `"This is a photo of {}"`): + The format used in conjunction with *candidate_labels* to attempt the image classification by + replacing the placeholder with the candidate_labels. Pass "{}" if *candidate_labels* are + already formatted. + + timeout (`float`, *optional*, defaults to None): + The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and + the call may block forever. + + Return: + A list of dictionaries containing one entry per proposed label. Each dictionary contains the + following keys: + - **label** (`str`) -- One of the suggested *candidate_labels*. + - **score** (`float`) -- The score attributed by the model to that label. It is a value between + 0 and 1, computed as the `softmax` of `logits_per_image`. + """ + # After deprecation of this is completed, remove the default `None` value for `image` + if "images" in kwargs: + image = kwargs.pop("images") + if image is None: + raise ValueError("Cannot call the zero-shot-image-classification pipeline without an images argument!") + return super().__call__(image, candidate_labels=candidate_labels, **kwargs) + + def _sanitize_parameters(self, tokenizer_kwargs=None, **kwargs): + preprocess_params = {} + if "candidate_labels" in kwargs: + preprocess_params["candidate_labels"] = kwargs["candidate_labels"] + if "timeout" in kwargs: + preprocess_params["timeout"] = kwargs["timeout"] + if "hypothesis_template" in kwargs: + preprocess_params["hypothesis_template"] = kwargs["hypothesis_template"] + + return preprocess_params, {}, {} + + def preprocess( + self, + image, + candidate_labels=None, + hypothesis_template="This is a photo of {}.", + timeout=None, + tokenizer_kwargs=None, + ): + if tokenizer_kwargs is None: + tokenizer_kwargs = {} + image = load_image(image, timeout=timeout) + inputs = self.image_processor(images=[image], return_tensors="pt") + inputs = inputs.to(self.dtype) + inputs["candidate_labels"] = candidate_labels + sequences = [hypothesis_template.format(x) for x in candidate_labels] + tokenizer_default_kwargs = {"padding": True} + if "siglip" in self.model.config.model_type: + tokenizer_default_kwargs.update(padding="max_length", max_length=64, truncation=True) + tokenizer_default_kwargs.update(tokenizer_kwargs) + text_inputs = self.tokenizer(sequences, return_tensors="pt", **tokenizer_default_kwargs) + inputs["text_inputs"] = [text_inputs] + return inputs + + def _forward(self, model_inputs): + candidate_labels = model_inputs.pop("candidate_labels") + text_inputs = model_inputs.pop("text_inputs") + if isinstance(text_inputs[0], UserDict): + text_inputs = text_inputs[0] + else: + # Batching case. + text_inputs = text_inputs[0][0] + + outputs = self.model(**text_inputs, **model_inputs) + + model_outputs = { + "candidate_labels": candidate_labels, + "logits": outputs.logits_per_image, + } + return model_outputs + + def postprocess(self, model_outputs): + candidate_labels = model_outputs.pop("candidate_labels") + logits = model_outputs["logits"][0] + if "siglip" in self.model.config.model_type: + probs = torch.sigmoid(logits).squeeze(-1) + scores = probs.tolist() + if not isinstance(scores, list): + scores = [scores] + else: + probs = logits.softmax(dim=-1).squeeze(-1) + scores = probs.tolist() + if not isinstance(scores, list): + scores = [scores] + + result = [ + {"score": score, "label": candidate_label} + for score, candidate_label in sorted(zip(scores, candidate_labels), key=lambda x: -x[0]) + ] + return result diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/zero_shot_object_detection.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/zero_shot_object_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..7f353afd7499e100353bd450293fd174183a0e13 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/zero_shot_object_detection.py @@ -0,0 +1,242 @@ +from typing import Any, Union, overload + +from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends +from .base import ChunkPipeline, build_pipeline_init_args + + +if is_vision_available(): + from PIL import Image + + from ..image_utils import load_image, valid_images + +if is_torch_available(): + import torch + + from transformers.modeling_outputs import BaseModelOutput + + from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES + +logger = logging.get_logger(__name__) + + +@add_end_docstrings(build_pipeline_init_args(has_image_processor=True)) +class ZeroShotObjectDetectionPipeline(ChunkPipeline): + """ + Zero shot object detection pipeline using `OwlViTForObjectDetection`. This pipeline predicts bounding boxes of + objects when you provide an image and a set of `candidate_labels`. + + Example: + + ```python + >>> from transformers import pipeline + + >>> detector = pipeline(model="google/owlvit-base-patch32", task="zero-shot-object-detection") + >>> detector( + ... "http://images.cocodataset.org/val2017/000000039769.jpg", + ... candidate_labels=["cat", "couch"], + ... ) + [{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.254, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}] + + >>> detector( + ... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", + ... candidate_labels=["head", "bird"], + ... ) + [{'score': 0.119, 'label': 'bird', 'box': {'xmin': 71, 'ymin': 170, 'xmax': 410, 'ymax': 508}}] + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) + + This object detection pipeline can currently be loaded from [`pipeline`] using the following task identifier: + `"zero-shot-object-detection"`. + + See the list of available models on + [huggingface.co/models](https://huggingface.co/models?filter=zero-shot-object-detection). + """ + + _load_processor = False + _load_image_processor = True + _load_feature_extractor = False + _load_tokenizer = True + + def __init__(self, **kwargs): + super().__init__(**kwargs) + + requires_backends(self, "vision") + self.check_model_type(MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES) + + @overload + def __call__( + self, image: Union[str, "Image.Image"], candidate_labels: str | list[str], **kwargs: Any + ) -> list[dict[str, Any]]: ... + + @overload + def __call__(self, image: list[dict[str, Any]], **kwargs: Any) -> list[list[dict[str, Any]]]: ... + + def __call__( + self, + image: Union[str, "Image.Image", list[dict[str, Any]]], + candidate_labels: str | list[str] | None = None, + **kwargs: Any, + ) -> list[dict[str, Any]] | list[list[dict[str, Any]]]: + """ + Detect objects (bounding boxes & classes) in the image(s) passed as inputs. + + Args: + image (`str`, `PIL.Image` or `list[dict[str, Any]]`): + The pipeline handles three types of images: + + - A string containing an http url pointing to an image + - A string containing a local path to an image + - An image loaded in PIL directly + + You can use this parameter to send directly a list of images, or a dataset or a generator like so: + + ```python + >>> from transformers import pipeline + + >>> detector = pipeline(model="google/owlvit-base-patch32", task="zero-shot-object-detection") + >>> detector( + ... [ + ... { + ... "image": "http://images.cocodataset.org/val2017/000000039769.jpg", + ... "candidate_labels": ["cat", "couch"], + ... }, + ... { + ... "image": "http://images.cocodataset.org/val2017/000000039769.jpg", + ... "candidate_labels": ["cat", "couch"], + ... }, + ... ] + ... ) + [[{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.25, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}], [{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.254, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}]] + ``` + + + candidate_labels (`str` or `list[str]` or `list[list[str]]`): + What the model should recognize in the image. + + threshold (`float`, *optional*, defaults to 0.1): + The probability necessary to make a prediction. + + top_k (`int`, *optional*, defaults to None): + The number of top predictions that will be returned by the pipeline. If the provided number is `None` + or higher than the number of predictions available, it will default to the number of predictions. + + timeout (`float`, *optional*, defaults to None): + The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and + the call may block forever. + + + Return: + A list of lists containing prediction results, one list per input image. Each list contains dictionaries + with the following keys: + + - **label** (`str`) -- Text query corresponding to the found object. + - **score** (`float`) -- Score corresponding to the object (between 0 and 1). + - **box** (`dict[str,int]`) -- Bounding box of the detected object in image's original size. It is a + dictionary with `x_min`, `x_max`, `y_min`, `y_max` keys. + """ + if "text_queries" in kwargs: + candidate_labels = kwargs.pop("text_queries") + + if isinstance(image, (str, Image.Image)): + inputs = {"image": image, "candidate_labels": candidate_labels} + elif isinstance(image, (list, tuple)) and valid_images(image): + return list( + super().__call__( + ({"image": img, "candidate_labels": labels} for img, labels in zip(image, candidate_labels)), + **kwargs, + ) + ) + else: + """ + Supports the following format + - {"image": image, "candidate_labels": candidate_labels} + - [{"image": image, "candidate_labels": candidate_labels}] + - Generator and datasets + This is a common pattern in other multimodal pipelines, so we support it here as well. + """ + inputs = image + + results = super().__call__(inputs, **kwargs) + return results + + def _sanitize_parameters(self, **kwargs): + preprocess_params = {} + if "timeout" in kwargs: + preprocess_params["timeout"] = kwargs["timeout"] + postprocess_params = {} + if "threshold" in kwargs: + postprocess_params["threshold"] = kwargs["threshold"] + if "top_k" in kwargs: + postprocess_params["top_k"] = kwargs["top_k"] + return preprocess_params, {}, postprocess_params + + def preprocess(self, inputs, timeout=None): + image = load_image(inputs["image"], timeout=timeout) + candidate_labels = inputs["candidate_labels"] + if isinstance(candidate_labels, str): + candidate_labels = candidate_labels.split(",") + + target_size = torch.tensor([[image.height, image.width]], dtype=torch.int32) + for i, candidate_label in enumerate(candidate_labels): + text_inputs = self.tokenizer(candidate_label, return_tensors="pt") + image_features = self.image_processor(image, return_tensors="pt") + image_features = image_features.to(self.dtype) + yield { + "is_last": i == len(candidate_labels) - 1, + "target_size": target_size, + "candidate_label": candidate_label, + **text_inputs, + **image_features, + } + + def _forward(self, model_inputs): + target_size = model_inputs.pop("target_size") + candidate_label = model_inputs.pop("candidate_label") + is_last = model_inputs.pop("is_last") + + outputs = self.model(**model_inputs) + + model_outputs = {"target_size": target_size, "candidate_label": candidate_label, "is_last": is_last, **outputs} + return model_outputs + + def postprocess(self, model_outputs, threshold=0.1, top_k=None): + results = [] + for model_output in model_outputs: + label = model_output["candidate_label"] + model_output = BaseModelOutput(model_output) + outputs = self.image_processor.post_process_object_detection( + outputs=model_output, threshold=threshold, target_sizes=model_output["target_size"] + )[0] + + for index in outputs["scores"].nonzero(): + score = outputs["scores"][index].item() + box = self._get_bounding_box(outputs["boxes"][index][0]) + + result = {"score": score, "label": label, "box": box} + results.append(result) + + results = sorted(results, key=lambda x: x["score"], reverse=True) + if top_k: + results = results[:top_k] + + return results + + def _get_bounding_box(self, box: "torch.Tensor") -> dict[str, int]: + """ + Turns list [xmin, xmax, ymin, ymax] into dict { "xmin": xmin, ... } + + Args: + box (`torch.Tensor`): Tensor containing the coordinates in corners format. + + Returns: + bbox (`dict[str, int]`): Dict containing the coordinates in corners format. + """ + xmin, ymin, xmax, ymax = box.int().tolist() + bbox = { + "xmin": xmin, + "ymin": ymin, + "xmax": xmax, + "ymax": ymax, + } + return bbox diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7117bc2b5d8045380f582ac09338af3f3f3e3f61 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# 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. +from .auto import AutoHfQuantizer, AutoQuantizationConfig, register_quantization_config, register_quantizer +from .base import HfQuantizer +from .quantizers_utils import get_module_from_name diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94ea654126f89b9c97428665d7cdbb9534feb56e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/auto.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/auto.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec8587e7de8b4f372f29ea9710330ead92a40bf7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/auto.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..789ea984103002f8c6226d7b745332cc985ffe11 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/base.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_aqlm.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_aqlm.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..888e8a7a0a51e40d9f1e45d723d68673ffe221fd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_aqlm.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_auto_round.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_auto_round.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a26348ec3aa87acfd068f7cd9d91de54726ec9eb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_auto_round.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_awq.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_awq.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..735d6f0e214bb12f0aaecbf03039be6382a027da Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_awq.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_bitnet.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_bitnet.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..481abb8c39b4ec846fa68939903523f6dfda2fc3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_bitnet.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_bnb_4bit.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_bnb_4bit.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76101e36cacb3685687a9b33aad1b541cffbb653 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_bnb_4bit.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_bnb_8bit.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_bnb_8bit.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e11d5a387b9a2cc91d1767295f5232716360a759 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_bnb_8bit.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_compressed_tensors.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_compressed_tensors.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c70ff2c365629a1314a44a9f032eed17445d5516 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_compressed_tensors.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_eetq.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_eetq.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8768a1c204bfce1be76b3ab1e01fd621f3a7e4e8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_eetq.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_fbgemm_fp8.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_fbgemm_fp8.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e1df94a3508fd39fe97a7350aa3ecd143eba10c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_fbgemm_fp8.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_finegrained_fp8.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_finegrained_fp8.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a69e8252033f37d9d49bfdc57827540a229cb25 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_finegrained_fp8.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_fouroversix.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_fouroversix.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c694b90b8dbe1590f0e64db68f1840fee5dfb068 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_fouroversix.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_fp_quant.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_fp_quant.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ada08ec1e12bdee8a6376d88f6f9a2ba6dda5f6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_fp_quant.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_gptq.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_gptq.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa4d762af8883eca756840283bb303282253d8b5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_gptq.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_higgs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_higgs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d338b1ca48e57860cab1f772b1e408f24736e1c8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_higgs.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_hqq.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_hqq.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f0d4ac9c96d9fb38b580d56a9776c98d519afd3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_hqq.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_metal.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_metal.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07c2c6f998bc152f8d2d5df529efe7435cbf280f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_metal.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_mxfp4.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_mxfp4.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e32d28383983be5259641aad666f45d3cb0d1a45 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_mxfp4.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_quanto.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_quanto.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20ec396f6049ac738aed4746d62a98286967b381 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_quanto.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_quark.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_quark.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..270ec286580829edc1be0465dc9b3e303fc07210 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_quark.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_sinq.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_sinq.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6d6a097306de93c66678aeff7df849f06b9c211 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_sinq.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_spqr.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_spqr.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b45291bef06ca396c79beeffcc3b0d274ba577a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_spqr.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_torchao.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_torchao.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf82220d77b87121a610517304bf45757d8cb20d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_torchao.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_vptq.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_vptq.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04b170ff6f7e3e796bc36e84a6d049c6d798ff50 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_vptq.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizers_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizers_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..084b78a1a326ba35e2def9eb8ff72d4bd3480276 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizers_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/auto.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/auto.py new file mode 100644 index 0000000000000000000000000000000000000000..a972c6f637bb23092426e42a04be3753c97f58b5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/auto.py @@ -0,0 +1,354 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# Modifications Copyright (C) 2025, Advanced Micro Devices, Inc. All rights reserved. +# +# 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. +import warnings + +from ..models.auto.configuration_auto import AutoConfig +from ..utils import logging +from ..utils.quantization_config import ( + AqlmConfig, + AutoRoundConfig, + AwqConfig, + BitNetQuantConfig, + BitsAndBytesConfig, + CompressedTensorsConfig, + EetqConfig, + FbgemmFp8Config, + FineGrainedFP8Config, + FourOverSixConfig, + FPQuantConfig, + GPTQConfig, + HiggsConfig, + HqqConfig, + MetalConfig, + Mxfp4Config, + QuantizationConfigMixin, + QuantizationMethod, + QuantoConfig, + QuarkConfig, + SinqConfig, + SpQRConfig, + TorchAoConfig, + VptqConfig, +) +from .base import HfQuantizer +from .quantizer_aqlm import AqlmHfQuantizer +from .quantizer_auto_round import AutoRoundQuantizer +from .quantizer_awq import AwqQuantizer +from .quantizer_bitnet import BitNetHfQuantizer +from .quantizer_bnb_4bit import Bnb4BitHfQuantizer +from .quantizer_bnb_8bit import Bnb8BitHfQuantizer +from .quantizer_compressed_tensors import CompressedTensorsHfQuantizer +from .quantizer_eetq import EetqHfQuantizer +from .quantizer_fbgemm_fp8 import FbgemmFp8HfQuantizer +from .quantizer_finegrained_fp8 import FineGrainedFP8HfQuantizer +from .quantizer_fouroversix import FourOverSixHfQuantizer +from .quantizer_fp_quant import FPQuantHfQuantizer +from .quantizer_gptq import GptqHfQuantizer +from .quantizer_higgs import HiggsHfQuantizer +from .quantizer_hqq import HqqHfQuantizer +from .quantizer_metal import MetalHfQuantizer +from .quantizer_mxfp4 import Mxfp4HfQuantizer +from .quantizer_quanto import QuantoHfQuantizer +from .quantizer_quark import QuarkHfQuantizer +from .quantizer_sinq import SinqHfQuantizer +from .quantizer_spqr import SpQRHfQuantizer +from .quantizer_torchao import TorchAoHfQuantizer +from .quantizer_vptq import VptqHfQuantizer + + +AUTO_QUANTIZER_MAPPING = { + "awq": AwqQuantizer, + "bitsandbytes_4bit": Bnb4BitHfQuantizer, + "bitsandbytes_8bit": Bnb8BitHfQuantizer, + "gptq": GptqHfQuantizer, + "aqlm": AqlmHfQuantizer, + "quanto": QuantoHfQuantizer, + "quark": QuarkHfQuantizer, + "fouroversix": FourOverSixHfQuantizer, + "fp_quant": FPQuantHfQuantizer, + "eetq": EetqHfQuantizer, + "higgs": HiggsHfQuantizer, + "hqq": HqqHfQuantizer, + "compressed-tensors": CompressedTensorsHfQuantizer, + "fbgemm_fp8": FbgemmFp8HfQuantizer, + "torchao": TorchAoHfQuantizer, + "bitnet": BitNetHfQuantizer, + "vptq": VptqHfQuantizer, + "spqr": SpQRHfQuantizer, + "fp8": FineGrainedFP8HfQuantizer, + "auto-round": AutoRoundQuantizer, + "mxfp4": Mxfp4HfQuantizer, + "metal": MetalHfQuantizer, + "sinq": SinqHfQuantizer, +} + +AUTO_QUANTIZATION_CONFIG_MAPPING = { + "awq": AwqConfig, + "bitsandbytes_4bit": BitsAndBytesConfig, + "bitsandbytes_8bit": BitsAndBytesConfig, + "eetq": EetqConfig, + "gptq": GPTQConfig, + "aqlm": AqlmConfig, + "quanto": QuantoConfig, + "quark": QuarkConfig, + "fouroversix": FourOverSixConfig, + "fp_quant": FPQuantConfig, + "hqq": HqqConfig, + "compressed-tensors": CompressedTensorsConfig, + "fbgemm_fp8": FbgemmFp8Config, + "higgs": HiggsConfig, + "torchao": TorchAoConfig, + "bitnet": BitNetQuantConfig, + "vptq": VptqConfig, + "spqr": SpQRConfig, + "fp8": FineGrainedFP8Config, + "auto-round": AutoRoundConfig, + "mxfp4": Mxfp4Config, + "metal": MetalConfig, + "sinq": SinqConfig, +} + +LOADING_ATTRIBUTES_CONFIG_TYPES = ( + GPTQConfig, + AwqConfig, + AutoRoundConfig, + FbgemmFp8Config, + CompressedTensorsConfig, + Mxfp4Config, + MetalConfig, + FineGrainedFP8Config, +) + +logger = logging.get_logger(__name__) + + +class AutoQuantizationConfig: + """ + The Auto-HF quantization config class that takes care of automatically dispatching to the correct + quantization config given a quantization config stored in a dictionary. + """ + + @classmethod + def from_dict(cls, quantization_config_dict: dict): + quant_method = quantization_config_dict.get("quant_method") + # We need a special care for bnb models to make sure everything is BC .. + if quantization_config_dict.get("load_in_8bit", False) or quantization_config_dict.get("load_in_4bit", False): + suffix = "_4bit" if quantization_config_dict.get("load_in_4bit", False) else "_8bit" + quant_method = QuantizationMethod.BITS_AND_BYTES + suffix + elif quant_method is None: + raise ValueError( + "The model's quantization config from the arguments has no `quant_method` attribute. Make sure that the model has been correctly quantized" + ) + + if quant_method not in AUTO_QUANTIZATION_CONFIG_MAPPING: + raise ValueError( + f"Unknown quantization type, got {quant_method} - supported types are:" + f" {list(AUTO_QUANTIZER_MAPPING.keys())}" + ) + + target_cls = AUTO_QUANTIZATION_CONFIG_MAPPING[quant_method] + return target_cls.from_dict(quantization_config_dict) + + @classmethod + def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): + model_config = AutoConfig.from_pretrained(pretrained_model_name_or_path, **kwargs) + if getattr(model_config, "quantization_config", None) is None: + raise ValueError( + f"Did not found a `quantization_config` in {pretrained_model_name_or_path}. Make sure that the model is correctly quantized." + ) + quantization_config_dict = model_config.quantization_config + quantization_config = cls.from_dict(quantization_config_dict) + # Update with potential kwargs that are passed through from_pretrained. + quantization_config.update(**kwargs) + return quantization_config + + +class AutoHfQuantizer: + """ + The Auto-HF quantizer class that takes care of automatically instantiating to the correct + `HfQuantizer` given the `QuantizationConfig`. + """ + + @classmethod + def from_config(cls, quantization_config: QuantizationConfigMixin | dict, **kwargs): + # Convert it to a QuantizationConfig if the q_config is a dict + if isinstance(quantization_config, dict): + quantization_config = AutoQuantizationConfig.from_dict(quantization_config) + + quant_method = quantization_config.quant_method + + # Again, we need a special care for bnb as we have a single quantization config + # class for both 4-bit and 8-bit quantization + if quant_method == QuantizationMethod.BITS_AND_BYTES: + if not isinstance(quantization_config, BitsAndBytesConfig): + raise TypeError( + "Found `quant_method=bitsandbytes` but `quantization_config` is not a `BitsAndBytesConfig`." + ) + if quantization_config.load_in_8bit: + quant_method += "_8bit" + else: + quant_method += "_4bit" + + if quant_method not in AUTO_QUANTIZER_MAPPING: + raise ValueError( + f"Unknown quantization type, got {quant_method} - supported types are:" + f" {list(AUTO_QUANTIZER_MAPPING.keys())}" + ) + + target_cls = AUTO_QUANTIZER_MAPPING[quant_method] + return target_cls(quantization_config, **kwargs) + + @classmethod + def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): + quantization_config = AutoQuantizationConfig.from_pretrained(pretrained_model_name_or_path, **kwargs) + return cls.from_config(quantization_config) + + @classmethod + def merge_quantization_configs( + cls, + quantization_config: dict | QuantizationConfigMixin, + quantization_config_from_args: QuantizationConfigMixin | None, + ): + """ + handles situations where both quantization_config from args and quantization_config from model config are present. + """ + if quantization_config_from_args is not None: + warning_msg = ( + "You passed `quantization_config` or equivalent parameters to `from_pretrained` but the model you're loading" + " already has a `quantization_config` attribute. The `quantization_config` from the model will be used." + ) + else: + warning_msg = "" + + if isinstance(quantization_config, dict): + # Convert the config based on the type of quantization_config_from_args (e.g., AutoRoundConfig), which takes priority before automatic configuration dispatch. + if isinstance(quantization_config_from_args, AutoRoundConfig): + quantization_config = AutoRoundConfig.from_dict(quantization_config) + else: + quantization_config = AutoQuantizationConfig.from_dict(quantization_config) + + if ( + quantization_config_from_args is not None + and quantization_config.__class__.__name__ != quantization_config_from_args.__class__.__name__ + ): + raise ValueError( + f"The model is quantized with {quantization_config.__class__.__name__} but you are passing a {quantization_config_from_args.__class__.__name__} config. " + "Please make sure to pass the same quantization config class to `from_pretrained` with different loading attributes." + ) + + if isinstance(quantization_config, LOADING_ATTRIBUTES_CONFIG_TYPES) and isinstance( + quantization_config_from_args, LOADING_ATTRIBUTES_CONFIG_TYPES + ): + loading_attr_dict = quantization_config_from_args.get_loading_attributes() + for attr, val in loading_attr_dict.items(): + setattr(quantization_config, attr, val) + + if loading_attr_dict: + warning_msg += f"However, loading attributes (e.g. {list(loading_attr_dict.keys())}) will be overwritten with the one you passed to `from_pretrained`. The rest will be ignored." + + if warning_msg != "" and not isinstance(quantization_config, (Mxfp4Config, MetalConfig, FineGrainedFP8Config)): + warnings.warn(warning_msg) + else: + # in the case of mxfp4, we don't want to print the warning message, bit confusing for users + logger.info(warning_msg) + return quantization_config + + @staticmethod + def supports_quant_method(quantization_config_dict): + quant_method = quantization_config_dict.get("quant_method", None) + if quantization_config_dict.get("load_in_8bit", False) or quantization_config_dict.get("load_in_4bit", False): + suffix = "_4bit" if quantization_config_dict.get("load_in_4bit", False) else "_8bit" + quant_method = QuantizationMethod.BITS_AND_BYTES + suffix + elif quant_method is None: + raise ValueError( + "The model's quantization config from the arguments has no `quant_method` attribute. Make sure that the model has been correctly quantized" + ) + + if quant_method not in AUTO_QUANTIZATION_CONFIG_MAPPING: + logger.warning( + f"Unknown quantization type, got {quant_method} - supported types are:" + f" {list(AUTO_QUANTIZER_MAPPING.keys())}. Hence, we will skip the quantization. " + "To remove the warning, you can delete the quantization_config attribute in config.json" + ) + return False + return True + + +def register_quantization_config(method: str): + """Register a custom quantization configuration.""" + + def register_config_fn(cls): + if method in AUTO_QUANTIZATION_CONFIG_MAPPING: + raise ValueError(f"Config '{method}' already registered") + + if not issubclass(cls, QuantizationConfigMixin): + raise TypeError("Config must extend QuantizationConfigMixin") + + AUTO_QUANTIZATION_CONFIG_MAPPING[method] = cls + return cls + + return register_config_fn + + +def register_quantizer(name: str): + """Register a custom quantizer.""" + + def register_quantizer_fn(cls): + if name in AUTO_QUANTIZER_MAPPING: + raise ValueError(f"Quantizer '{name}' already registered") + + if not issubclass(cls, HfQuantizer): + raise TypeError("Quantizer must extend HfQuantizer") + + AUTO_QUANTIZER_MAPPING[name] = cls + return cls + + return register_quantizer_fn + + +def get_hf_quantizer(config, quantization_config, device_map, weights_only, user_agent): + pre_quantized = hasattr(config, "quantization_config") + if pre_quantized and not AutoHfQuantizer.supports_quant_method(config.quantization_config): + pre_quantized = False + + if pre_quantized or quantization_config is not None: + if pre_quantized: + config.quantization_config = AutoHfQuantizer.merge_quantization_configs( + config.quantization_config, quantization_config + ) + else: + config.quantization_config = quantization_config + + hf_quantizer = AutoHfQuantizer.from_config( + config.quantization_config, + pre_quantized=pre_quantized, + ) + else: + hf_quantizer = None + + if hf_quantizer is not None: + hf_quantizer.validate_environment( + device_map=device_map, + weights_only=weights_only, + ) + device_map = hf_quantizer.update_device_map(device_map) + config = hf_quantizer.update_tp_plan(config) + config = hf_quantizer.update_ep_plan(config) + + # In order to ensure popular quantization methods are supported. Can be disable with `disable_telemetry` + if not getattr(hf_quantizer.quantization_config, "dequantize", False): + quant_method = hf_quantizer.quantization_config.quant_method + user_agent["quant"] = getattr(quant_method, "value", quant_method) + return hf_quantizer, config, device_map diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/base.py new file mode 100644 index 0000000000000000000000000000000000000000..fbebea2977bebfbcdea00fa2fd74e4cb0d689f16 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/base.py @@ -0,0 +1,342 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# 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. +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING, Any + +from ..utils import is_torch_available, logging +from ..utils.quantization_config import QuantizationConfigMixin, QuantizationMethod +from .quantizers_utils import get_module_from_name + + +if TYPE_CHECKING: + from torch.nn import ModuleList + + from ..modeling_utils import PreTrainedModel + +if is_torch_available(): + import torch + + if not TYPE_CHECKING: + from torch.nn import ModuleList +else: + ModuleList = str + +logger = logging.get_logger(__file__) + + +def get_keys_to_not_convert(model) -> list: + r""" + Function to automatically detect keys to not convert for usage like quantization. For example for CausalLM modules + we may want to keep the lm_head in full precision for numerical stability reasons. + """ + # remove tied weights + tied_keys = set() + if len(model.all_tied_weights_keys) > 0: + tied_keys = set(model.all_tied_weights_keys.values()) | set(model.all_tied_weights_keys.keys()) + + # remove last module + last_module_key = {list(model.named_parameters())[-1][0]} + + # remove output emb + output_emb_module = model.get_output_embeddings() + output_emb_keys = { + name + for name, module in model.named_modules() + if output_emb_module is not None and id(module) == id(output_emb_module) + } + modules_to_not_convert = tied_keys | last_module_key | output_emb_keys + + modules_to_not_convert = list({k.removesuffix(".weight") for k in modules_to_not_convert}) + + return list(modules_to_not_convert) + + +def _assign_is_quantized(model): + from ..modeling_utils import PreTrainedModel + + for module in model.modules(): + if isinstance(module, PreTrainedModel): + module.config._is_quantized = True + + +class HfQuantizer(ABC): + """ + Abstract class of the HuggingFace quantizer. Supports for now quantizing HF transformers models for inference and/or quantization. + This class is used only for transformers.PreTrainedModel.from_pretrained and cannot be easily used outside the scope of that method + yet. + + Attributes + quantization_config (`transformers.utils.quantization_config.QuantizationConfigMixin`): + The quantization config that defines the quantization parameters of your model that you want to quantize. + requires_calibration (`bool`): + Whether the quantization method requires to calibrate the model before using it. + """ + + requires_calibration = False + + def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs): + self.quantization_config = quantization_config + self.pre_quantized = kwargs.pop("pre_quantized", True) + + if not self.pre_quantized and self.requires_calibration: + raise ValueError( + f"The quantization method {quantization_config.quant_method} does require the model to be pre-quantized." + f" You explicitly passed `pre_quantized=False` meaning your model weights are not quantized. Make sure to " + f"pass `pre_quantized=True` while knowing what you are doing." + ) + + def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype": + """ + Some quantization methods require to explicitly set the dtype of the model to a + target dtype. You need to override this method in case you want to make sure that behavior is + preserved + + Args: + dtype (`torch.dtype`): + The input dtype that is passed in `from_pretrained` + """ + return dtype + + def update_device_map(self, device_map: dict[str, Any] | None) -> dict[str, Any] | None: + """ + Override this method if you want to pass a override the existing device map with a new + one. E.g. for bitsandbytes, since `accelerate` is a hard requirement, if no device_map is + passed, the device_map is set to `"auto"`` + + Args: + device_map (`Union[dict, str]`, *optional*): + The device_map that is passed through the `from_pretrained` method. + """ + return device_map + + def param_element_size(self, model: "PreTrainedModel", param_name: str, param: "torch.Tensor") -> float: + return param.element_size() + + def adjust_max_memory(self, max_memory: dict[str, int | str]) -> dict[str, int | str]: + """adjust max_memory argument for infer_auto_device_map() if extra memory is needed for quantization""" + return max_memory + + def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool: + """ + Check whether a given param needs to be quantized. + """ + return False + + def validate_environment(self, *args, **kwargs): + """ + This method is used to potentially check for potential conflicts with arguments that are + passed in `from_pretrained`. You need to define it for all future quantizers that are integrated with transformers. + If no explicit check are needed, simply return nothing. + """ + return + + def update_tp_plan(self, config): + "updates the tp plan for the scales" + return config + + def update_ep_plan(self, config): + "updates the tp plan for the scales" + return config + + def _process_model_before_weight_loading(self, model, **kwargs): + return model + + def preprocess_model(self, model: "PreTrainedModel", dtype=None, **kwargs): + """ + Setting model attributes and/or converting model before weights loading. At this point + the model should be initialized on the meta device so you can freely manipulate the skeleton + of the model in order to replace modules in-place. Make sure to override the abstract method `_process_model_before_weight_loading`. + + Args: + model (`~transformers.PreTrainedModel`): + The model to quantize + kwargs (`dict`, *optional*): + The keyword arguments that are passed along `_process_model_before_weight_loading`. + """ + setattr(model, "is_quantized", True) + setattr(model, "quantization_method", self.quantization_config.quant_method) + if self.pre_quantized: + self._convert_model_for_quantization(model) + self._process_model_before_weight_loading(model, **kwargs) + + def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs): + return model + + def postprocess_model(self, model: "PreTrainedModel", **kwargs): + """ + Post-process the model post weights loading. + Make sure to override the abstract method `_process_model_after_weight_loading`. + + Args: + model (`~transformers.PreTrainedModel`): + The model to quantize + kwargs (`dict`, *optional*): + The keyword arguments that are passed along `_process_model_after_weight_loading`. + """ + model.config.quantization_config = self.quantization_config + + if self.pre_quantized and getattr(self.quantization_config, "dequantize", False): + self.remove_quantization_config(model) + else: + _assign_is_quantized(model) + + return self._process_model_after_weight_loading(model, **kwargs) + + def remove_quantization_config(self, model): + """ + Remove the quantization config from the model. + """ + if hasattr(model, "hf_quantizer"): + del model.hf_quantizer + if hasattr(model.config, "quantization_config"): + del model.config.quantization_config + if hasattr(model, "quantization_method"): + del model.quantization_method + model.is_quantized = False + + def dequantize(self, model, dtype=None): + """ + Potentially dequantize the model to retrieve the original model, with some loss in accuracy / performance. + Note not all quantization schemes support this. + """ + if dtype is None: + # using the same dtype we used to load the model. If we don't do that, we might have issues with modules we didn't quantize. + # or we need to upcast everything to the same dtype + dtype = model.config.dtype + model = self._dequantize(model, dtype=dtype) + self.remove_quantization_config(model) + + return model + + def _dequantize(self, model, dtype=None): + raise NotImplementedError( + f"{self.quantization_config.quant_method} has no implementation of `dequantize`, please raise an issue on GitHub." + ) + + def get_param_name(self, param_name: str) -> str: + """ + Override this method if you want to adjust the `param_name`. + """ + return param_name + + @staticmethod + def get_modules_to_not_convert( + model: "PreTrainedModel", + skip_modules: list[str] | None = None, + keep_in_fp32_modules: list[str] | None = None, + add_default_skips: bool = False, + ): + if skip_modules is None or add_default_skips: + modules_to_not_convert = get_keys_to_not_convert(model) + else: + modules_to_not_convert = [] + + if skip_modules is not None: + modules_to_not_convert.extend(skip_modules) + + if keep_in_fp32_modules is not None: + modules_to_not_convert.extend(keep_in_fp32_modules) + + modules_to_not_convert = list(set(modules_to_not_convert)) + + return modules_to_not_convert + + @property + def is_qat_trainable(self) -> bool: + """Flag indicating whether the quantized model can carry out quantization aware training""" + return False + + @property + def is_compileable(self) -> bool: + """Flag indicating whether the quantized model can be compiled""" + return False + + def get_state_dict_and_metadata(self, model): + """Get state dict and metadata. Useful when we need to modify a bit the state dict due to quantization""" + return None, {} + + @abstractmethod + def is_serializable(self): ... + + @property + @abstractmethod + def is_trainable(self): ... + + def _convert_model_for_quantization(self, model): + for name, module in model.named_modules(): + module_class_name = module.__class__.__name__ + if module_class_name in MODULES_TO_PATCH_FOR_QUANTIZATION and ( + self.quantization_config.quant_method + in MODULES_TO_PATCH_FOR_QUANTIZATION[module_class_name]["quantization_methods"] + ): + with torch.device("meta"): + parent_module, name = get_module_from_name(model, name) + parent_module._modules[name] = MODULES_TO_PATCH_FOR_QUANTIZATION[module_class_name]["module_name"]( + model.config.get_text_config() + ) + + def get_quantize_ops(self): + raise NotImplementedError( + f"{self.quantization_config.quant_method} is not available yet and will be supported soon." + ) + + def get_weight_conversions(self): + return [] + + def update_weight_conversions(self, weight_conversions): + """Give the quantizer a chance to rewrite the weight conversion pipeline. + + Loading runs ``renamings → converters → (dequant → merge → concat)``. Dequant + has to happen *before* any merge/concat op because those operations aren't + aware of per-block scales, so the per-expert (weight, scale) pairs need to be + collapsed into full-precision tensors first. Subclasses (e.g. the FP8 + quantizer in ``dequantize=True`` mode) override this to inject a dequantize + op at the start of each model-provided :class:`WeightConverter` and attach the + matching scale source patterns. Default: no-op. + """ + return weight_conversions + self.get_weight_conversions() + + +class SequentialLlama4TextExperts(ModuleList): + """ + A module that implements a compressed version of a list of expert modules. + This is specifically designed to work with Llama4TextExperts in MoE layers. + """ + + def __init__(self, config): + from transformers.models.llama4.modeling_llama4 import Llama4TextMLP + + super().__init__([Llama4TextMLP(config) for _ in range(config.num_local_experts)]) + self.num_experts = config.num_local_experts + + def forward( + self, + hidden_states: "torch.Tensor", + ) -> "torch.Tensor": + hidden_states = hidden_states.reshape(self.num_experts, -1, hidden_states.shape[-1]) + routed_out = torch.zeros_like(hidden_states) + for expert_idx in range(self.num_experts): + routed_out[expert_idx] = self[expert_idx](hidden_states[expert_idx]) + return routed_out + + +MODULES_TO_PATCH_FOR_QUANTIZATION = { + "Llama4TextExperts": { + "module_name": SequentialLlama4TextExperts, + "quantization_methods": [ + QuantizationMethod.COMPRESSED_TENSORS, + QuantizationMethod.BITS_AND_BYTES, + ], + } +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_aqlm.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_aqlm.py new file mode 100644 index 0000000000000000000000000000000000000000..2d0fd7939d88ad4a417b5f92772f04de7f4fbc95 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_aqlm.py @@ -0,0 +1,75 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# 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. +from importlib import metadata +from typing import TYPE_CHECKING + +from packaging import version + +from .base import HfQuantizer + + +if TYPE_CHECKING: + from ..modeling_utils import PreTrainedModel + from ..utils.quantization_config import AqlmConfig + +from ..integrations import replace_with_aqlm_linear +from ..utils import is_accelerate_available, is_aqlm_available, logging +from ..utils.quantization_config import QuantizationConfigMixin + + +logger = logging.get_logger(__name__) + + +class AqlmHfQuantizer(HfQuantizer): + """ + Quantizer of the AQLM method. Enables the loading of prequantized models. + """ + + requires_calibration = True + quantization_config: "AqlmConfig" + + def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs): + super().__init__(quantization_config, **kwargs) + + def validate_environment(self, *args, **kwargs): + if not is_accelerate_available(): + raise ImportError("Using `aqlm` quantization requires Accelerate: `pip install accelerate`") + + if not is_aqlm_available(): + raise ImportError("Using `aqlm` quantization requires AQLM: `pip install aqlm[gpu,cpu]`") + + def _process_model_before_weight_loading( + self, + model: "PreTrainedModel", + **kwargs, + ): + replace_with_aqlm_linear( + model, + modules_to_not_convert=self.quantization_config.linear_weights_not_to_quantize, + quantization_config=self.quantization_config, + ) + + @property + def is_trainable(self) -> bool: + aqlm_supports_training = version.parse(metadata.version("aqlm")) >= version.parse("1.0.2") + if aqlm_supports_training: + return True + else: + logger.warning( + f"Currently installed `aqlm` version ({metadata.version('aqlm')}) doesn't support training. If you wish to train a quantized model, please update `aqlm` with `pip install aqlm>=1.0.2`" + ) + return False + + def is_serializable(self): + return True diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_auto_round.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_auto_round.py new file mode 100644 index 0000000000000000000000000000000000000000..3a52314013066b21fb90ed5646e101ec7d67cd09 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_auto_round.py @@ -0,0 +1,71 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# 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. +from typing import TYPE_CHECKING + +from .base import HfQuantizer + + +if TYPE_CHECKING: + from ..modeling_utils import PreTrainedModel + +from ..utils import is_auto_round_available, logging +from ..utils.quantization_config import QuantizationConfigMixin + + +logger = logging.get_logger(__name__) + + +class AutoRoundQuantizer(HfQuantizer): + """ + Quantizer of the AutoRound method. (https://huggingface.co/papers/2309.05516) + """ + + # AutoRound requires data calibration - we support only inference + requires_calibration = True + + def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs): + super().__init__(quantization_config, **kwargs) + + def validate_environment(self, *args, **kwargs): + self.device_map = kwargs.get("device_map") + if not is_auto_round_available(): + raise ImportError( + "Loading an AutoRound quantized model requires auto-round library (`pip install 'auto-round>=0.5'`)" + ) + + def _process_model_before_weight_loading(self, model: "PreTrainedModel", **kwargs): + if model.__class__.main_input_name != "input_ids": + logger.warning("AutoRound offers only limited support for models that are not strictly text-based.") + from auto_round.inference.convert_model import convert_hf_model, infer_target_device + + if self.pre_quantized: + target_device = infer_target_device(self.device_map) + model, used_backends = convert_hf_model(model, target_device) + self.used_backends = used_backends + + def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs): + if self.pre_quantized: + from auto_round.inference.convert_model import post_init + + post_init(model, self.used_backends) + else: + raise ValueError("AutoRound only sports pre-quantized models.") + + @property + def is_trainable(self) -> bool: + return False + + def is_serializable(self): + ## for gptq/awq models, the quantization config will be changed + return True diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_awq.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_awq.py new file mode 100644 index 0000000000000000000000000000000000000000..3a574ef13f8ff88cb033f650cbb71ee087644cb5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_awq.py @@ -0,0 +1,97 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# 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. +import importlib.metadata +from typing import TYPE_CHECKING + +from packaging import version + +from .base import HfQuantizer + + +if TYPE_CHECKING: + from ..modeling_utils import PreTrainedModel + from ..utils.quantization_config import AwqConfig + +from ..utils import is_accelerate_available, is_gptqmodel_available, is_torch_available, logging +from ..utils.quantization_config import AwqBackend + + +if is_torch_available(): + import torch + +logger = logging.get_logger(__name__) + + +class AwqQuantizer(HfQuantizer): + """ + 4-bit quantization for Activation-aware Weight Quantization(AWQ) (https://huggingface.co/papers/2306.00978) + """ + + # AWQ requires data calibration - we support only inference + requires_calibration = True + quantization_config: "AwqConfig" + + def __init__(self, quantization_config, **kwargs): + super().__init__(quantization_config, **kwargs) + + def validate_environment(self, **kwargs): + if not is_gptqmodel_available(): + raise ImportError( + "Loading an AWQ quantized model requires gptqmodel. Please install it with `pip install gptqmodel`" + ) + + if not is_accelerate_available(): + raise ImportError("Loading an AWQ quantized model requires accelerate (`pip install accelerate`)") + + def update_dtype(self, dtype): + if dtype == torch.bfloat16 and (torch.cuda.is_available() or torch.xpu.is_available()): + logger.warning( + "`torch.bfloat16` is not supported for AWQ CUDA/XPU kernels yet. Casting to `torch.float16`." + ) + dtype = torch.float16 + elif dtype != torch.float16 and (torch.cuda.is_available() or torch.xpu.is_available()): + logger.warning("We suggest you to set `dtype=torch.float16` for better efficiency on CUDA/XPU with AWQ.") + return dtype + + def _process_model_before_weight_loading(self, model: "PreTrainedModel", **kwargs): + from ..integrations import replace_quantization_scales, replace_with_awq_linear + + self.modules_to_not_convert = self.get_modules_to_not_convert( + model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules, add_default_skips=True + ) + + model = replace_with_awq_linear( + model, + quantization_config=self.quantization_config, + modules_to_not_convert=self.modules_to_not_convert, + device_map=kwargs.get("device_map"), + ) + + model = replace_quantization_scales(model, model.config.model_type) + + def _process_model_after_weight_loading(self, model, **kwargs): + from gptqmodel.utils.model import hf_gptqmodel_post_init + + hf_gptqmodel_post_init(model, use_act_order=self.quantization_config.desc_act) + + def is_serializable(self): + if self.quantization_config.backend in [AwqBackend.EXLLAMA_V1, AwqBackend.EXLLAMA_V2]: + logger.warning("You cannot save an AWQ model that uses Exllama backend!") + return False + + return True + + @property + def is_trainable(self): + return version.parse(importlib.metadata.version("gptqmodel")) >= version.parse("5.0.0") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_bitnet.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_bitnet.py new file mode 100644 index 0000000000000000000000000000000000000000..ec22976939eefcec251ad171f5c7a12331ff8e3e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_bitnet.py @@ -0,0 +1,124 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# 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. +from typing import TYPE_CHECKING + +from .base import HfQuantizer + + +if TYPE_CHECKING: + from ..modeling_utils import PreTrainedModel + from ..utils.quantization_config import BitNetQuantConfig + +from ..utils import is_accelerate_available, is_torch_available, logging + + +if is_torch_available(): + import torch + + +logger = logging.get_logger(__name__) + + +class BitNetHfQuantizer(HfQuantizer): + """ + 1.58-bit quantization from BitNet quantization method: + Before loading: it converts the linear layers into BitLinear layers during loading. + + Check out the paper introducing this method: https://huggingface.co/papers/2402.17764 + """ + + requires_calibration = True + quantization_config: "BitNetQuantConfig" + + def __init__(self, quantization_config, **kwargs): + super().__init__(quantization_config, **kwargs) + + def validate_environment(self, *args, **kwargs): + if not is_accelerate_available(): + raise ImportError("Loading a BitNet quantized model requires accelerate (`pip install accelerate`)") + + if not torch.cuda.is_available(): + logger.warning_once( + "You don't have a GPU available to load the model, the inference will be slow because of weight unpacking" + ) + return + + device_map = kwargs.get("device_map") + if device_map is None: + logger.warning_once( + "You have loaded a BitNet model on CPU and have a CUDA device available, make sure to set " + "your model on a GPU device in order to run your model." + ) + elif isinstance(device_map, dict): + if len(device_map) > 1 and "cpu" in device_map.values() or "disk" in device_map.values(): + raise ValueError( + "You are attempting to load a BitNet model with a device_map that contains a CPU or disk device." + "This is not supported. Please remove the CPU or disk device from the device_map." + ) + + def _process_model_before_weight_loading( + self, + model: "PreTrainedModel", + **kwargs, + ): + from ..integrations import replace_with_bitnet_linear + + self.modules_to_not_convert = self.get_modules_to_not_convert( + model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules + ) + + model = replace_with_bitnet_linear( + model, + modules_to_not_convert=self.modules_to_not_convert, + quantization_config=self.quantization_config, + ) + + def adjust_max_memory(self, max_memory: dict[str, int | str]) -> dict[str, int | str]: + max_memory = {key: val * 0.90 for key, val in max_memory.items()} + return max_memory + + def is_serializable(self): + return True + + @property + def is_trainable(self) -> bool: + return ( + self.quantization_config.linear_class == "autobitlinear" + and self.quantization_config.quantization_mode == "online" + ) + + @property + def is_qat_trainable(self) -> bool: + """Flag indicating whether the quantized model can carry out quantization aware training""" + return ( + self.quantization_config.linear_class == "autobitlinear" + and self.quantization_config.quantization_mode == "online" + ) + + def get_weight_conversions(self): + from ..core_model_loading import WeightConverter + from ..integrations.bitnet import BitNetDeserialize + + if ( + self.quantization_config.linear_class == "autobitlinear" + and self.quantization_config.quantization_mode == "offline" + ): + return [ + WeightConverter( + source_patterns=["weight"], + target_patterns=["weight"], + operations=[BitNetDeserialize(self)], + ) + ] + return [] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_bnb_4bit.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_bnb_4bit.py new file mode 100644 index 0000000000000000000000000000000000000000..5fd040bed10e9fce70473e667adb4513459163b4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_bnb_4bit.py @@ -0,0 +1,187 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# 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. +from typing import TYPE_CHECKING + +from .base import HfQuantizer +from .quantizers_utils import get_module_from_name + + +if TYPE_CHECKING: + from ..modeling_utils import PreTrainedModel + from ..utils.quantization_config import BitsAndBytesConfig + +from ..utils import ( + ACCELERATE_MIN_VERSION, + BITSANDBYTES_MIN_VERSION, + is_accelerate_available, + is_bitsandbytes_available, + is_torch_available, + is_torch_hpu_available, + is_torch_npu_available, + is_torch_xpu_available, + logging, +) + + +if is_torch_available(): + import torch + + from ..core_model_loading import WeightConverter + +logger = logging.get_logger(__name__) + + +class Bnb4BitHfQuantizer(HfQuantizer): + """ + 4-bit quantization from bitsandbytes quantization method + """ + + requires_calibration = False + quantization_config: "BitsAndBytesConfig" + + def __init__(self, quantization_config, **kwargs): + super().__init__(quantization_config, **kwargs) + + def validate_environment(self, *args, **kwargs): + if not is_accelerate_available(): + raise ImportError( + f"Using `bitsandbytes` 4-bit quantization requires accelerate: `pip install 'accelerate>={ACCELERATE_MIN_VERSION}'`" + ) + if not is_bitsandbytes_available(): + raise ImportError( + f"Using `bitsandbytes` 4-bit quantization requires bitsandbytes: `pip install -U bitsandbytes>={BITSANDBYTES_MIN_VERSION}`" + ) + + from ..integrations import validate_bnb_backend_availability + + validate_bnb_backend_availability(raise_exception=True) + + device_map = kwargs.get("device_map") + if not self.quantization_config.llm_int8_enable_fp32_cpu_offload and isinstance(device_map, dict): + values = set(device_map.values()) + if values != {"cpu"} and ("cpu" in values or "disk" in values): + raise ValueError( + "Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the " + "quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules " + "in 32-bit, you need to set `llm_int8_enable_fp32_cpu_offload=True` and pass a custom `device_map` to " + "`from_pretrained`. Check " + "https://huggingface.co/docs/transformers/main/en/main_classes/quantization#offload-between-cpu-and-gpu " + "for more details. " + ) + + def param_element_size(self, model: "PreTrainedModel", param_name: str, param: "torch.Tensor") -> float: + "Return the element size (in bytes) for `param_name`." + if self.param_needs_quantization(model, param_name): + # 4 bit + return 0.5 + + return super().param_element_size(model, param_name, param) + + def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool: + import bitsandbytes as bnb + + module, name = get_module_from_name(model, param_name) + return isinstance(module, bnb.nn.Linear4bit) and name != "bias" + + def adjust_max_memory(self, max_memory: dict[str, int | str]) -> dict[str, int | str]: + # need more space for buffers that are created during quantization + max_memory = {key: val * 0.90 for key, val in max_memory.items()} + return max_memory + + def update_device_map(self, device_map): + if device_map is None: + if torch.cuda.is_available(): + device_map = {"": torch.cuda.current_device()} + elif is_torch_npu_available() and hasattr(torch, "npu"): + device_map = {"": f"npu:{torch.npu.current_device()}"} + elif is_torch_hpu_available() and hasattr(torch, "hpu"): + device_map = {"": f"hpu:{torch.hpu.current_device()}"} + elif is_torch_xpu_available(): + device_map = {"": torch.xpu.current_device()} + else: + device_map = {"": "cpu"} + logger.info( + "The device_map was not initialized. " + f"Setting device_map to {device_map}. " + "If you want to use the model for inference, please set device_map ='auto' " + ) + return device_map + + def _process_model_before_weight_loading( + self, + model: "PreTrainedModel", + device_map, + **kwargs, + ): + from ..integrations import replace_with_bnb_linear + + self.modules_to_not_convert = self.get_modules_to_not_convert( + model, self.quantization_config.llm_int8_skip_modules, model._keep_in_fp32_modules + ) + + if self.quantization_config.llm_int8_enable_fp32_cpu_offload: + if isinstance(device_map, dict): + keys_on_cpu = [key for key, value in device_map.items() if value in ["disk", "cpu"]] + self.modules_to_not_convert.extend(keys_on_cpu) + + model = replace_with_bnb_linear( + model, + modules_to_not_convert=self.modules_to_not_convert, + quantization_config=self.quantization_config, + pre_quantized=self.pre_quantized, + ) + + def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs): + setattr(model, "is_loaded_in_4bit", True) + setattr(model, "is_4bit_serializable", self.is_serializable()) + return model + + def is_serializable(self): + return True + + @property + def is_trainable(self) -> bool: + return True + + def _dequantize(self, model, dtype=None): + from ..integrations import dequantize_and_replace + + model = dequantize_and_replace(model, quantization_config=self.quantization_config, dtype=dtype) + return model + + def get_quantize_ops(self): + from ..integrations.bitsandbytes import Bnb4bitQuantize + + return Bnb4bitQuantize(self) + + def get_weight_conversions(self): + from ..integrations.bitsandbytes import Bnb4bitDeserialize + + if self.pre_quantized: + return [ + WeightConverter( + source_patterns=[ + "weight.nested_absmax", + "weight.nested_quant_map", + "weight.quant_map", + "weight.absmax", + "weight.quant_state.bitsandbytes__nf4", + "weight.quant_state.bitsandbytes__fp4", + "weight", + ], + target_patterns="weight", + operations=[Bnb4bitDeserialize(self)], + ) + ] + return [] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_bnb_8bit.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_bnb_8bit.py new file mode 100644 index 0000000000000000000000000000000000000000..cf3192bcd72a48a9e0d27cec1baaec19236f0a85 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_bnb_8bit.py @@ -0,0 +1,178 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# 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. +from typing import TYPE_CHECKING + +from .base import HfQuantizer + + +if TYPE_CHECKING: + from ..modeling_utils import PreTrainedModel + from ..utils.quantization_config import BitsAndBytesConfig + +from ..utils import ( + ACCELERATE_MIN_VERSION, + BITSANDBYTES_MIN_VERSION, + is_accelerate_available, + is_bitsandbytes_available, + is_torch_available, + is_torch_hpu_available, + is_torch_npu_available, + is_torch_xpu_available, + logging, +) +from .quantizers_utils import get_module_from_name + + +if is_torch_available(): + import torch + + from ..core_model_loading import WeightConverter + +logger = logging.get_logger(__name__) + + +class Bnb8BitHfQuantizer(HfQuantizer): + """ + 8-bit quantization from bitsandbytes quantization method + """ + + requires_calibration = False + quantization_config: "BitsAndBytesConfig" + + def __init__(self, quantization_config, **kwargs): + super().__init__(quantization_config, **kwargs) + + def validate_environment(self, *args, **kwargs): + if not is_accelerate_available(): + raise ImportError( + f"Using `bitsandbytes` 8-bit quantization requires accelerate: `pip install 'accelerate>={ACCELERATE_MIN_VERSION}'`" + ) + if not is_bitsandbytes_available(): + raise ImportError( + f"Using `bitsandbytes` 8-bit quantization requires bitsandbytes: `pip install -U bitsandbytes>={BITSANDBYTES_MIN_VERSION}`" + ) + + from ..integrations import validate_bnb_backend_availability + + validate_bnb_backend_availability(raise_exception=True) + + device_map = kwargs.get("device_map") + if not self.quantization_config.llm_int8_enable_fp32_cpu_offload and isinstance(device_map, dict): + values = set(device_map.values()) + if values != {"cpu"} and ("cpu" in values or "disk" in values): + raise ValueError( + "Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the " + "quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules " + "in 32-bit, you need to set `llm_int8_enable_fp32_cpu_offload=True` and pass a custom `device_map` to " + "`from_pretrained`. Check " + "https://huggingface.co/docs/transformers/main/en/main_classes/quantization#offload-between-cpu-and-gpu " + "for more details. " + ) + + def adjust_max_memory(self, max_memory: dict[str, int | str]) -> dict[str, int | str]: + # need more space for buffers that are created during quantization + max_memory = {key: val * 0.90 for key, val in max_memory.items()} + return max_memory + + def update_device_map(self, device_map): + if device_map is None: + if torch.cuda.is_available(): + device_map = {"": torch.cuda.current_device()} + elif is_torch_npu_available() and hasattr(torch, "npu"): + device_map = {"": f"npu:{torch.npu.current_device()}"} + elif is_torch_hpu_available() and hasattr(torch, "hpu"): + device_map = {"": f"hpu:{torch.hpu.current_device()}"} + elif is_torch_xpu_available(): + device_map = {"": torch.xpu.current_device()} + else: + device_map = {"": "cpu"} + logger.info( + "The device_map was not initialized. " + f"Setting device_map to {device_map}. " + "If you want to use the model for inference, please set device_map ='auto' " + ) + return device_map + + def param_element_size(self, model: "PreTrainedModel", param_name: str, param: "torch.Tensor") -> float: + "Return the element size (in bytes) for `param_name`." + if self.param_needs_quantization(model, param_name): + # 8-bit + return 1 + return super().param_element_size(model, param_name, param) + + def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool: + import bitsandbytes as bnb + + module, name = get_module_from_name(model, param_name) + return isinstance(module, bnb.nn.Linear8bitLt) and name != "bias" + + def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs): + setattr(model, "is_loaded_in_8bit", True) + model.is_8bit_serializable = self.is_serializable() + return model + + def _process_model_before_weight_loading( + self, + model: "PreTrainedModel", + device_map, + **kwargs, + ): + from ..integrations import replace_with_bnb_linear + + self.modules_to_not_convert = self.get_modules_to_not_convert( + model, self.quantization_config.llm_int8_skip_modules, model._keep_in_fp32_modules + ) + + if self.quantization_config.llm_int8_enable_fp32_cpu_offload: + if isinstance(device_map, dict): + keys_on_cpu = [key for key, value in device_map.items() if value in ["disk", "cpu"]] + self.modules_to_not_convert.extend(keys_on_cpu) + + model = replace_with_bnb_linear( + model, + modules_to_not_convert=self.modules_to_not_convert, + quantization_config=self.quantization_config, + pre_quantized=self.pre_quantized, + ) + + def is_serializable(self): + return True + + @property + def is_trainable(self) -> bool: + return True + + def _dequantize(self, model, dtype=None): + from ..integrations import dequantize_and_replace + + model = dequantize_and_replace(model, quantization_config=self.quantization_config, dtype=dtype) + return model + + def get_quantize_ops(self): + from ..integrations.bitsandbytes import Bnb8bitQuantize + + return Bnb8bitQuantize(self) + + def get_weight_conversions(self): + from ..integrations.bitsandbytes import Bnb8bitDeserialize + + if self.pre_quantized: + return [ + WeightConverter( + source_patterns=["SCB", "weight_format", "weight"], + target_patterns="weight", + operations=[Bnb8bitDeserialize(self)], + ) + ] + return [] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_compressed_tensors.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_compressed_tensors.py new file mode 100644 index 0000000000000000000000000000000000000000..5e1e4882beea28467043e85813757f764d175a97 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_compressed_tensors.py @@ -0,0 +1,114 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# 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. + + +from ..utils import is_compressed_tensors_available, is_torch_available, logging +from ..utils.quantization_config import CompressedTensorsConfig +from .base import HfQuantizer + + +if is_torch_available(): + import torch + +logger = logging.get_logger(__name__) + + +class CompressedTensorsHfQuantizer(HfQuantizer): + """ + Quantizer for the compressed_tensors package. Loads and restores models to + quantized state with compressed_tensors + """ + + requires_calibration = True + quantization_config: CompressedTensorsConfig + + def __init__(self, quantization_config: CompressedTensorsConfig, **kwargs): + super().__init__(quantization_config, **kwargs) + + if not is_compressed_tensors_available(): + raise ImportError( + "Using `compressed_tensors` quantized models requires the compressed-tensors library: " + "`pip install compressed-tensors`" + ) + + # Call post_init here to ensure proper config setup when `run_compressed` + # is provided directly via CompressedTensorsConfig, and to avoid duplicate logging. + + quantization_config.post_init() + from compressed_tensors.compressors import ModelCompressor + + self.compressor = ModelCompressor.from_compression_config(quantization_config) + self.run_compressed = quantization_config.run_compressed + self.quantization_config = quantization_config + + def validate_environment(self, *args, **kwargs): + if not is_compressed_tensors_available(): + raise ImportError( + "Using `compressed_tensors` quantized models requires the compressed-tensors library: " + "`pip install compressed-tensors`" + ) + + def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype": + if dtype != torch.float16: + logger.info("We suggest you to set `dtype=torch.float16` for better efficiency with compressed_tensors.") + return dtype + + def _process_model_before_weight_loading(self, model, **kwargs): + from compressed_tensors.quantization import apply_quantization_config + + ct_quantization_config = self.compressor.quantization_config + + # Always initialize compressed wrappers to match the checkpoint + apply_quantization_config(model, ct_quantization_config, self.run_compressed) + if ( + self.quantization_config.is_quantization_compressed + or self.quantization_config.is_sparsification_compressed + ): + self.compressor.compress_model(model=model) + + def _process_model_after_weight_loading(self, model, **kwargs): + """Decompress loaded model if necessary - need for qat""" + + if (self.quantization_config.is_quantization_compressed and not self.run_compressed) or ( + self.quantization_config.is_sparsification_compressed + ): + self.compressor.decompress_model(model=model) + + # NOTE: TP plan override for compressed tensors removed - unsupported styles were used. + # TODO: Implement proper TP support for compressed tensors quantization + def update_tp_plan(self, config): + additional_plan = { + "layers.*.feed_forward.experts.*.gate_proj.weight": "colwise", + "layers.*.feed_forward.experts.*.gate_proj.weight_scale": "colwise", + "layers.*.feed_forward.experts.*.up_proj.weight": "colwise", + "layers.*.feed_forward.experts.*.up_proj.weight_scale": "colwise", + "layers.*.feed_forward.experts.*.down_proj.weight": "rowwise", + } + if config.get_text_config() is not None and config.get_text_config().base_model_tp_plan is not None: + config.get_text_config().base_model_tp_plan.update(additional_plan) + + return config + + @property + def is_trainable(self): + return True + + def is_qat_trainable(self) -> bool: + """Loaded Models can carry out quantization aware training""" + # models need to be decompressed carry out qat + return not self.run_compressed or not self.quantization_config.is_quantization_compressed + + def is_serializable(self) -> bool: + """Models quantized using compressed tensors can be saved to disk""" + return True diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_eetq.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_eetq.py new file mode 100644 index 0000000000000000000000000000000000000000..ce1d350f3d96438663c6f065e94af95cc8d5fc57 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_eetq.py @@ -0,0 +1,110 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# 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. +from typing import TYPE_CHECKING + +from .base import HfQuantizer + + +if TYPE_CHECKING: + from ..modeling_utils import PreTrainedModel + from ..utils.quantization_config import EetqConfig + +from ..utils import is_accelerate_available, is_kernels_available, is_torch_available, logging +from .quantizers_utils import get_module_from_name + + +if is_torch_available(): + import torch + + +logger = logging.get_logger(__name__) + + +class EetqHfQuantizer(HfQuantizer): + """ + 8-bit quantization from EETQ quantization method + """ + + requires_calibration = False + quantization_config: "EetqConfig" + + def __init__(self, quantization_config, **kwargs): + super().__init__(quantization_config, **kwargs) + + def validate_environment(self, *args, **kwargs): + if not is_kernels_available(): + raise ImportError("Loading an EETQ quantized model requires kernels (`pip install kernels`)") + + if not is_accelerate_available(): + raise ImportError("Loading an EETQ quantized model requires accelerate (`pip install accelerate`)") + + if not torch.cuda.is_available(): + raise RuntimeError("No GPU found. A GPU is needed for quantization.") + + device_map = kwargs.get("device_map") + if device_map is None: + logger.warning_once( + "You have loaded an EETQ model on CPU and have a CUDA device available, make sure to set " + "your model on a GPU device in order to run your model." + ) + elif isinstance(device_map, dict): + if len(device_map) > 1 and "cpu" in device_map.values() or "disk" in device_map.values(): + raise ValueError( + "You are attempting to load an EETQ model with a device_map that contains a CPU or disk device." + " This is not supported. Please remove the CPU or disk device from the device_map." + ) + + def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype": + if dtype != torch.float16: + logger.info("We suggest you to set `dtype=torch.float16` for better efficiency with EETQ.") + return dtype + + def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool: + from ..integrations.eetq import EetqLinear + + module, tensor_name = get_module_from_name(model, param_name) + + if isinstance(module, EetqLinear): + if self.pre_quantized or tensor_name == "bias": + return False + else: + return True + return False + + def _process_model_before_weight_loading( + self, + model: "PreTrainedModel", + **kwargs, + ): + from ..integrations import replace_with_eetq_linear + + self.modules_to_not_convert = self.get_modules_to_not_convert( + model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules + ) + + model = replace_with_eetq_linear( + model, modules_to_not_convert=self.modules_to_not_convert, pre_quantized=self.pre_quantized + ) + + def is_serializable(self): + return True + + @property + def is_trainable(self) -> bool: + return True + + def get_quantize_ops(self): + from ..integrations.eetq import EetqQuantize + + return EetqQuantize(self) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_fbgemm_fp8.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_fbgemm_fp8.py new file mode 100644 index 0000000000000000000000000000000000000000..9cbc3cdcbe5f2413af19c4819692ba97a9178d98 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_fbgemm_fp8.py @@ -0,0 +1,207 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# 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. +from typing import TYPE_CHECKING + +from .base import HfQuantizer + + +if TYPE_CHECKING: + from ..modeling_utils import PreTrainedModel + from ..utils.quantization_config import FbgemmFp8Config + +from ..utils import ( + is_accelerate_available, + is_fbgemm_gpu_available, + is_kernels_available, + is_torch_available, + is_torch_cuda_available, + is_torch_xpu_available, + logging, +) +from .quantizers_utils import get_module_from_name + + +if is_torch_available(): + import torch + +logger = logging.get_logger(__name__) + + +class FbgemmFp8HfQuantizer(HfQuantizer): + """ + FP8 quantization using fbgemm kernels + """ + + requires_calibration = False + quantization_config: "FbgemmFp8Config" + + def __init__(self, quantization_config, **kwargs): + super().__init__(quantization_config, **kwargs) + + def validate_environment(self, *args, **kwargs): + if not is_torch_cuda_available() and not is_torch_xpu_available(): + raise ImportError("Using fbgemm fp8 quantization requires a GPU or XPU") + if is_torch_xpu_available() and not is_kernels_available(): + raise ImportError("Using FP8 fbgemm on XPU requires kernels (`pip install kernels`)") + if is_torch_cuda_available() and not is_fbgemm_gpu_available(): + raise ImportError( + "Loading an FP8 fbgemm quantized model on CUDA requires fbgemm-gpu library" + "Please install the latest version of fbgemm-gpu library by following : https://pytorch.org/FBGEMM/fbgemm_gpu-development/InstallationInstructions.html#fbgemm-gpu-install-libraries" + ) + if not is_accelerate_available(): + raise ImportError( + "Loading an FP8 quantized model requires accelerate (`pip install --upgrade accelerate`)" + ) + if is_torch_cuda_available(): + compute_capability = torch.cuda.get_device_capability() + major, _ = compute_capability + if major < 9: + raise ValueError( + "FP8 quantized models is only supported on GPUs with compute capability >= 9.0 (e.g H100)" + ) + + device_map = kwargs.get("device_map") + if device_map is None: + logger.warning_once( + "You have loaded an FP8 model on CPU and have a CUDA/XPU device available, make sure to set " + "your model on a GPU/XPU device in order to run your model. To remove this warning, pass device_map = 'cuda' or 'xpu' or 'auto'. " + ) + elif isinstance(device_map, dict): + if not self.pre_quantized and ("cpu" in device_map.values() or "disk" in device_map.values()): + raise ValueError( + "You are attempting to load an FP8 model with a device_map that contains a CPU or disk device." + "This is not supported when the model is quantized on the fly. " + "Please use a quantized checkpoint or remove the CPU or disk device from the device_map." + ) + + def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype": + if dtype != torch.bfloat16: + logger.warning_once( + f"Setting dtype to {dtype}, but only bfloat16 is supported right now. Overwriting torch_dtype to bfloat16." + ) + dtype = torch.bfloat16 + return dtype + + def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool: + from ..integrations import FbgemmFp8Linear, FbgemmFp8Llama4TextExperts + + module, tensor_name = get_module_from_name(model, param_name) + + if isinstance(module, FbgemmFp8Linear): + if self.pre_quantized or tensor_name == "bias": + return False + else: + return True + if isinstance(module, FbgemmFp8Llama4TextExperts): + if self.pre_quantized or tensor_name == "bias": + return False + else: + return True + return False + + def param_element_size(self, model: "PreTrainedModel", param_name: str, param: "torch.Tensor") -> float: + "Return the element size (in bytes) for `param_name`." + if self.param_needs_quantization(model, param_name): + # 8 bit, this is neeed as when `pre_quantized`` is False, we don't set the dtype of the FP8Linear in order to correctly load the weights + return 1 + return super().param_element_size(model, param_name, param) + + def _process_model_before_weight_loading( + self, + model: "PreTrainedModel", + **kwargs, + ): + from ..integrations import replace_with_fbgemm_fp8_linear + + self.modules_to_not_convert = self.get_modules_to_not_convert( + model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules + ) + + model = replace_with_fbgemm_fp8_linear( + model, + modules_to_not_convert=self.modules_to_not_convert, + quantization_config=self.quantization_config, + pre_quantized=self.pre_quantized, + tp_plan=model._tp_plan, + ) + + def _process_model_after_weight_loading(self, model, **kwargs): + """ + Force update the input scale upper bound after weight loading and device dispatch are complete. + This resolves issues where persistent buffers are zeroed out or overwritten during the loading process. + """ + from ..integrations.fbgemm_fp8 import FbgemmFp8Linear, FbgemmFp8Llama4TextExperts + + for m in model.modules(): + if isinstance(m, (FbgemmFp8Linear, FbgemmFp8Llama4TextExperts)): + if hasattr(m, "input_scale_ub"): + # The model is now on the target device, so we can use fill_ directly. + m.input_scale_ub.fill_(self.quantization_config.activation_scale_ub) + return model + + def update_tp_plan(self, config): + if "Llama4" in config.__class__.__name__: + text_plan = { + # We are using a different tp plan with local_colwise and local_rowwise for the attention because fbgemm operations cannot be parallelized + # With local_colwise and local_rowwise, all the operations are done locally, and we add a gather operation to gather the results instead of + # using dtensors + "layers.*.self_attn.q_proj.weight": "colwise", + "layers.*.self_attn.q_proj.weight_scale": "colwise", + "layers.*.self_attn.k_proj.weight": "colwise", + "layers.*.self_attn.k_proj.weight_scale": "colwise", + "layers.*.self_attn.v_proj.weight": "colwise", + "layers.*.self_attn.v_proj.weight_scale": "colwise", + "layers.*.self_attn.o_proj.weight": "rowwise", + # We keep the same sequence_parallel plan for layernorms + "layers.*.input_layernorm.weight": "sequence_parallel", + "layers.*.post_attention_layernorm.weight": "sequence_parallel", + "norm.weight": "sequence_parallel", + # We keep the same local_colwise and local_rowwise plan for the feed forward shared expert + # We also add scales for the shared expert, for local_colwise the scale is also local_colwise + # For local_rowwise the scale is replicated, so we don't need to add it + "layers.*.feed_forward.shared_expert.gate_proj.weight": "colwise", + "layers.*.feed_forward.shared_expert.gate_proj.weight_scale": "colwise", + "layers.*.feed_forward.shared_expert.up_proj.weight": "colwise", + "layers.*.feed_forward.shared_expert.up_proj.weight_scale": "colwise", + "layers.*.feed_forward.shared_expert.down_proj.weight": "rowwise", + "layers.*.feed_forward.experts.*.gate_proj.weight": "colwise", + "layers.*.feed_forward.experts.*.gate_proj.weight_scale": "colwise", + "layers.*.feed_forward.experts.*.up_proj.weight": "colwise", + "layers.*.feed_forward.experts.*.up_proj.weight_scale": "colwise", + "layers.*.feed_forward.experts.*.down_proj.weight": "rowwise", + # For Fused implementation we use local_packed_rowwise for the gate_up_proj, and the same for the packed scales + # We use local_colwise for the down_proj, and the scales are replicated so we don't add them + "layers.*.feed_forward.experts.gate_up_proj": "packed_rowwise", + "layers.*.feed_forward.experts.gate_up_proj_scale": "packed_rowwise", + "layers.*.feed_forward.experts.down_proj": "colwise", + } + if config.get_text_config() is not None: + config.get_text_config().base_model_tp_plan = text_plan + else: + config.base_model_tp_plan = text_plan + return config + + return config + + def is_serializable(self): + return True + + @property + def is_trainable(self) -> bool: + return False + + def get_quantize_ops(self): + from ..integrations.fbgemm_fp8 import FbgemmFp8Quantize + + return FbgemmFp8Quantize(self) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_finegrained_fp8.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_finegrained_fp8.py new file mode 100644 index 0000000000000000000000000000000000000000..be10624d4842b189420de294cadf42660153a0f6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_finegrained_fp8.py @@ -0,0 +1,226 @@ +from typing import TYPE_CHECKING + +from ..utils import is_accelerate_available, is_torch_available, is_torch_xpu_available, logging +from .base import HfQuantizer +from .quantizers_utils import get_module_from_name + + +if is_torch_available(): + import torch + +if TYPE_CHECKING: + from ..modeling_utils import PreTrainedModel + from ..utils.quantization_config import FineGrainedFP8Config + +logger = logging.get_logger(__name__) + + +class FineGrainedFP8HfQuantizer(HfQuantizer): + """ + FP8 quantization implementation supporting both standard and MoE models. + Supports both e4m3fn formats based on platform. + """ + + requires_calibration = False + quantization_config: "FineGrainedFP8Config" + + def __init__(self, quantization_config, **kwargs): + super().__init__(quantization_config, **kwargs) + + def validate_environment(self, *args, **kwargs): + if not is_accelerate_available(): + raise ImportError("Loading an FP8 quantized model requires accelerate (`pip install accelerate`)") + + if self.quantization_config.dequantize: + return + + if not torch.cuda.is_available() and not is_torch_xpu_available(): + if self.pre_quantized: + logger.warning_once( + "Using FP8 quantized models requires a GPU or XPU, we will default to dequantizing the model to bf16 since no GPU or XPU is available" + ) + self.quantization_config.dequantize = True + return + else: + raise RuntimeError("No GPU or XPU found. A GPU or XPU is needed for FP8 quantization.") + + if torch.cuda.is_available(): + compute_capability = torch.cuda.get_device_capability() + major, minor = compute_capability + if (major < 8) or (major == 8 and minor < 9): + logger.warning_once( + "FP8 quantized models is only supported on GPUs with compute capability >= 8.9 (e.g 4090/H100)" + f", actual = `{major}.{minor}`. We will default to dequantizing the model to bf16. Feel free " + f"to use a different quantization method like bitsandbytes or torchao" + ) + self.quantization_config.dequantize = True + return + + device_map = kwargs.get("device_map") + if device_map is None: + logger.warning_once( + "You have loaded an FP8 model on CPU and have a CUDA or XPU device available, make sure to set " + "your model on a GPU or XPU device in order to run your model. To remove this warning, " + "pass device_map = 'cuda' or 'xpu'. " + ) + elif isinstance(device_map, dict): + if ( + not self.pre_quantized + and len(device_map) > 1 + and "cpu" in device_map.values() + or "disk" in device_map.values() + ): + raise ValueError( + "You are attempting to load an FP8 model with a device_map that contains a cpu/disk device." + "This is not supported when the model is quantized on the fly. " + "Please use a quantized checkpoint or remove the cpu/disk device from the device_map." + ) + + def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool: + from ..integrations.finegrained_fp8 import FP8Experts, FP8Linear + + module, tensor_name = get_module_from_name(model, param_name) + if isinstance(module, (FP8Linear, FP8Experts)): + if self.pre_quantized or tensor_name == "bias": + return False + else: + return True + return False + + def param_element_size(self, model: "PreTrainedModel", param_name: str, param: "torch.Tensor") -> float: + "Return the element size (in bytes) for `param_name`." + if self.param_needs_quantization(model, param_name): + # 8 bit, this is neeed as when `pre_quantized`` is False, we don't set the dtype of the FP8Linear in order to correctly load the weights + return 1 + return super().param_element_size(model, param_name, param) + + def _process_model_before_weight_loading( + self, + model: "PreTrainedModel", + **kwargs, + ): + from ..integrations.finegrained_fp8 import replace_with_fp8_linear + + self.modules_to_not_convert = self.get_modules_to_not_convert( + model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules + ) + + model = replace_with_fp8_linear( + model, + modules_to_not_convert=self.modules_to_not_convert, + quantization_config=self.quantization_config, + pre_quantized=self.pre_quantized, + ) + + def update_tp_plan(self, config): + if "Qwen3" in config.__class__.__name__: + text_plan = { + "layers.*.self_attn.q_proj.weight": "colwise", + "layers.*.self_attn.q_proj.weight_scale_inv": "colwise", + "layers.*.self_attn.k_proj.weight": "colwise", + "layers.*.self_attn.k_proj.weight_scale_inv": "colwise", + "layers.*.self_attn.v_proj.weight": "colwise", + "layers.*.self_attn.v_proj.weight_scale_inv": "colwise", + "layers.*.self_attn.o_proj.weight": "rowwise", + "layers.*.self_attn.o_proj.weight_scale_inv": "rowwise", + "layers.*.mlp.gate_proj.weight": "colwise", + "layers.*.mlp.gate_proj.weight_scale_inv": "colwise", + "layers.*.mlp.up_proj.weight": "colwise", + "layers.*.mlp.up_proj.weight_scale_inv": "colwise", + "layers.*.mlp.down_proj.weight": "rowwise", + "layers.*.mlp.down_proj.weight_scale_inv": "rowwise", + } + + config.base_model_tp_plan = text_plan + + return config + + def is_serializable(self): + return True + + @property + def is_trainable(self) -> bool: + return False + + @property + def is_compileable(self) -> bool: + return True + + def get_quantize_ops(self): + from ..integrations.finegrained_fp8 import Fp8Quantize + + return Fp8Quantize(self) + + def get_weight_conversions(self): + from ..core_model_loading import WeightConverter + from ..integrations.finegrained_fp8 import Fp8Dequantize + + if self.pre_quantized and self.quantization_config.dequantize: + return [ + # either use the dollar sign, or permute the source patterns to start matching against the scales first + # We also collect the activation scales, they will not be used + WeightConverter( + source_patterns=["weight$", "weight_scale_inv", "activation_scale"], + target_patterns="weight", + operations=[Fp8Dequantize(self)], + ) + ] + return [] + + def update_weight_conversions(self, weight_conversions): + """When loading with ``dequantize=True``, attach an :class:`Fp8Dequantize` op to + every existing :class:`WeightConverter` so that per-block scales are folded into + the weight *before* any later merge/concat ops collapse the per-expert structure. + + For each model-supplied converter that has a ``.weight`` source, we: + 1. anchor the existing weight patterns with ``$`` so they don't accidentally + also match the ``.weight_scale_inv`` keys (the regex is searched, so the + unanchored prefix would match both, sending scales to the wrong bucket); + 2. add anchored ``*.weight_scale_inv`` sources next to each weight pattern so + the loader collects scale tensors alongside the weight tensors into the + *same* converter bucket (both keys rewrite to the same target); + 3. prepend a fresh :class:`Fp8Dequantize` op so dequant runs first, before + any merge/concat collapses the per-expert structure. + + The generic ``weight$ + weight_scale_inv → weight`` converter from + :meth:`get_weight_conversions` is still appended at the end as a fallback for + plain ``nn.Linear`` weights with no model-specific converter. + """ + if not (self.pre_quantized and self.quantization_config.dequantize): + return weight_conversions + self.get_weight_conversions() + + from ..core_model_loading import WeightConverter, WeightRenaming + from ..integrations.finegrained_fp8 import Fp8Dequantize + + # Some upstream FP8 checkpoints (e.g. DeepSeek-V4-Flash) ship per-block scales + # under a ``.scale`` suffix instead of HF's canonical ``.weight_scale_inv``. + # Prepending the rename here (instead of in each model's conversion_mapping) + # keeps the model-side mapping clean — the rename only kicks in when FP8 dequant + # is actually active, so a non-FP8 save / load round-trip doesn't see a stray + # rule that ``test_reverse_loading_mapping`` can't match. + scale_rename = WeightRenaming(source_patterns=r"^(.+)\.scale$", target_patterns=r"\1.weight_scale_inv") + weight_conversions = [scale_rename] + list(weight_conversions) + + updated: list = [] + for conv in weight_conversions: + # Only WeightConverter has ``.operations`` to extend with the dequant op; + # WeightRenaming (e.g. the ``scale_rename`` we prepended) just passes through. + if not isinstance(conv, WeightConverter): + updated.append(conv) + continue + weight_sources = [p for p in conv.source_patterns if p.endswith(".weight")] + if weight_sources: + anchored_weight = [p + "$" for p in weight_sources] + scale_sources = [p[: -len(".weight")] + ".weight_scale_inv$" for p in weight_sources] + other = [p for p in conv.source_patterns if not p.endswith(".weight")] + new_sources = anchored_weight + scale_sources + other + new_ops = [Fp8Dequantize(self)] + list(conv.operations) + conv = WeightConverter( + source_patterns=new_sources, + target_patterns=conv._original_target_patterns, + operations=new_ops, + ) + updated.append(conv) + # Generic fallback for plain ``nn.Linear`` weights with no model-specific converter. + updated.extend(self.get_weight_conversions()) + return updated diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_fouroversix.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_fouroversix.py new file mode 100644 index 0000000000000000000000000000000000000000..79acb8cbb2161a9545229252270b53eaab99b9cf --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_fouroversix.py @@ -0,0 +1,123 @@ +from typing import TYPE_CHECKING + +from ..utils.import_utils import is_fouroversix_available +from .base import HfQuantizer +from .quantizers_utils import get_module_from_name + + +if TYPE_CHECKING: + from ..modeling_utils import PreTrainedModel + from ..utils.quantization_config import FourOverSixConfig + +from ..utils import ( + is_torch_available, +) + + +if is_torch_available(): + import torch + + +class FourOverSixHfQuantizer(HfQuantizer): + """ + FP4 quantization with fouroversix. + """ + + requires_calibration = False + quantization_config: "FourOverSixConfig" + + def __init__(self, quantization_config, **kwargs): + super().__init__(quantization_config, **kwargs) + + def validate_environment(self, *args, **kwargs): + if not is_fouroversix_available(): + raise ImportError( + "Using `fouroversix` requires fouroversix: `pip install fouroversix --no-build-isolation`" + ) + + def param_element_size( + self, + model: "PreTrainedModel", + param_name: str, + param: "torch.Tensor", + ) -> float: + from fouroversix import QuantizedModule + + module, tensor_name = get_module_from_name(model, param_name) + + if QuantizedModule.is_quantized_module_type(type(module)): + return module.get_element_size(tensor_name) + + return super().param_element_size(model, param_name, param) + + def param_needs_quantization( + self, + model: "PreTrainedModel", + param_name: str, + **kwargs, + ) -> bool: + from fouroversix import QuantizedModule + + module, tensor_name = get_module_from_name(model, param_name) + + return QuantizedModule.is_quantized_module_type(type(module)) and tensor_name in module.parameters_to_quantize + + def _process_model_before_weight_loading( + self, + model: "PreTrainedModel", + device_map, + **kwargs, + ): + from fouroversix import QuantizedModule, quantize_model + + from ..integrations.fouroversix import adapt_fouroversix_config + + quantize_model( + model, + adapt_fouroversix_config(self.quantization_config), + ) + + # If the model has already been quantized, we need to delete the weight tensor here so that + # it's not expected when parameters are loaded from the checkpoint. + if self.pre_quantized and not self.quantization_config.keep_master_weights: + for _, module in model.named_modules(): + if QuantizedModule.is_quantized_module_type(type(module)): + for parameter_name in module.parameters_to_quantize: + delattr(module, parameter_name) + + def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs): + return model + + def is_serializable(self): + return True + + @property + def is_trainable(self) -> bool: + return self.quantization_config.keep_master_weights + + def get_quantize_ops(self): + from ..integrations.fouroversix import FourOverSixQuantize + + return FourOverSixQuantize(self) + + def get_weight_conversions(self): + """ + Return weight conversions for loading pre-quantized checkpoints of + other pre-quantized models (not fouroversix models). After first use, + the pre_quantized_model_config_type attribute is set to None to ensure + subsequent calls (e.g., during save_pretrained) return an empty list + since, by then, the model will be saved with our framework's format + so weight conversions are no longer needed. + """ + from fouroversix import WeightConversions + + # pre_quantized_model_config_type is only set if we are loading a + # pre-quantized model so it is not guaranteed to exist. + if hasattr(self.quantization_config, "pre_quantized_model_config_type"): + model_config_type = self.quantization_config.pre_quantized_model_config_type + weight_conversions = WeightConversions.get_weight_conversions( + model_config_type, + ) + return weight_conversions + + return [] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_fp_quant.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_fp_quant.py new file mode 100644 index 0000000000000000000000000000000000000000..c367b957d206fed69a361f11bd42b8e429bda5e5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_fp_quant.py @@ -0,0 +1,164 @@ +# Copyright 2025 The HuggingFace Inc. team. All rights reserved. +# +# 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. +from typing import TYPE_CHECKING, Optional + +from .base import HfQuantizer +from .quantizers_utils import get_module_from_name + + +if TYPE_CHECKING: + from ..modeling_utils import PreTrainedModel + from ..utils.quantization_config import FPQuantConfig + +from ..utils import is_fp_quant_available, is_qutlass_available, is_torch_available, is_torch_xpu_available, logging +from ..utils.quantization_config import QuantizationConfigMixin + + +if is_torch_available(): + import torch + +logger = logging.get_logger(__name__) + + +class FPQuantHfQuantizer(HfQuantizer): + """ + Quantizer for the FP-Quant method. Enables the loading of prequantized models and in-flight quantization of full-precision models. + """ + + requires_calibration = False + is_qat_trainable = True + quantization_config: "FPQuantConfig" + + def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs): + super().__init__(quantization_config, **kwargs) + + def validate_environment(self, device_map, **kwargs): + if not torch.cuda.is_available() and not is_torch_xpu_available(): + raise NotImplementedError( + "FPQuant quantization is only supported on GPU or Intel XPU. Please use a different quantizer." + ) + + if not is_qutlass_available() and not self.quantization_config.pseudoquantization: + raise ImportError( + "Using `fp_quant` with real quantization requires a **Blackwell GPU** and qutlass: `git clone https://github.com/IST-DASLab/qutlass.git && cd qutlass && pip install --no-build-isolation .`. You can use `FPQuantConfig(pseudoquantization=True, ...)` to use Triton-based pseudo-quantization. It doesn't provide any speedups but emulates the quantization behavior of the real quantization." + ) + + if ( + self.quantization_config.pseudoquantization + and self.quantization_config.forward_dtype == "nvfp4" + and torch.cuda.is_available() + and torch.cuda.get_device_capability()[0] < 9 + ): + raise ValueError( + "NVFP4 pseudoquantization requires a GPU with compute capability >= 9.0 (Hopper or newer) " + "because the Triton kernel uses the `fp8e4nv` type. Please use `forward_dtype='mxfp4'` instead, " + "or use a GPU with compute capability >= 9.0." + ) + + if self.quantization_config.pseudoquantization: + logger.warning( + "Using pseudo-quantization for FP-Quant. This doesn't provide any speedups but emulates the quantization behavior of the real quantization." + ) + + if not is_fp_quant_available(): + raise ImportError("Using `fp_quant` quantization requires fp_quant: `pip install fp_quant`") + + if device_map is None and not self.quantization_config.pseudoquantization: + raise ValueError( + "You are attempting to load a FPQuant model without setting device_map." + " Please set device_map comprised of 'cuda' devices." + ) + elif isinstance(device_map, dict): + if ( + not self.quantization_config.pseudoquantization + and len(device_map) > 1 + and "cpu" in device_map.values() + or "disk" in device_map.values() + ): + raise ValueError( + "You are attempting to load a FPQuant model with a device_map that contains a CPU or disk device." + " This is not supported. Please remove the CPU or disk device from the device_map." + ) + + def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype": + if dtype != torch.bfloat16: + logger.warning_once( + f"Setting dtype to {dtype}, but only bfloat16 is supported right now. Overwriting torch_dtype to bfloat16." + ) + dtype = torch.bfloat16 + return dtype + + def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool: + from fp_quant import FPQuantLinear + + module, tensor_name = get_module_from_name(model, param_name) + if isinstance(module, FPQuantLinear) and tensor_name in ["weight", "qweight", "dqweight"]: + # Only quantize weights of FPQuantLinear modules that are not already quantized + return True + else: + return False + + def _process_model_before_weight_loading( + self, + model: "PreTrainedModel", + **kwargs, + ): + from fp_quant import replace_with_fp_quant_linear + + from ..integrations.fp_quant import adapt_fp_quant_config + + replace_with_fp_quant_linear( + model, + fp_quant_linear_config=adapt_fp_quant_config(self.quantization_config), + ) + + @property + def is_trainable(self, model: Optional["PreTrainedModel"] = None): + trainable = self.quantization_config.store_master_weights + if not trainable: + logger.warning( + "You are attempting to train a model with FPQuant quantization. This is only supported when `store_master_weights=True`. Please set `store_master_weights=True` to train the model." + ) + return trainable + + def is_serializable(self): + return True + + def get_quantize_ops(self): + from ..integrations.fp_quant import FpQuantQuantize + + return FpQuantQuantize(self) + + def get_weight_conversions(self): + from ..core_model_loading import WeightConverter + from ..integrations.fp_quant import FpQuantDeserialize + + if self.pre_quantized: + if self.quantization_config.pseudoquantization: + return [ + WeightConverter( + source_patterns=[".dqweight"], + target_patterns=".dqweight", + operations=[FpQuantDeserialize(self)], + ), + ] + else: + return [ + WeightConverter( + source_patterns=[".qweight"], + target_patterns=".qweight", + operations=[FpQuantDeserialize(self)], + ), + ] + return [] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_gptq.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_gptq.py new file mode 100644 index 0000000000000000000000000000000000000000..f018704f494931d5c30f66d695d8ff96bacfc5d0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_gptq.py @@ -0,0 +1,111 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# 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. +from importlib import metadata +from typing import TYPE_CHECKING + +from packaging import version + +from .base import HfQuantizer + + +if TYPE_CHECKING: + from ..modeling_utils import PreTrainedModel + +from ..utils import is_gptqmodel_available, is_optimum_available, is_torch_available, logging +from ..utils.quantization_config import GPTQConfig, QuantizationConfigMixin + + +if is_torch_available(): + import torch + +logger = logging.get_logger(__name__) + + +MIN_GPTQ_VERSION = "1.4.3" +MIN_OPTIMUM_VERSION = "1.24.0" + + +class GptqHfQuantizer(HfQuantizer): + """ + Quantizer of the GPTQ method - for GPTQ the quantizer support calibration of the model through + the GPT-QModel package (Python import name `gptqmodel`). Quantization is done under the hood for users if they + load a non-prequantized model. + """ + + requires_calibration = False + quantization_config: "GPTQConfig" + + def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs): + super().__init__(quantization_config, **kwargs) + + if not is_optimum_available(): + raise ImportError("Loading a GPTQ quantized model requires optimum (`pip install optimum`)") + from optimum.gptq import GPTQQuantizer + + self.optimum_quantizer = GPTQQuantizer.from_dict(self.quantization_config.to_dict_optimum()) + + def validate_environment(self, *args, **kwargs): + if not is_optimum_available(): + raise ImportError("Loading a GPTQ quantized model requires optimum (`pip install optimum`)") + + gptq_supports_cpu = is_gptqmodel_available() + if not gptq_supports_cpu and not torch.cuda.is_available(): + raise RuntimeError("GPU is required to quantize or run quantize model.") + elif not is_gptqmodel_available(): + raise ImportError("Loading a GPTQ quantized model requires gptqmodel (`pip install gptqmodel`) library.") + elif is_gptqmodel_available() and ( + version.parse(metadata.version("gptqmodel")) < version.parse(MIN_GPTQ_VERSION) + or version.parse(metadata.version("optimum")) < version.parse(MIN_OPTIMUM_VERSION) + ): + raise ImportError( + f"The gptqmodel version should be >= {MIN_GPTQ_VERSION}, optimum version should >= {MIN_OPTIMUM_VERSION}" + ) + + def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype": + if dtype != torch.float16: + logger.info("We suggest you to set `dtype=torch.float16` for better efficiency with GPTQ.") + return dtype + + def update_device_map(self, device_map): + if device_map is None: + device_map = {"": torch.device("cpu")} + return device_map + + def _process_model_before_weight_loading(self, model: "PreTrainedModel", **kwargs): + if model.__class__.main_input_name != "input_ids": + raise RuntimeError("We can only quantize pure text model.") + + if self.pre_quantized: + # compat: latest optimum has gptqmodel refactor + if version.parse(metadata.version("optimum")) < version.parse(MIN_OPTIMUM_VERSION): + model = self.optimum_quantizer.convert_model(model) + else: + model = self.optimum_quantizer.convert_model(model, **kwargs) + + def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs): + if self.pre_quantized: + model = self.optimum_quantizer.post_init_model(model) + else: + if self.quantization_config.tokenizer is None: + self.quantization_config.tokenizer = model.name_or_path + + self.optimum_quantizer.quantize_model(model, self.quantization_config.tokenizer) + model.config.quantization_config = GPTQConfig.from_dict(self.optimum_quantizer.to_dict()) + + @property + def is_trainable(self) -> bool: + return True + + def is_serializable(self): + return True diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_higgs.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_higgs.py new file mode 100644 index 0000000000000000000000000000000000000000..78d168aab59c2b097c17df6fcfb60483385eeeb0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_higgs.py @@ -0,0 +1,178 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# 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. +from typing import TYPE_CHECKING + +from ..utils.logging import tqdm +from .base import HfQuantizer +from .quantizers_utils import get_module_from_name + + +if TYPE_CHECKING: + from ..modeling_utils import PreTrainedModel + from ..utils.quantization_config import HiggsConfig + +from ..utils import is_accelerate_available, is_flute_available, is_hadamard_available, is_torch_available, logging +from ..utils.quantization_config import QuantizationConfigMixin + + +if is_torch_available(): + import torch + +logger = logging.get_logger(__name__) + + +class HiggsHfQuantizer(HfQuantizer): + """ + Quantizer of the HIGGS method. Enables the loading of prequantized models and in-flight quantization of full-precision models. + """ + + requires_calibration = False + quantization_config: "HiggsConfig" + + def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs): + super().__init__(quantization_config, **kwargs) + + def validate_environment(self, device_map, **kwargs): + if not torch.cuda.is_available(): + raise NotImplementedError("HIGGS quantization is only supported on GPU. Please use a different quantizer.") + + if not is_accelerate_available(): + raise ImportError("Using `higgs` quantization requires Accelerate: `pip install accelerate`") + + if not is_flute_available(): + raise ImportError("Using `higgs` quantization requires FLUTE: `pip install flute-kernel>=0.3.0`") + + if not is_hadamard_available(): + raise ImportError( + "Using `higgs` quantization requires fast_hadamard_transform: `pip install fast_hadamard_transform`" + ) + + if device_map is None: + raise ValueError( + "You are attempting to load a HIGGS model without setting device_map." + " Please set device_map comprised of 'cuda' devices." + ) + elif isinstance(device_map, dict): + if "cpu" in device_map.values() or "disk" in device_map.values(): + raise ValueError( + "You are attempting to load a HIGGS model with a device_map that contains a CPU or disk device." + " This is not supported. Please remove the CPU or disk device from the device_map." + ) + + def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype": + if dtype != torch.float16 and dtype != torch.bfloat16: + raise ValueError( + f"Invalid `dtype` {dtype}. HIGGS quantization only supports `dtype=torch.float16` or `dtype=torch.bfloat16`." + ) + + return dtype + + # TODO: to remove + # Kept here in case we see some interest in adding support for it + # def create_quantized_param( + # self, + # model: "PreTrainedModel", + # param_value: "torch.Tensor", + # param_name: str, + # target_device: "torch.device", + # **kwargs, + # ): + # from ..integrations import quantize_with_higgs + + # flute_dict = quantize_with_higgs( + # param_value.to(target_device), + # self.quantization_config.bits, + # self.quantization_config.p, + # self.quantization_config.group_size, + # self.quantization_config.hadamard_size, + # ) + # del param_value + + # module, _ = get_module_from_name(model, param_name) + # module_name = ".".join(param_name.split(".")[:-1]) + # for key, value in flute_dict.items(): + # if key in module._parameters: + # module._parameters[key] = torch.nn.Parameter(value, requires_grad=False) + # elif key in module._buffers: + # module._buffers[key] = torch.nn.Buffer(value) + # elif key == "tune_metadata": + # module.tune_metadata = value + # self.quantization_config.tune_metadata[module_name] = value.to_dict() + # else: + # raise ValueError(f"Unexpected key {key} in module {module}") + + def _process_model_before_weight_loading( + self, + model: "PreTrainedModel", + **kwargs, + ): + from ..integrations import replace_with_higgs_linear + + self.modules_to_not_convert = self.get_modules_to_not_convert( + model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules + ) + + replace_with_higgs_linear( + model, + quantization_config=self.quantization_config, + modules_to_not_convert=self.modules_to_not_convert, + ) + + def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs): + from flute.tune import TuneMetaData, maybe_tune_and_repack + from flute.utils import make_workspace_streamk + + from ..integrations import HiggsLinear + + flute_workspaces = {} + flute_modules = {name: module for name, module in model.named_modules() if isinstance(module, HiggsLinear)} + for name, module in tqdm(flute_modules.items(), desc="Repacking HIGGS modules", leave=False): + # Every HiggsLinear needs a "workspace": a buffer for the unpacking operation. + # This buffer needs to be on the same device as the weights, but can be reused across modules otherwise. + if module.weight.device not in flute_workspaces: + flute_workspaces[module.weight.device] = make_workspace_streamk(device=module.weight.device) + module.workspace = flute_workspaces[module.weight.device] + + # FLUTE weights are packed in a way that is optimized for a specific number of SMs (GPU streaming multiprocessors). + # If the model is loaded on a different device than the one it was saved on, we need to repack the weights. + module.tune_metadata = TuneMetaData.from_dict(self.quantization_config.tune_metadata[name]) + module.weight.data, module.tune_metadata = maybe_tune_and_repack( + weight=module.weight.data, + scales=module.scales.data, + metadata=module.tune_metadata, + ) + self.quantization_config.tune_metadata[name] = module.tune_metadata.to_dict() + + @property + def is_trainable(self) -> bool: + return False + + def is_serializable(self): + return True + + def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool: + from ..integrations import HiggsLinear + + module, tensor_name = get_module_from_name(model, param_name) + if isinstance(module, HiggsLinear) and tensor_name == "weight": + # Only quantize weights of HiggsLinear modules that are not already quantized + return True + else: + return False + + def _dequantize(self, model): + from ..integrations import dequantize_higgs + + model = dequantize_higgs(model) + return model diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_hqq.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_hqq.py new file mode 100644 index 0000000000000000000000000000000000000000..05dce3d996a0693a9db2349cbc5079f3aff52cd6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_hqq.py @@ -0,0 +1,264 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# 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. + +from typing import TYPE_CHECKING + +from ..integrations import prepare_for_hqq_linear +from ..utils import is_hqq_available, is_torch_available, logging +from .base import HfQuantizer +from .quantizers_utils import get_module_from_name + + +if TYPE_CHECKING: + from ..modeling_utils import PreTrainedModel + from ..utils.quantization_config import HqqConfig + + +if is_torch_available(): + import torch + +if is_hqq_available(): + from hqq.core.quantize import HQQLinear + + # This is a compatibility hack. HQQ-quantized linear layers do not have a `weight` attribute, + # but some models attempt to access `weight.dtype` during the forward pass. To prevent runtime errors, + # we patch HQQLinear with a dummy `weight` property that returns an empty tensor with the correct dtype and device. + @property + def weight(self): + return torch.empty(0, dtype=self.compute_dtype, device=self.device) + + HQQLinear.weight = weight + +logger = logging.get_logger(__name__) + + +class HqqHfQuantizer(HfQuantizer): + """ + HQQ quantizer base HF class. + nn.Linear modules are first tagged with quant_config in _process_model_before_weight_loading(). + """ + + requires_calibration = False + quantization_config: "HqqConfig" + + def __init__(self, quantization_config, **kwargs): + if not is_hqq_available(): + raise ImportError( + "A valid HQQ version (>=0.2.1) is not available. Please follow the instructions to install it: `https://github.com/mobiusml/hqq/`." + ) + super().__init__(quantization_config, **kwargs) + self.dtype = None + self.using_multi_gpu = False + # Keys that are serialized specifically by hqq + self.hqq_keys = HQQLinear(None, None).state_dict_keys() - {"bias"} + + def validate_environment(self, *args, **kwargs): + if self.dtype is None: + if "dtype" in kwargs: + self.dtype = kwargs["dtype"] + else: + self.dtype = torch.float32 + logger.info("Setting dtype to torch.float32 as the default value since it was not specified.") + + device_map = kwargs.get("device_map") + if isinstance(device_map, dict): + if "cpu" in device_map.values() or "disk" in device_map.values(): + raise ValueError( + "You are attempting to use an HQQ model with a device_map that contains a CPU or disk device." + " This is not supported. Please remove the CPU or disk device from the device_map." + ) + else: + self.using_multi_gpu = len(set(device_map.values())) > 1 + + # TODO: to remove + # Kept here in case we see some interest in adding support for it + # # Adds missing keys for HQQLinear modules that are loaded but the model with initialized with torch.nn.Linear + # def update_expected_keys( + # self, model: "PreTrainedModel", expected_keys: list[str], loaded_keys: list[str] + # ) -> list[str]: + # if not self.pre_quantized: + # return expected_keys + + # # Collects all quantizable (linear) layers + # def _find_hqq_quantizable_layers(model, layers): + # for name, module in model.named_children(): + # if isinstance(module, (torch.nn.Linear)): + # layers.add(module.name) + # _find_hqq_quantizable_layers(module, layers) + + # new_keys = set(expected_keys) + + # # Name modules + # for name, module in model.named_modules(): + # module.name = name + + # # valid modules are Linear layers that have HQQLinear state_dict. We ignore skip_modules and any layers with Linear state_dict() params + # _valid_modules = set() + # _find_hqq_quantizable_layers(model, _valid_modules) + + # # Remove skipped modules + # _skipped_modules = set() + # for _module in _valid_modules: + # for _skip_module in model.config.quantization_config["skip_modules"]: + # if _skip_module in _module: + # _skipped_modules.add(_module) + # _valid_modules -= _skipped_modules + + # # Append new expected layers based on _ref_keys + # _ref_keys = HQQLinear( + # linear_layer=None, + # quant_config=None, + # compute_dtype=torch.float16, + # device="cpu", + # del_orig=False, + # ).state_dict_keys() - {"bias"} + + # # Clean-up + # _rm_keys = set() + # for key in new_keys: + # if any(_module in key for _module in _valid_modules): + # _rm_keys.add(key) + # new_keys -= _rm_keys + # # At this point, new_keys contains all the keys of the layers that are NOT HQQLinear or torch.nn.Linear + + # # Re-populate Linear/HQQLinear + # for _module in _valid_modules: + # if _module + ".weight" in loaded_keys: + # new_keys.add(_module + ".weight") + # else: + # new_keys.update({_module + "." + _ref_key for _ref_key in _ref_keys}) + # if _module + ".bias" in loaded_keys: + # new_keys.add(_module + ".bias") + + # return list(new_keys) + + def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool: + module, _ = get_module_from_name(model, param_name) + # Since we do not prepare the modules in advance, we need every param of the Linear layer to go through + # `create_quantized_param`, even when `self.is_quantized == True` + return isinstance(module, torch.nn.Linear) + + # TODO: to remove + # def create_quantized_param( + # self, + # model: "PreTrainedModel", + # param_value: "torch.Tensor", + # param_name: str, + # target_device: "torch.device", + # **kwargs, + # ): + # module, tensor_name = get_module_from_name(model, param_name) + # module_name = param_name.rsplit(".", 1)[0] + # parent_module, node = get_module_from_name(model, module_name) + + # quant_config = model.config.quantization_config["quant_config"] + # skip_modules = model.config.quantization_config["skip_modules"] + + # # In this case we do not quantize this layer (it's explicitly skipped) -> simply load param + # if any(skip_module in module.name for skip_module in skip_modules): + # module.load_state_dict( + # {tensor_name: param_value.to(device=target_device, dtype=self.dtype)}, strict=False, assign=True + # ) + # return + + # # We need this hack as the model is not pre-prepared as an empty skeleton on meta device + # if self.pre_quantized: + # # Save them for later + # if not hasattr(self, "hqq_params"): + # self.hqq_params = defaultdict(dict) + # self.hqq_params[module_name].update({tensor_name: param_value}) + # hqq_params = self.hqq_params[module_name] + + # # If they are all present and saved, make it a HQQLinear layer! (we cannot do it param after param because + # # hqq does not support it...) + # if all(k in hqq_params for k in self.hqq_keys) and ("bias" in hqq_params or module.bias is None): + # hqq_layer = HQQLinear( + # linear_layer=None, + # quant_config=None, + # compute_dtype=self.dtype, + # device=target_device, + # del_orig=False, + # ) + # hqq_layer.load_state_dict(hqq_params) + + # if hqq_layer.bias is not None and isinstance(hqq_layer.bias, torch.Tensor): + # hqq_layer.bias = torch.nn.Parameter(hqq_layer.bias) + # if self.using_multi_gpu: + # hqq_layer = self._patch_layer_for_multigpu(hqq_layer) + + # setattr(parent_module, node, hqq_layer) + # del self.hqq_params[module_name], module + # return + + # # Load param in the module (without caring about device or dtype, it will be changed later) + # module.load_state_dict({tensor_name: param_value}, strict=False, assign=True) + + # # If both the weight and bias have already been loaded, time to quantize! + # module_is_ready = module.weight.device.type != "meta" and ( + # module.bias is None or module.bias.device.type != "meta" + # ) + + # if module_is_ready: + # module_tag = ".".join(module.name.split(".")[-2:]) + # if "weight_quant_params" in quant_config: + # module_quant_config = quant_config + # elif module_tag in quant_config: + # module_quant_config = quant_config[module_tag] + + # hqq_layer = HQQLinear( + # module, + # quant_config=module_quant_config, + # compute_dtype=self.dtype, + # device=target_device, + # del_orig=True, + # ) + + # if hqq_layer.bias is not None and isinstance(hqq_layer.bias, torch.Tensor): + # hqq_layer.bias = torch.nn.Parameter(hqq_layer.bias) + + # if self.using_multi_gpu: + # hqq_layer = self._patch_layer_for_multigpu(hqq_layer) + + # setattr(parent_module, node, hqq_layer) + + def _patch_layer_for_multigpu(self, hqq_layer): + def forward_with_device(self, x): + out = torch.matmul(x.to(self.device), self.dequantize().t()) + if self.bias is not None: + out += self.bias + return out + + hqq_layer.forward = lambda x: forward_with_device(hqq_layer, x) + return hqq_layer + + def _process_model_before_weight_loading( + self, + model: "PreTrainedModel", + **kwargs, + ): + # Add the corresponding quant_config to each valid module. This allows us to do the actual nn.Linear -> HQQLinear conversion in create_quantized_param(). + # prepare_for_hqq_linear() also sets the right quantization config inside the model (model.config.quantization_config) and the layers (hqq_layer.quant_config) + model = prepare_for_hqq_linear(model, quantization_config=self.quantization_config) + + def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs): + setattr(model, "is_hqq_quantized", True) + setattr(model, "is_hqq_serializable", self.is_serializable()) + return model + + def is_serializable(self): + return True + + @property + def is_trainable(self) -> bool: + return True diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_metal.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_metal.py new file mode 100644 index 0000000000000000000000000000000000000000..a3706ed7e2b44d7b30aad5715097bf6a0c5351f9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_metal.py @@ -0,0 +1,130 @@ +# Copyright 2025 The HuggingFace Inc. team. All rights reserved. +# +# 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. +from typing import TYPE_CHECKING, Any + +from ..utils import is_kernels_available, is_torch_available, logging +from .base import HfQuantizer +from .quantizers_utils import get_module_from_name + + +if is_torch_available(): + import torch + +if TYPE_CHECKING: + from ..modeling_utils import PreTrainedModel + from ..utils.quantization_config import MetalConfig + +logger = logging.get_logger(__name__) + + +class MetalHfQuantizer(HfQuantizer): + """ + Quantizer for Metal affine quantization on Apple Silicon (MPS) devices. + + Uses the ``quantization-mlx`` Metal kernels from the Hub to pack weights into + low-bit (2/4/8) uint32 tensors with per-group scales and biases, and performs + fused dequant + matmul in the forward pass. + """ + + requires_calibration = False + quantization_config: "MetalConfig" + + def __init__(self, quantization_config, **kwargs): + super().__init__(quantization_config, **kwargs) + + def validate_environment(self, *args, **kwargs): + if self.quantization_config.dequantize: + return + + if not torch.backends.mps.is_available(): + if self.pre_quantized: + logger.warning_once( + "Metal quantization requires an Apple Silicon GPU (MPS), but none is available. " + "We will default to dequantizing the model to the original dtype." + ) + self.quantization_config.dequantize = True + return + else: + raise RuntimeError("Metal quantization requires an Apple Silicon GPU (MPS). No MPS device found.") + + if not is_kernels_available(): + raise ImportError("Metal quantization requires kernels: `pip install kernels`") + + device_map = kwargs.get("device_map") + if device_map is None: + logger.warning_once( + "You have loaded a Metal quantized model on CPU and have an MPS device available. " + "Set device_map='mps' to use the Metal kernels." + ) + elif isinstance(device_map, dict): + if not self.pre_quantized and ("cpu" in device_map.values() or "disk" in device_map.values()): + raise ValueError( + "Metal quantization on the fly does not support CPU or disk in the device_map. " + "Please use a pre-quantized checkpoint or remove CPU/disk from device_map." + ) + + def update_device_map(self, device_map: dict[str, Any] | None) -> dict[str, Any] | None: + if device_map is None: + device_map = {"": "mps"} + return device_map + + def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool: + from ..integrations.metal_quantization import MetalLinear + + module, tensor_name = get_module_from_name(model, param_name) + if isinstance(module, MetalLinear): + if self.pre_quantized or tensor_name != "weight": + return False + return True + return False + + def _process_model_before_weight_loading(self, model: "PreTrainedModel", **kwargs): + from ..integrations.metal_quantization import replace_with_metal_linear + + self.modules_to_not_convert = self.get_modules_to_not_convert( + model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules + ) + + model = replace_with_metal_linear( + model, + modules_to_not_convert=self.modules_to_not_convert, + quantization_config=self.quantization_config, + pre_quantized=self.pre_quantized, + ) + + def is_serializable(self): + return True + + @property + def is_trainable(self) -> bool: + return False + + def get_quantize_ops(self): + from ..integrations.metal_quantization import MetalQuantize + + return MetalQuantize(self) + + def get_weight_conversions(self): + from ..core_model_loading import WeightConverter + from ..integrations.metal_quantization import MetalDequantize + + if self.pre_quantized and self.quantization_config.dequantize: + return [ + WeightConverter( + source_patterns=["weight$", "scales", "qbiases"], + target_patterns="weight", + operations=[MetalDequantize(self)], + ) + ] + return [] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_mxfp4.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_mxfp4.py new file mode 100644 index 0000000000000000000000000000000000000000..7859a8ff739ad41674f0f0ad5c28bbcfe3639ab9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_mxfp4.py @@ -0,0 +1,315 @@ +# Copyright 2025 The HuggingFace Inc. team. All rights reserved. +# +# 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. +from typing import TYPE_CHECKING + +from .base import HfQuantizer + + +if TYPE_CHECKING: + from ..modeling_utils import PreTrainedModel + from ..utils.quantization_config import Mxfp4Config + +from ..utils import ( + is_accelerate_available, + is_kernels_available, + is_torch_available, + is_triton_available, + logging, +) +from .quantizers_utils import get_module_from_name + + +if is_torch_available(): + import torch + + from ..core_model_loading import WeightConverter + +logger = logging.get_logger(__name__) +triton_kernels_hub = None + + +class Mxfp4HfQuantizer(HfQuantizer): + """ + FP4 quantization using fbgemm kernels + """ + + requires_calibration = False + quantization_config: "Mxfp4Config" + + def __init__(self, quantization_config, **kwargs): + super().__init__(quantization_config, **kwargs) + self.triton_kernels_hub = None + + def _lazy_import_kernels(self): + """Lazy import and initialize kernels only when needed""" + if self.triton_kernels_hub is None: + try: + from ..integrations.hub_kernels import get_kernel + + self.triton_kernels_hub = get_kernel("kernels-community/gpt-oss-triton-kernels") + except ImportError: + raise ImportError("kernels package is required for MXFP4 quantization") + return self.triton_kernels_hub + + def validate_environment(self, *args, **kwargs): + if not is_torch_available(): + raise ImportError( + "Using mxfp4 quantization requires torch" + "Please install the latest version of torch ( pip install --upgrade torch )" + ) + + if self.quantization_config.dequantize: + return + + if not is_accelerate_available(): + raise ImportError("Using mxfp4 requires Accelerate: `pip install accelerate`") + + device = torch.accelerator.current_accelerator() or torch.device("cpu") + if device.type not in ["cuda", "xpu", "cpu"]: + if self.pre_quantized: + logger.warning_once( + f"Using MXFP4 quantized models requires model on cuda/xpu/cpu, but found {device}, we will default to dequantizing the model to bf16. To use mxfp4, please disable the current accelerator." + ) + self.quantization_config.dequantize = True + return + else: + raise RuntimeError( + f"Quantizing a model using MXFP4 requires model on cuda/xpu/cpu, but found {device}. To use mxfp4, please disable the current accelerator." + ) + + if torch.xpu.is_available(): + is_device_supported_mxfp4 = True + triton_available = is_triton_available("3.5.0") + kernels_installed = is_kernels_available() + elif torch.cuda.is_available(): + compute_capability = torch.cuda.get_device_capability() + is_device_supported_mxfp4 = compute_capability >= (7, 5) + triton_available = is_triton_available("3.4.0") + kernels_installed = is_kernels_available() + elif device.type == "cpu": + is_device_supported_mxfp4 = True + triton_available = is_triton_available("3.5.0") + kernels_installed = is_kernels_available() + else: + is_device_supported_mxfp4 = False + triton_available = False + kernels_installed = False + + if self.pre_quantized: + if not is_device_supported_mxfp4: + logger.warning_once( + "MXFP4 quantization is only supported on GPUs with compute capability >= 7.5 " + "(e.g T4, A100, L4, H100, or B200) or XPUs (e.g Intel® Data Center GPU Max Series). " + "We will default to dequantizing the model to bf16." + ) + self.quantization_config.dequantize = True + return + + if not triton_available: + logger.warning_once( + "MXFP4 quantization requires Triton: CUDA requires Triton >= 3.4.0, " + "XPU/CPU requires Triton >= 3.5.0. Please install triton: `pip install triton`. " + "We will default to dequantizing the model to bf16." + ) + self.quantization_config.dequantize = True + return + + if not kernels_installed: + logger.warning_once( + "MXFP4 quantization requires the `kernels` package: " + "`pip install kernels>=0.12.0`. " + "We will default to dequantizing the model to bf16." + ) + self.quantization_config.dequantize = True + return + elif not is_device_supported_mxfp4: + raise ValueError( + "MXFP4 quantization is only supported on GPUs with compute capability >= 7.5 " + "(e.g T4, A100, L4, H100, or B200) or XPUs (e.g Intel® Data Center GPU Max Series) or CPU" + ) + elif not triton_available: + raise ValueError( + "MXFP4 quantization requires Triton: CUDA requires Triton >= 3.4.0, " + "XPU/CPU requires Triton >= 3.5.0. Please install triton: `pip install triton`" + ) + elif not kernels_installed: + raise ValueError("MXFP4 quantization requires the `kernels` package: `pip install kernels>=0.12.0`") + + if not self.pre_quantized: + self._lazy_import_kernels() + + device_map = kwargs.get("device_map") + if device_map is not None and isinstance(device_map, dict): + if not self.pre_quantized and "disk" in device_map.values(): + raise ValueError( + "You are attempting to load an FP4 model with a device_map that contains a disk device." + "This is not supported when the model is quantized on the fly. " + "Please use a quantized checkpoint or remove the disk device from the device_map." + ) + + def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool: + from ..integrations import Mxfp4GptOssExperts + + module, tensor_name = get_module_from_name(model, param_name) + if isinstance(module, Mxfp4GptOssExperts): + if tensor_name in ["down_proj_bias", "gate_up_proj_bias"]: + return False + return True + return False + + def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs): + # clean cache due to triton ops + if torch.cuda.is_available(): + torch.cuda.empty_cache() + elif torch.xpu.is_available(): + torch.xpu.empty_cache() + + def _process_model_before_weight_loading( + self, + model: "PreTrainedModel", + use_kernels: bool = False, + **kwargs, + ): + from ..integrations import replace_with_mxfp4_linear + + # if we are using kernels, we can't use the quantized model, since the forward pass is different and needs special handling + # only CPU kernels can work with pre-quantized models + device = torch.accelerator.current_accelerator() or torch.device("cpu") + if use_kernels and device.type not in ["cpu"]: + logger.warning_once( + "You are using full precision kernels, we will dequantize the model to bf16. " + "To use the quantized model with quantization kernels, please set use_kernels=False" + ) + self.quantization_config.dequantize = True + + if not use_kernels and device.type in ["cpu"]: + logger.warning_once( + "MXFP4 inference on CPU requires use_kernels=True, but use_kernels is disabled. " + "We will dequantize the model to bf16. To run MXFP4 natively on CPU, please set use_kernels=True." + ) + self.quantization_config.dequantize = True + + self.modules_to_not_convert = self.get_modules_to_not_convert( + model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules + ) + + model = replace_with_mxfp4_linear( + model, modules_to_not_convert=self.modules_to_not_convert, quantization_config=self.quantization_config + ) + + def update_tp_plan(self, config): + if "GptOssConfig" in config.__class__.__name__: + if getattr(config, "base_model_tp_plan", None) is not None: + config.base_model_tp_plan.update( + { + "layers.*.mlp.experts.gate_up_proj_blocks": "grouped_gemm", + "layers.*.mlp.experts.gate_up_proj_scales": "grouped_gemm", + "layers.*.mlp.experts.down_proj_blocks": "grouped_gemm", + "layers.*.mlp.experts.down_proj_scales": "grouped_gemm", + } + ) + return config + + def update_ep_plan(self, config): + if "GptOssConfig" in config.__class__.__name__: + if getattr(config, "base_model_ep_plan", None) is not None: + config.base_model_ep_plan.update( + { + "layers.*.mlp.experts.gate_up_proj_blocks": "grouped_gemm", + "layers.*.mlp.experts.gate_up_proj_scales": "grouped_gemm", + "layers.*.mlp.experts.down_proj_blocks": "grouped_gemm", + "layers.*.mlp.experts.down_proj_scales": "grouped_gemm", + } + ) + return config + + def get_state_dict_and_metadata(self, model): + from ..integrations import Mxfp4GptOssExperts + + state_dict = model.state_dict() + num_local_experts = getattr(model.config, "num_local_experts", 32) + hidden_size = getattr(model.config, "hidden_size", 2880) + + for name, module in model.named_modules(): + if not ( + isinstance(module, Mxfp4GptOssExperts) + and hasattr(module, "gate_up_proj") + and hasattr(module, "down_proj") + ): + continue + + for proj in ("gate_up_proj", "down_proj"): + triton_tensor = getattr(module, proj) + precision_config = getattr(module, f"{proj}_precision_config") + + blocks = triton_tensor.storage.layout.unswizzle_data(triton_tensor.storage.data).transpose(-1, -2) + if proj == "gate_up_proj": + blocks = blocks.reshape(num_local_experts, -1, 90, 16) + else: + blocks = blocks.reshape(num_local_experts, hidden_size, 90, -1) + + scales = precision_config.weight_scale.storage.layout.unswizzle_data( + precision_config.weight_scale.storage.data + ).transpose(-1, -2) + + state_dict[f"{name}.{proj}_blocks"] = blocks + state_dict[f"{name}.{proj}_scales"] = scales + + metadata = {} + return state_dict, metadata + + def is_serializable(self): + return True + + @property + def is_trainable(self) -> bool: + logger.warning_once( + "MXFP4 quantization don't support training, please consider dequantizing the model first by passing quantization_config=Mxfp4Config(dequantize=True) to .from_pretrained()" + ) + return False + + def get_quantize_ops(self): + from ..integrations.mxfp4 import Mxfp4Quantize + + return Mxfp4Quantize(self) + + def get_weight_conversions(self): + from ..integrations.mxfp4 import Mxfp4Dequantize, Mxfp4Deserialize + + if self.pre_quantized and self.quantization_config.dequantize: + return [ + WeightConverter( + source_patterns=["down_proj_blocks", "down_proj_scales"], + target_patterns=r"down_proj$", + operations=[Mxfp4Dequantize(self)], + ), + WeightConverter( + source_patterns=["gate_up_proj_blocks", "gate_up_proj_scales"], + target_patterns=["gate_up_proj$"], + operations=[Mxfp4Dequantize(self)], + ), + ] + + return [ + WeightConverter( + source_patterns=["gate_up_proj_blocks", "gate_up_proj_scales"], + target_patterns=r"gate_up_proj$", + operations=[Mxfp4Deserialize(self)], + ), + WeightConverter( + source_patterns=["down_proj_blocks", "down_proj_scales"], + target_patterns=r"down_proj$", + operations=[Mxfp4Deserialize(self)], + ), + ] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_quanto.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_quanto.py new file mode 100644 index 0000000000000000000000000000000000000000..9b08ec271356b1c8236f48a6e6418d4afbbd5768 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_quanto.py @@ -0,0 +1,122 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# 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. +from typing import TYPE_CHECKING + +from .base import HfQuantizer +from .quantizers_utils import get_module_from_name + + +if TYPE_CHECKING: + from ..modeling_utils import PreTrainedModel + +from ..utils import ( + is_accelerate_available, + is_optimum_quanto_available, + is_torch_available, + logging, +) +from ..utils.quantization_config import QuantoConfig + + +if is_torch_available(): + import torch + +logger = logging.get_logger(__name__) + + +class QuantoHfQuantizer(HfQuantizer): + """ + Quantizer for the quanto library + """ + + requires_calibration = False + quantization_config: "QuantoConfig" + + def __init__(self, quantization_config: QuantoConfig, **kwargs): + super().__init__(quantization_config, **kwargs) + map_to_param_size = { + "int8": 1, + "float8": 1, + "int4": 0.5, + "int2": 0.25, + } + self.quantized_param_size = map_to_param_size.get(self.quantization_config.weights, None) + + def validate_environment(self, *args, **kwargs): + if not is_optimum_quanto_available(): + raise ImportError( + "Loading an optimum-quanto quantized model requires optimum-quanto library (`pip install optimum-quanto`)" + ) + if not is_accelerate_available(): + raise ImportError( + "Loading an optimum-quanto quantized model requires accelerate library (`pip install accelerate`)" + ) + device_map = kwargs.get("device_map") + if isinstance(device_map, dict): + if len(device_map) > 1 and "cpu" in device_map.values() or "disk" in device_map.values(): + raise ValueError( + "You are attempting to load an model with a device_map that contains a CPU or disk device." + "This is not supported with quanto when the model is quantized on the fly. " + "Please remove the CPU or disk device from the device_map." + ) + if self.quantization_config.activations is not None: + raise ValueError( + "We don't support quantizing the activations with transformers library." + "Use quanto library for more complex use cases such as activations quantization, calibration and quantization aware training." + ) + + def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool: + from optimum.quanto import QModuleMixin + + module, tensor_name = get_module_from_name(model, param_name) + # We only quantize the weights and the bias is not quantized. + if isinstance(module, QModuleMixin) and "weight" in tensor_name: + # if the weights are quantized, don't need to recreate it again with `create_quantized_param` + return not module.frozen + else: + return False + + def adjust_max_memory(self, max_memory: dict[str, int | str]) -> dict[str, int | str]: + max_memory = {key: val * 0.90 for key, val in max_memory.items()} + return max_memory + + def param_element_size(self, model: "PreTrainedModel", param_name: str, param: "torch.Tensor") -> float: + "Return the element size (in bytes) for `param_name`." + if self.param_needs_quantization(model, param_name) and self.quantized_param_size is not None: + return self.quantized_param_size + + return super().param_element_size(model, param_name, param) + + def _process_model_before_weight_loading(self, model: "PreTrainedModel", **kwargs): + from ..integrations import replace_with_quanto_layers + + self.modules_to_not_convert = self.get_modules_to_not_convert( + model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules + ) + + model = replace_with_quanto_layers( + model, modules_to_not_convert=self.modules_to_not_convert, quantization_config=self.quantization_config + ) + + @property + def is_trainable(self) -> bool: + return True + + def is_serializable(self): + return False + + def get_quantize_ops(self): + from ..integrations.quanto import QuantoQuantize + + return QuantoQuantize(self) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_quark.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_quark.py new file mode 100644 index 0000000000000000000000000000000000000000..590159cce77cb765b6d3c53a439ee3d9eb60d45a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_quark.py @@ -0,0 +1,104 @@ +# Copyright 2025 Advanced Micro Devices, Inc. and The HuggingFace Inc. team. All rights reserved. +# +# 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. + +from typing import TYPE_CHECKING + +from .base import HfQuantizer + + +if TYPE_CHECKING: + from ..modeling_utils import PreTrainedModel + from ..utils.quantization_config import QuarkConfig + +from ..utils import is_quark_available, logging + + +logger = logging.get_logger(__name__) + + +CHECKPOINT_KEYS = { + "weight_scale": "weight_quantizer.scale", + "bias_scale": "bias_quantizer.scale", + "input_scale": "input_quantizer.scale", + "output_scale": "output_quantizer.scale", + "weight_zero_point": "weight_quantizer.zero_point", + "bias_zero_point": "bias_quantizer.zero_point", + "input_zero_point": "input_quantizer.zero_point", + "output_zero_point": "output_quantizer.zero_point", +} + + +class QuarkHfQuantizer(HfQuantizer): + """ + Quark quantizer (https://quark.docs.amd.com/latest/). + """ + + requires_calibration = True # On-the-fly quantization with quark is not supported for now. + quantization_config: "QuarkConfig" + + def __init__(self, quantization_config, **kwargs): + super().__init__(quantization_config, **kwargs) + + self.json_export_config = quantization_config.json_export_config + + def validate_environment(self, *args, **kwargs): + if not is_quark_available(): + raise ImportError( + "Loading a Quark quantized model requires the `quark` library but it was not found in the environment. Please refer to https://quark.docs.amd.com/latest/install.html." + ) + + def _process_model_before_weight_loading(self, model: "PreTrainedModel", **kwargs): + from quark.torch.export.api import _map_to_quark + + _map_to_quark( + model, + self.quantization_config.quant_config, + pack_method=self.json_export_config.pack_method, + custom_mode=self.quantization_config.custom_mode, + ) + + return model + + def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool: + return True + + def is_serializable(self): + return False + + @property + def is_trainable(self): + return False + + def get_weight_conversions(self): + from ..core_model_loading import WeightConverter + from ..integrations.quark import QuarkDeserialize + + # In Quark, quantization is managed through a QParamsLinear module, which holds + # separate quantizers for the weights, inputs, and biases (e.g. weight_quantizer + # input_quantizer, bias_quantizer, etc.). + # + # The checkpoint stores keys like `weight_scale`, `input_scale`, etc. + # but the model's state_dict() exposes `weight_quantizer.scale`, `input_quantizer.scale`, etc. + # We rename from checkpoint format to model format, and the QuarkDeserialize operation + # handles assigning values into the corresponding quantizer attributes. + converters = [] + for source_key, target_key in CHECKPOINT_KEYS.items(): + converters.append( + WeightConverter( + source_patterns=[source_key], + target_patterns=target_key, + operations=[QuarkDeserialize(self)], + ) + ) + return converters diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_sinq.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_sinq.py new file mode 100644 index 0000000000000000000000000000000000000000..d42d4cc8296d2e0fba5535075235cf13c99d63a1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_sinq.py @@ -0,0 +1,262 @@ +# Copyright 2026 The HuggingFace Inc. team. All rights reserved. +# +# 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. +from __future__ import annotations + +from typing import TYPE_CHECKING + +from ..utils import is_torch_available, logging +from ..utils.quantization_config import SinqConfig +from .base import HfQuantizer +from .quantizers_utils import get_module_from_name + + +if is_torch_available(): + import torch + +if TYPE_CHECKING: + from ..modeling_utils import PreTrainedModel + +logger = logging.get_logger(__name__) + + +class SinqHfQuantizer(HfQuantizer): + """ + HF v5 quantizer for SINQ. + + Modes: + - method="sinq" (default): + * weight-only SINQ + * param-level ConversionOps (`SinqQuantize`) during load for pure language models + (each Linear.weight is turned into a SINQLinear module) + * module-level quantization after load for multimodal models + - method="asinq": + * A-SINQ (activation-aware) SINQ quantization + """ + + requires_parameters_quantization: bool = True + quantization_config: SinqConfig + + def __init__(self, quantization_config: SinqConfig, **kwargs): + super().__init__(quantization_config, **kwargs) + + self._normalized_device_str: str | None = None + self._do_param_level_sinq: bool = False + + def is_serializable(self) -> bool: + return True + + @property + def is_trainable(self) -> bool: + return True + + def update_device_map(self, device_map): + if device_map is None: + if torch.cuda.is_available(): + device_map = {"": torch.cuda.current_device()} + else: + device_map = {"": "cpu"} + logger.info( + "The device_map was not initialized. " + f"Setting device_map to {device_map}. " + "If you want to use the model for inference, please set device_map='auto'" + ) + return device_map + + def update_dtype(self, dtype: torch.dtype) -> torch.dtype: + if dtype is None: + dtype = torch.bfloat16 + self.dtype = dtype + return dtype + + def validate_environment(self, *args, **kwargs) -> None: + from ..utils import is_sinq_available + + if not is_sinq_available(): + raise ImportError("The 'sinq' package is not installed. Please install it with: pip install sinq") + + if not torch.cuda.is_available(): + logger.warning( + "No CUDA device is available. Quantization and inference will run on the CPU. Please note that this will significantly slow down inference speed and increase quantization time." + ) + + device_map = kwargs.get("device_map") + + if isinstance(device_map, dict): + device_map_values = set(device_map.values()) + if len(device_map_values) > 1: + raise RuntimeError( + "SinqHfQuantizer: multi-GPU device_map detected, but SINQ currently supports only a single CUDA " + f"device. Got {sorted(device_map_values)}. Please use device_map=None." + ) + + if self.quantization_config.method == "asinq" and not self.pre_quantized: + raise ValueError( + "You are using `method='asinq'` in the quantization config. Right now the calibrated version of SINQ" + " is not supported in Hugging Face, please refer and use the official SINQ repository " + "`to quantize a model with this method. " + ) + + def _build_sinq_quant_dict(self, cfg: SinqConfig) -> dict: + """ + Build the dict that SINQLinear expects as quant_config. + """ + from sinq.sinqlinear_hf import sinq_base_quant_config as sinq_base_quant_config_fn + + method = cfg.method + return sinq_base_quant_config_fn( + nbits=int(cfg.nbits), + group_size=int(cfg.group_size) if cfg.group_size is not None else None, + quant_zero=False, + quant_scale=False, + view_as_float=False, + axis=1, + tiling_mode=str(cfg.tiling_mode), + method=method, + ) + + def param_needs_quantization(self, model: PreTrainedModel, param_name: str, **kwargs) -> bool: + """ + Called per-parameter to decide whether to run `SinqQuantize` on it. + + - If `self.pre_quantized`, we do *not* quantize again (handled by SinqDeserialize instead). + - For method="asinq": return False (ASINQ is not supported in Hugging Face). + - For method="sinq": True only for SINQLinear.weight not in modules_to_not_convert. + + Note: After _process_model_before_weight_loading(), the modules are already SINQLinear, + not nn.Linear. We check for SINQLinear modules that are not yet quantized (ready=False). + """ + from sinq.sinqlinear_hf import SINQLinear + + if self.pre_quantized: + return False + + if self.quantization_config.method == "asinq": + return False + + # SINQ param-level only if deemed safe + if not self._do_param_level_sinq: + return False + + module, tensor_name = get_module_from_name(model, param_name) + + if tensor_name != "weight": + return False + + # Check if it's an unquantized SINQLinear + is_sinq = isinstance(module, SINQLinear) + is_ready = getattr(module, "ready", True) + result = is_sinq and not is_ready + return result + + def get_quantize_ops(self): + """ + Return the ConversionOps used for param-level quantization (Sinq). + The actual SINQLinear construction is in integrations/sinq.py. + """ + from ..integrations.sinq import SinqQuantize + + return SinqQuantize(self) + + def get_weight_conversions(self): + """ + If `pre_quantized=True`, interpret a checkpoint produced by SINQLinear.state_dict: + + .W_q + .bias + .meta + + via a WeightConverter + SinqDeserialize so that we reconstruct a SINQLinear + module instead of a plain nn.Linear. + """ + from ..core_model_loading import WeightConverter + + if self.pre_quantized: + from ..integrations.sinq import SinqDeserialize + + return [ + WeightConverter( + source_patterns=[ + ".W_q", + ".meta", + ".bias", + ], + target_patterns=[".weight"], + operations=[SinqDeserialize(self)], + ) + ] + return [] + + def _process_model_before_weight_loading( + self, + model: PreTrainedModel, + device_map, + keep_in_fp32_modules: list[str] | None = None, + **kwargs, + ): + """ + Called on meta-initialized model, before loading any weights. + + For SINQ, we replace nn.Linear modules with empty SINQLinear modules here. + The actual quantization happens later in SinqQuantize.convert() when weights are loaded. + """ + from ..integrations.sinq import replace_with_sinq_linear + + self.modules_to_not_convert = self.get_modules_to_not_convert( + model, (self.quantization_config.modules_to_not_convert or []), keep_in_fp32_modules + ) + + # Enable param-level quantization for SINQ method + self._do_param_level_sinq = self.quantization_config.method == "sinq" and not self.pre_quantized + + sinq_quant_dict = None if self.pre_quantized else self._build_sinq_quant_dict(self.quantization_config) + + # Extract device from device_map (guaranteed to be set by update_device_map) + if isinstance(device_map, dict): + first_device = next(iter(device_map.values()), 0) + if isinstance(first_device, int): + device_str = f"cuda:{first_device}" + else: + device_str = str(first_device) + else: + device_str = "cuda:0" if torch.cuda.is_available() else "cpu" + + model = replace_with_sinq_linear( + model, + modules_to_not_convert=self.modules_to_not_convert, + quant_config=sinq_quant_dict, + compute_dtype=self.dtype, + device=device_str, + pre_quantized=self.pre_quantized, + ) + + def _process_model_after_weight_loading( + self, + model: PreTrainedModel, + **kwargs, + ): + """ + Called after *all* weights have been loaded. + + For SINQ: + 1. Move non-SINQLinear modules to GPU (embeddings, norms, lm_head, etc.) + - SINQLinear modules already have GemLite buffers on GPU + - We skip moving SINQLinear's W_q/meta to avoid memory duplication + 2. Patch HF save/load methods for SINQ serialization + """ + from sinq.hf_io import patch_hf_pretrained_io + + # Patch HF save/load methods for SINQ serialization + patch_hf_pretrained_io() + + return model diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_spqr.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_spqr.py new file mode 100644 index 0000000000000000000000000000000000000000..918b7c6a01b5e2717a600f21c2982088ef4694d3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_spqr.py @@ -0,0 +1,81 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# 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/lic enses/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. +from typing import TYPE_CHECKING + +from .base import HfQuantizer + + +if TYPE_CHECKING: + from ..modeling_utils import PreTrainedModel + from ..utils.quantization_config import SpQRConfig + +from ..integrations import replace_with_spqr_linear +from ..utils import is_accelerate_available, is_spqr_available, is_torch_available, logging +from ..utils.quantization_config import QuantizationConfigMixin + + +if is_torch_available(): + import torch + +logger = logging.get_logger(__name__) + + +class SpQRHfQuantizer(HfQuantizer): + """ + Quantizer of the SpQR method. Enables the loading of prequantized models. + """ + + requires_calibration = True + quantization_config: "SpQRConfig" + + def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs): + super().__init__(quantization_config, **kwargs) + + def validate_environment(self, *args, **kwargs): + if not torch.cuda.is_available(): + raise RuntimeError("GPU is required to run SpQR quantized model.") + + if not is_accelerate_available(): + raise ImportError("Using `spqr` quantization requires Accelerate: `pip install accelerate`") + + if not is_spqr_available(): + raise ImportError("Using `spqr` quantization requires SpQR: `pip install spqr_quant[gpu]`") + + def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype": + if dtype != torch.float16: + raise ValueError( + "You cannot use any type other than torch.float16 for SpQR. Please set it totorch.float16 explicitly." + ) + return dtype + + def _process_model_before_weight_loading( + self, + model: "PreTrainedModel", + **kwargs, + ): + self.modules_to_not_convert = self.get_modules_to_not_convert( + model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules + ) + replace_with_spqr_linear( + model, + quantization_config=self.quantization_config, + modules_to_not_convert=self.modules_to_not_convert, + ) + + @property + def is_trainable(self): + return False + + def is_serializable(self): + return True diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_torchao.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_torchao.py new file mode 100644 index 0000000000000000000000000000000000000000..fd117b08023b598c334d80c1140707de5717c93c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_torchao.py @@ -0,0 +1,196 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# 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. +import re +from typing import TYPE_CHECKING + +from .base import HfQuantizer +from .quantizers_utils import get_module_from_name, should_convert_module + + +if TYPE_CHECKING: + from ..modeling_utils import PreTrainedModel + from ..utils.quantization_config import TorchAoConfig + +from safetensors import safe_open + +from ..utils import is_torch_available, is_torchao_available, logging + + +MIN_TORCH_VERSION = "2.5.0" + + +if is_torch_available(): + from ..core_model_loading import WeightConverter + + +if is_torch_available(): + import torch + +if is_torchao_available(): + from torchao.prototype.safetensors.safetensors_support import ( + flatten_tensor_state_dict, + ) + + +logger = logging.get_logger(__name__) + + +def _fuzzy_match_size(config_name: str) -> str | None: + """ + Extract the size digit from torchao config class names like "Int4WeightOnlyConfig", "Int8WeightOnlyConfig". + Returns the digit as a string if found, otherwise None. + """ + match = re.search(r"(\d)weight", config_name.lower()) + return match.group(1) if match else None + + +class TorchAoHfQuantizer(HfQuantizer): + """ + Quantizer for torchao: https://github.com/pytorch/ao/ + """ + + requires_calibration = False + quantization_config: "TorchAoConfig" + + def __init__(self, quantization_config, **kwargs): + super().__init__(quantization_config, **kwargs) + + size_digit = _fuzzy_match_size(type(self.quantization_config.quant_type).__name__) + self.quantized_param_size = 0.5 if size_digit == "4" else 1 + + def validate_environment(self, *args, **kwargs): + if not is_torchao_available(): + raise ImportError("Loading an torchao quantized model requires torchao library (`pip install torchao`)") + + device_map = kwargs.get("device_map") + self.offload_to_cpu = False + if isinstance(device_map, dict): + if ("disk" in device_map.values() or "cpu" in device_map.values()) and len(device_map) > 1: + self.offload_to_cpu = "cpu" in device_map.values() + if self.pre_quantized and "disk" in device_map.values(): + raise ValueError( + "You are attempting to perform disk offload with a pre-quantized torchao model " + "This is not supported yet . Please remove the disk device from the device_map." + ) + + def get_state_dict_and_metadata(self, model): + """ + We flatten the state dict of tensor subclasses so that it is compatible with the safetensors format. + """ + return flatten_tensor_state_dict(model.state_dict()) + + def param_element_size(self, model: "PreTrainedModel", param_name: str, param: "torch.Tensor") -> float: + "Return the element size (in bytes) for `param_name`." + if self.param_needs_quantization(model, param_name) and self.quantized_param_size is not None: + return self.quantized_param_size + + return super().param_element_size(model, param_name, param) + + def adjust_max_memory(self, max_memory: dict[str, int | str]) -> dict[str, int | str]: + # need more space for the quantization parameters (e.g. scale). Tested with int4 wo and group size = 128 + max_memory = {key: val * 0.9 for key, val in max_memory.items()} + return max_memory + + def _process_model_before_weight_loading(self, model: "PreTrainedModel", checkpoint_files=None, **kwargs): + self.modules_to_not_convert = self.get_modules_to_not_convert( + model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules + ) + if self.quantization_config.include_input_output_embeddings: + input_emb = model.get_input_embeddings() + input_emb_names = [name for name, module in model.named_modules() if id(module) == id(input_emb)] + output_emb = model.get_output_embeddings() + output_emb_names = [name for name, module in model.named_modules() if id(module) == id(output_emb)] + self.modules_to_not_convert = [ + x for x in self.modules_to_not_convert if x not in input_emb_names + output_emb_names + ] + if checkpoint_files is not None: + # Torchao needs access to all metadata later + self.set_metadata(checkpoint_files) + + def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool: + # check if the param_name is not in self.modules_to_not_convert + if not should_convert_module(param_name, self.modules_to_not_convert): + return False + + # we only quantize the weight of nn.Linear and nn.Embedding + module, tensor_name = get_module_from_name(model, param_name) + _QUANTIZABLE = [torch.nn.Linear] + if self.quantization_config.include_input_output_embeddings: + _QUANTIZABLE.append(torch.nn.Embedding) + + from torchao.quantization import FqnToConfig, fqn_matches_fqn_config + + if isinstance(self.quantization_config.quant_type, FqnToConfig): + module_fqn, _ = param_name.rsplit(".", 1) + if ( + fqn_matches_fqn_config(module_fqn, self.quantization_config.quant_type) + or fqn_matches_fqn_config(param_name, self.quantization_config.quant_type) + or ( + "_default" in self.quantization_config.quant_type.fqn_to_config + and isinstance(module, tuple(_QUANTIZABLE)) + ) + ): + return True + + return isinstance(module, tuple(_QUANTIZABLE)) and tensor_name == "weight" + + def is_serializable(self) -> bool: + return True + + @property + def is_trainable(self) -> bool: + # Only 8-bit quantization (e.g. Int8WeightOnly, Int8DynamicActivationInt8Weight) supports training + return _fuzzy_match_size(type(self.quantization_config.quant_type).__name__) == "8" + + @property + def is_compileable(self) -> bool: + return True + + def set_metadata(self, checkpoint_files: list[str]): + if checkpoint_files[0].endswith(".safetensors"): + metadata = {} + for checkpoint in checkpoint_files: + with safe_open(checkpoint, framework="pt") as f: + metadata_ = f.metadata() or {} + metadata.update(metadata_) + # Save it + self.metadata = metadata + + def get_quantize_ops(self): + from ..integrations.torchao import TorchAoQuantize + + return TorchAoQuantize(self) + + def get_weight_conversions(self): + from ..integrations.torchao import TorchAoDeserialize + + if self.pre_quantized: + return [ + WeightConverter( + # TODO: incr flexibility by generalizing the source patterns to match the format of "_weight_" + # note that the matching logic is greedy, so for ex, if _weight_scale is before _weight_scale_and_zero in this list, it will match _weight_scale always (this is incorrect) + # thus, the order of source_patterns is intentional + source_patterns=[ + "_weight_qdata", + "_weight_scale_and_zero", + "_weight_per_tensor_scale", + "_weight_scale", + "_weight_zero_point", + "_weight_act_pre_scale", + ], + target_patterns="weight", + operations=[TorchAoDeserialize(self)], + ), + ] + return [] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_vptq.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_vptq.py new file mode 100644 index 0000000000000000000000000000000000000000..8d60559b09d36e7b401c24fa0bcbfcdc1106a165 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_vptq.py @@ -0,0 +1,75 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# 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. +from typing import TYPE_CHECKING + +from .base import HfQuantizer + + +if TYPE_CHECKING: + from ..modeling_utils import PreTrainedModel + from ..utils.quantization_config import VptqConfig + +from ..utils import is_accelerate_available, is_torch_available, is_vptq_available, logging +from ..utils.quantization_config import QuantizationConfigMixin + + +if is_torch_available(): + import torch + +logger = logging.get_logger(__name__) + + +class VptqHfQuantizer(HfQuantizer): + """ + Quantizer of the VPTQ method. Enables the loading of prequantized models. + """ + + requires_calibration = True + quantization_config: "VptqConfig" + + def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs): + super().__init__(quantization_config, **kwargs) + + def validate_environment(self, *args, **kwargs): + if not is_accelerate_available(): + raise ImportError("Using `vptq` quantization requires Accelerate: `pip install accelerate`") + + if not is_vptq_available(): + raise ImportError("Using `vptq` quantization requires VPTQ>=0.0.4: `pip install -U vptq`") + + if not torch.cuda.is_available(): + raise RuntimeError("GPU is required to run VTPQ quantized model.") + + def _process_model_before_weight_loading( + self, + model: "PreTrainedModel", + **kwargs, + ): + from ..integrations import replace_with_vptq_linear + + self.modules_to_not_convert = self.get_modules_to_not_convert( + model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules + ) + replace_with_vptq_linear( + model, + quantization_config=self.quantization_config, + modules_to_not_convert=self.modules_to_not_convert, + ) + + @property + def is_trainable(self) -> bool: + return False + + def is_serializable(self): + return True diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizers_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizers_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0e90e238ec4a6ed4a392b170c95d1c6895025a80 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizers_utils.py @@ -0,0 +1,41 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# 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. +import re +from typing import Any + + +def get_module_from_name(module, tensor_name: str) -> tuple[Any, str]: + if "." in tensor_name: + module_name, tensor_name = tensor_name.rsplit(".", 1) + module = module.get_submodule(module_name) + return module, tensor_name + + +def should_convert_module(full_name, patterns: list[str] | None = None): + if patterns is None: + return True + + # We should avoid converting in the following situations: + # 1. The pattern appears as a prefix followed by a dot in `full_name` + # (e.g., "model.decoder.layer.11." matches "model.decoder.layer.11.attn.weight"). + # 2. The pattern matches `full_name` exactly or via regex + # (e.g., "lm_head" matches "lm_head"; "model.decoder.layer.*" matches "model.decoder.layer.11.attn.weight"). + # 3. `full_name` ends with the pattern + # (e.g., "fc1" matches "model.decoder.layers.23.fc1"). + + should_not_convert = any( + re.match(f"{key}\\.", full_name) or re.match(f"{key}", full_name) or full_name.endswith(key) + for key in patterns + ) + return not should_not_convert diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d12e0b277c1bc54bd030dfaefb1caef3b1727737 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__init__.py @@ -0,0 +1,336 @@ +#!/usr/bin/env python + +# Copyright 2021 The HuggingFace Inc. team. All rights reserved. +# +# 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. + +from functools import lru_cache + +from packaging import version + +from .. import __version__ +from .auto_docstring import ( + ClassAttrs, + ClassDocstring, + ImageProcessorArgs, + ModelArgs, + ModelOutputArgs, + auto_class_docstring, + auto_docstring, + get_args_doc_from_source, + parse_docstring, + set_min_indent, +) +from .chat_template_utils import DocstringParsingException, TypeHintParsingException, get_json_schema +from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD +from .doc import ( + add_code_sample_docstrings, + add_end_docstrings, + add_start_docstrings, + add_start_docstrings_to_model_forward, + copy_func, + replace_return_docstrings, +) +from .generic import ( + ContextManagers, + ExplicitEnum, + ModelOutput, + PaddingStrategy, + TensorType, + TransformersKwargs, + _is_tensor_or_array_like, + can_return_loss, + can_return_tuple, + expand_dims, + filter_out_non_signature_kwargs, + find_labels, + flatten_dict, + is_numpy_array, + is_tensor, + is_timm_config_dict, + is_timm_local_checkpoint, + is_torch_device, + is_torch_dtype, + is_torch_tensor, + reshape, + safe_load_json_file, + squeeze, + strtobool, + tensor_size, + to_numpy, + to_py_obj, + torch_float, + torch_int, + transpose, +) +from .hub import ( + CHAT_TEMPLATE_DIR, + CHAT_TEMPLATE_FILE, + CLOUDFRONT_DISTRIB_PREFIX, + HF_MODULES_CACHE, + LEGACY_PROCESSOR_CHAT_TEMPLATE_FILE, + S3_BUCKET_PREFIX, + TRANSFORMERS_DYNAMIC_MODULE_NAME, + EntryNotFoundError, + PushInProgress, + PushToHubMixin, + RepositoryNotFoundError, + RevisionNotFoundError, + cached_file, + define_sagemaker_information, + extract_commit_hash, + has_file, + http_user_agent, + list_repo_templates, + try_to_load_from_cache, +) +from .import_utils import ( + ACCELERATE_MIN_VERSION, + BITSANDBYTES_MIN_VERSION, + ENV_VARS_TRUE_AND_AUTO_VALUES, + ENV_VARS_TRUE_VALUES, + GGUF_MIN_VERSION, + TRITON_MIN_VERSION, + XLA_FSDPV2_MIN_VERSION, + DummyObject, + OptionalDependencyNotAvailable, + _LazyModule, + check_torch_load_is_safe, + direct_transformers_import, + enable_tf32, + get_torch_version, + is_accelerate_available, + is_apex_available, + is_apollo_torch_available, + is_aqlm_available, + is_auto_round_available, + is_av_available, + is_bitsandbytes_available, + is_bs4_available, + is_coloredlogs_available, + is_compressed_tensors_available, + is_cuda_platform, + is_cv2_available, + is_cython_available, + is_datasets_available, + is_decord_available, + is_detectron2_available, + is_env_variable_false, + is_env_variable_true, + is_essentia_available, + is_faiss_available, + is_fbgemm_gpu_available, + is_flash_attn_2_available, + is_flash_attn_3_available, + is_flash_attn_4_available, + is_flash_attn_greater_or_equal, + is_flash_attn_greater_or_equal_2_10, + is_flute_available, + is_fouroversix_available, + is_fp_quant_available, + is_fsdp_available, + is_g2p_en_available, + is_galore_torch_available, + is_gguf_available, + is_gptqmodel_available, + is_grokadamw_available, + is_grouped_mm_available, + is_habana_gaudi1, + is_hadamard_available, + is_hqq_available, + is_huggingface_hub_greater_or_equal, + is_in_notebook, + is_ipython_available, + is_jinja_available, + is_jmespath_available, + is_jumanpp_available, + is_kenlm_available, + is_kernels_available, + is_levenshtein_available, + is_libcst_available, + is_librosa_available, + is_liger_kernel_available, + is_llm_awq_available, + is_lomo_available, + is_matplotlib_available, + is_mistral_common_available, + is_mlx_available, + is_multipart_available, + is_natten_available, + is_ninja_available, + is_nltk_available, + is_num2words_available, + is_numba_available, + is_onnx_available, + is_openai_available, + is_optimum_available, + is_optimum_quanto_available, + is_pandas_available, + is_peft_available, + is_phonemizer_available, + is_pretty_midi_available, + is_protobuf_available, + is_psutil_available, + is_py3nvml_available, + is_pyctcdecode_available, + is_pytesseract_available, + is_pytest_available, + is_pytest_order_available, + is_pytorch_quantization_available, + is_quanto_greater, + is_quark_available, + is_qutlass_available, + is_rich_available, + is_rjieba_available, + is_rocm_platform, + is_sacremoses_available, + is_sagemaker_dp_enabled, + is_sagemaker_mp_enabled, + is_schedulefree_available, + is_scipy_available, + is_sentencepiece_available, + is_seqio_available, + is_serve_available, + is_sinq_available, + is_sklearn_available, + is_soundfile_available, + is_spacy_available, + is_speech_available, + is_spqr_available, + is_sudachi_available, + is_sudachi_projection_available, + is_tiktoken_available, + is_timm_available, + is_tokenizers_available, + is_torch_accelerator_available, + is_torch_available, + is_torch_bf16_available_on_device, + is_torch_bf16_gpu_available, + is_torch_cuda_available, + is_torch_deterministic, + is_torch_flex_attn_available, + is_torch_fp16_available_on_device, + is_torch_fx_proxy, + is_torch_greater_or_equal, + is_torch_hpu_available, + is_torch_mlu_available, + is_torch_mps_available, + is_torch_musa_available, + is_torch_neuron_available, + is_torch_neuroncore_available, + is_torch_npu_available, + is_torch_optimi_available, + is_torch_tensorrt_fx_available, + is_torch_tf32_available, + is_torch_xla_available, + is_torch_xpu_available, + is_torchao_available, + is_torchaudio_available, + is_torchcodec_available, + is_torchdistx_available, + is_torchdynamo_compiling, + is_torchdynamo_exporting, + is_torchvision_available, + is_torchvision_v2_available, + is_tracing, + is_training_run_on_sagemaker, + is_triton_available, + is_uroman_available, + is_vision_available, + is_vptq_available, + is_xlstm_available, + is_yt_dlp_available, + requires_backends, + torch_compilable_check, + torch_only_method, +) +from .kernel_config import KernelConfig +from .peft_utils import ( + ADAPTER_CONFIG_NAME, + ADAPTER_SAFE_WEIGHTS_NAME, + ADAPTER_WEIGHTS_NAME, + check_peft_version, + find_adapter_config_file, +) + + +WEIGHTS_NAME = "pytorch_model.bin" +WEIGHTS_INDEX_NAME = "pytorch_model.bin.index.json" +SAFE_WEIGHTS_NAME = "model.safetensors" +SAFE_WEIGHTS_INDEX_NAME = "model.safetensors.index.json" +CONFIG_NAME = "config.json" +FEATURE_EXTRACTOR_NAME = "preprocessor_config.json" +IMAGE_PROCESSOR_NAME = "preprocessor_config.json" +VIDEO_PROCESSOR_NAME = "video_preprocessor_config.json" +AUDIO_TOKENIZER_NAME = "audio_tokenizer_config.json" +PROCESSOR_NAME = "processor_config.json" +GENERATION_CONFIG_NAME = "generation_config.json" +MODEL_CARD_NAME = "modelcard.json" + + +SENTENCEPIECE_UNDERLINE = "▁" +SPIECE_UNDERLINE = SENTENCEPIECE_UNDERLINE # Kept for backward compatibility + +MULTIPLE_CHOICE_DUMMY_INPUTS = [ + [[0, 1, 0, 1], [1, 0, 0, 1]] +] * 2 # Needs to have 0s and 1s only since XLM uses it for langs too. +DUMMY_INPUTS = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]] +DUMMY_MASK = [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]] + + +def check_min_version(min_version): + if version.parse(__version__) < version.parse(min_version): + if "dev" in min_version: + error_message = ( + "This example requires a source install from HuggingFace Transformers (see " + "`https://huggingface.co/docs/transformers/installation#install-from-source`)," + ) + else: + error_message = f"This example requires a minimum version of {min_version}," + error_message += f" but the version found is {__version__}.\n" + raise ImportError( + error_message + + "Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other " + "versions of HuggingFace Transformers." + ) + + +@lru_cache +def get_available_devices() -> frozenset[str]: + """ + Returns a frozenset of devices available for the current PyTorch installation. + """ + devices = {"cpu"} # `cpu` is always supported as a device in PyTorch + + if is_torch_cuda_available(): + devices.add("cuda") + + if is_torch_mps_available(): + devices.add("mps") + + if is_torch_xpu_available(): + devices.add("xpu") + + if is_torch_npu_available(): + devices.add("npu") + + if is_torch_hpu_available(): + devices.add("hpu") + + if is_torch_mlu_available(): + devices.add("mlu") + + if is_torch_musa_available(): + devices.add("musa") + + return frozenset(devices) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a34931ff9950aa3919f758f9839af17ac7c2d94a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/attention_visualizer.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/attention_visualizer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..743cdb0622bcc88cf0bd4138eaf9ae17d8532694 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/attention_visualizer.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/backbone_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/backbone_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26e3e211aaec0c52d3a3c1ddf813d92a1ffc70e0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/backbone_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/chat_parsing_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/chat_parsing_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc932baa4a1254767bad98241a91a21e3b7b41f4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/chat_parsing_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/chat_template_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/chat_template_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63960ef1b94d346b9e2fdae3f3a40a26bef54c22 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/chat_template_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/constants.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/constants.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa144e4cdaf51ddfae307f0f9629fa536a2d93f1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/constants.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/deprecation.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/deprecation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc0db77809c152594b70ff07281cd4f7a4a42465 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/deprecation.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/doc.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/doc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e126236fd04cd2d3404ecf3983ed3ec1e8ffd37c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/doc.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_detectron2_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_detectron2_objects.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f12cea8b4329e1a5c90c81b07504a4b394097a91 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_detectron2_objects.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4abe96ec5214a7a17ab4733be927f1bb78beb59 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_mistral_common_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_mistral_common_objects.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a0053b10cb30af0530d803b7ef8b2b8b23b57aa Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_mistral_common_objects.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_music_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_music_objects.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0acde2520c71f78b1d64e2520594af02b315402 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_music_objects.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_pt_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_pt_objects.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5845a2ccfb35e71efc993367667f65fd4867d751 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_pt_objects.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_sentencepiece_and_tokenizers_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_sentencepiece_and_tokenizers_objects.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4a3a51061b437c70aa6f7184cc00d10d0e8046a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_sentencepiece_and_tokenizers_objects.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_speech_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_speech_objects.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb7a124d7970e3a604e039f63dd538dd713ff2ca Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_speech_objects.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_timm_and_torchvision_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_timm_and_torchvision_objects.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84397e88928e371cd1157bdd842fee5a3d92a05e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_timm_and_torchvision_objects.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_tokenizers_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_tokenizers_objects.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..946b6960231b4250c8c0c4ea666a2736842f5745 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_tokenizers_objects.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_torchaudio_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_torchaudio_objects.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10db61078b0c7245acda6e959588948c472a6002 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_torchaudio_objects.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_torchvision_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_torchvision_objects.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c17a1f3bc697d729683f77fdb3a4d4029e4cac1d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_torchvision_objects.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_vision_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_vision_objects.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8f411ffef3a0e8680ee5675a4deae25f1973d30 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_vision_objects.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/generic.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/generic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4513d76f10dbd08be718c3211b8241a3f6ced55f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/generic.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/hp_naming.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/hp_naming.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fde57256239a73b62e43b2c3b2f5209c29a533d3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/hp_naming.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/hub.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/hub.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90d81e10055a7971eaeccd788fea1c8f9449a574 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/hub.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/kernel_config.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/kernel_config.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e7914457339a35980c56db60ece260b2afe3ff3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/kernel_config.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/loading_report.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/loading_report.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..143cb6304e89cbefb1e93f417682d6cf6bbadacd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/loading_report.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/logging.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/logging.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bed9f65033a47d5dd978113be883e0f105307435 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/logging.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/metrics.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/metrics.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1cf67bc447e8d42e23f04a2e46ecd93d7874098e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/metrics.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/network_logging.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/network_logging.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc03f3187cdc0be7a596fe5670f1421e52b830ac Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/network_logging.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/notebook.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/notebook.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85b17cc29e79e3a4eb84e8daf3e01b4c86319185 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/notebook.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/output_capturing.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/output_capturing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7eff8ac640262c2c67bc75a89c83adedd5a19a1d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/output_capturing.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/peft_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/peft_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7fec42b1948795caeac5365a5ec0022cad29f82b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/peft_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/pytest_helpers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/pytest_helpers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6ea3d9110bbf8cd5f4678114eff5cb0fa107295 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/pytest_helpers.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/sentencepiece_model_pb2.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/sentencepiece_model_pb2.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64966ca7cd9e744bc288f3a76b4b71e1ee8d1d06 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/sentencepiece_model_pb2.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/sentencepiece_model_pb2_new.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/sentencepiece_model_pb2_new.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..395244f63f292033f14242def33eb8f5a3fa1b5e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/sentencepiece_model_pb2_new.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/type_validators.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/type_validators.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05b8d7f3c5c200cb96876ffc555ecafc222aaa3f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/type_validators.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/versions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/versions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f3249dfae1ed2c62215e435a6380e1e7fee0705 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/versions.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/attention_visualizer.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/attention_visualizer.py new file mode 100644 index 0000000000000000000000000000000000000000..9f9b9699101269cabdf84d9e79f8c91e10ff772a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/attention_visualizer.py @@ -0,0 +1,255 @@ +# Copyright 2025 The HuggingFace Inc. team. +# +# 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. +import io + +import httpx +from PIL import Image + +from ..masking_utils import create_causal_mask +from ..models.auto.auto_factory import _get_model_class +from ..models.auto.configuration_auto import AutoConfig +from ..models.auto.modeling_auto import MODEL_FOR_PRETRAINING_MAPPING, MODEL_MAPPING +from ..models.auto.processing_auto import PROCESSOR_MAPPING_NAMES, AutoProcessor +from ..models.auto.tokenization_auto import AutoTokenizer +from .import_utils import is_torch_available + + +if is_torch_available(): + import torch + import torch.nn as nn + +# Print the matrix with words as row labels +GREEN = "\033[92m" +YELLOW = "\033[93m" +RESET = "\033[0m" +BLACK_SQUARE = "■" +WHITE_SQUARE = "⬚" + + +def generate_attention_matrix_from_mask( + words, mask, img_token="", sliding_window=None, token_type_ids=None, image_seq_length=None +): + """ + Generates an attention matrix from a given attention mask. + + Optionally applies a sliding window mask (e.g., for Gemma2/3) and + marks regions where image tokens occur based on the specified `img_token`. + """ + mask = mask.int() + if mask.ndim == 3: + mask = mask[0, :, :] + if mask.ndim == 4: + mask = mask[0, 0, :, :] + + n = len(words) + max_word_length = max(len(repr(word)) for word in words) + first_img_idx = 0 + output = [] + + for i, k in enumerate(words): + if k == img_token and not first_img_idx: + first_img_idx = i + mask[i, i] = 2 # Mark yellow regions + if first_img_idx > 0 and (k != img_token or i == n - 1): + if i == n - 1: + i += 1 + mask[first_img_idx:i, first_img_idx:i] = 2 # Mark yellow regions + first_img_idx = 0 + + # Generate sliding window mask (size = 4), excluding img_token + sliding_window_mask = None + if sliding_window is not None: + sliding_window_mask = [[1 if (0 <= i - j < sliding_window) else 0 for j in range(n)] for i in range(n)] + + row_dummy = " ".join( + f"{YELLOW}{BLACK_SQUARE}{RESET}" + if mask[0, j] + else f"{GREEN}{BLACK_SQUARE}{RESET}" + if j == 0 + else BLACK_SQUARE + if mask[0, j] + else WHITE_SQUARE + for j in range(n) + ) + + if token_type_ids is not None: + is_special = token_type_ids == 1 + token_type_buckets = torch.where( + (token_type_ids.cumsum(-1) % 5 + is_special).bool(), token_type_ids.cumsum(-1), 0 + ) + boundaries = torch.arange(0, image_seq_length + 1, image_seq_length) + token_type_buckets = torch.bucketize(token_type_buckets, boundaries=boundaries) + + # Print headers + legend = f"{GREEN}{BLACK_SQUARE}{RESET}: i == j (diagonal) {YELLOW}{BLACK_SQUARE}{RESET}: token_type_ids" + output.append(" " + legend) + f_string = " " * (max_word_length + 5) + "Attention Matrix".ljust(len(row_dummy) // 2) + if sliding_window is not None: + f_string += "Sliding Window Mask" + output.append(f_string) + + vertical_header = [] + for idx, word in enumerate(words): + if mask[idx, idx] == 2: + vertical_header.append([f"{YELLOW}{k}{RESET}" for k in list(str(idx).rjust(len(str(n))))]) + else: + vertical_header.append(list(str(idx).rjust(len(str(n))))) + + vertical_header = list(map(list, zip(*vertical_header))) # Transpose + + for row in vertical_header: + output.append( + (max_word_length + 5) * " " + " ".join(row) + " | " + " ".join(row) + if sliding_window is not None + else "" + ) + for i, word in enumerate(words): + word_repr = repr(word).ljust(max_word_length) + colored_word = f"{YELLOW}{word_repr}{RESET}" if img_token in word else word_repr + row_display = " ".join( + f"{YELLOW}{BLACK_SQUARE}{RESET}" + if img_token in words[j] and mask[i, j] and img_token in word + else f"{GREEN}{BLACK_SQUARE}{RESET}" + if i == j + else BLACK_SQUARE + if mask[i, j] + else WHITE_SQUARE + for j in range(n) + ) + sliding_window_row = "" + if sliding_window is not None: + sliding_window_row = " ".join( + f"{YELLOW}{BLACK_SQUARE}{RESET}" + if img_token in words[j] and img_token in word and token_type_buckets[0, i] == token_type_buckets[0, j] + else f"{GREEN}{BLACK_SQUARE}{RESET}" + if i == j + else BLACK_SQUARE + if sliding_window_mask[i][j] + else WHITE_SQUARE + for j in range(n) + ) + + output.append(f"{colored_word}: {str(i).rjust(2)} {row_display} | {sliding_window_row}") + + return "\n".join(output) + + +class AttentionMaskVisualizer: + def __init__(self, model_name: str): + config = AutoConfig.from_pretrained(model_name) + self.image_token = "" + if hasattr(config.get_text_config(), "sliding_window"): + self.sliding_window = getattr(config.get_text_config(), "sliding_window", None) + try: + mapped_cls = _get_model_class(config, MODEL_MAPPING) + except Exception: + mapped_cls = _get_model_class(config, MODEL_FOR_PRETRAINING_MAPPING) + + if mapped_cls is None: + raise ValueError(f"Model name {model_name} is not supported for attention visualization") + self.mapped_cls = mapped_cls + + class _ModelWrapper(mapped_cls, nn.Module): + def __init__(self, config, model_name): + nn.Module.__init__(self) + self.dummy_module = nn.Linear(1, 1) + self.config = config + + self.model = _ModelWrapper(config, model_name) + self.model.to(config.dtype) + self.repo_id = model_name + self.config = config + + def __call__(self, input_sentence: str, suffix=""): + self.visualize_attention_mask(input_sentence, suffix=suffix) + + def visualize_attention_mask(self, input_sentence: str, suffix=""): + model = self.model + kwargs = {} + image_seq_length = None + if self.config.model_type in PROCESSOR_MAPPING_NAMES: + img = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg?download=true" + img = Image.open(io.BytesIO(httpx.get(img, follow_redirects=True).content)) + image_seq_length = 5 + processor = AutoProcessor.from_pretrained(self.repo_id, image_seq_length=image_seq_length) + if hasattr(processor, "image_token"): + image_token = processor.image_token + else: + image_token = processor.tokenizer.convert_ids_to_tokens([processor.image_token_id])[0] + + if image_token: + input_sentence = input_sentence.replace("", image_token) + + inputs = processor(images=img, text=input_sentence, suffix=suffix, return_tensors="pt") + + self.image_token = processor.tokenizer.convert_ids_to_tokens([processor.image_token_id])[0] + + attention_mask = inputs["attention_mask"] + if "token_type_ids" in inputs: # TODO inspect signature of update causal mask + kwargs["token_type_ids"] = inputs["token_type_ids"] + tokens = processor.tokenizer.convert_ids_to_tokens(inputs["input_ids"][0]) + else: + tokenizer = AutoTokenizer.from_pretrained(self.repo_id) + if tokenizer is None: + raise ValueError(f"Could not load tokenizer for {self.repo_id}") + tokens = tokenizer.tokenize(input_sentence) + attention_mask = tokenizer(input_sentence, return_tensors="pt")["attention_mask"] + if attention_mask is None: + raise ValueError(f"Model type {self.config.model_type} does not support attention visualization") + + model.config._attn_implementation = "eager" + model.train() + + batch_size, seq_length = attention_mask.shape + inputs_embeds = torch.zeros((batch_size, seq_length, model.config.hidden_size), dtype=self.model.dtype) + + causal_mask = create_causal_mask( + config=model.config, + inputs_embeds=inputs_embeds, + attention_mask=attention_mask, + past_key_values=None, + ) + + if causal_mask is None: + # attention_mask must be a tensor here + attention_mask = attention_mask.unsqueeze(1).unsqueeze(1).expand(batch_size, 1, seq_length, seq_length) + elif isinstance(causal_mask, torch.Tensor): + attention_mask = ~causal_mask.to(dtype=torch.bool) + else: + attention_mask = ~causal_mask + + top_bottom_border = "##" * ( + len(f"Attention visualization for {self.config.model_type} | {self.mapped_cls}") + 4 + ) # Box width adjusted to text length + side_border = "##" + print(f"\n{top_bottom_border}") + print( + "##" + + f" Attention visualization for \033[1m{self.config.model_type}:{self.repo_id}\033[0m {self.mapped_cls.__name__}".center( + len(top_bottom_border) + ) + + " " + + side_border, + ) + print(f"{top_bottom_border}") + f_string = generate_attention_matrix_from_mask( + tokens, + attention_mask, + img_token=self.image_token, + sliding_window=getattr(self.config, "sliding_window", None), + token_type_ids=kwargs.get("token_type_ids"), + image_seq_length=image_seq_length, + ) + print(f_string) + print(f"{top_bottom_border}") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/auto_docstring.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/auto_docstring.py new file mode 100644 index 0000000000000000000000000000000000000000..419579891e35530a2bface37fe7f7ecfedad1e91 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/auto_docstring.py @@ -0,0 +1,4515 @@ +# Copyright 2025 HuggingFace Inc. team. All rights reserved. +# +# 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. +from __future__ import annotations + +import inspect +import os +from collections.abc import Mapping +from functools import lru_cache +from pathlib import Path +from types import UnionType +from typing import ClassVar, Union, get_args, get_origin + +import regex as re +import typing_extensions + +from .doc import ( + MODELS_TO_PIPELINE, + PIPELINE_TASKS_TO_SAMPLE_DOCSTRINGS, + PT_SAMPLE_DOCSTRINGS, +) +from .generic import ModelOutput + + +PATH_TO_TRANSFORMERS = Path("src").resolve() / "transformers" + + +AUTODOC_FILES = [ + "configuration_*.py", + "modeling_*.py", + "tokenization_*.py", + "processing_*.py", + "image_processing_pil_*.py", + "image_processing_*.py", + "feature_extractor_*.py", +] + +PLACEHOLDER_TO_AUTO_MODULE = { + "image_processor_class": ("image_processing_auto", "IMAGE_PROCESSOR_MAPPING_NAMES"), + "tokenizer_class": ("tokenization_auto", "TOKENIZER_MAPPING_NAMES"), + "video_processor_class": ("video_processing_auto", "VIDEO_PROCESSOR_MAPPING_NAMES"), + "feature_extractor_class": ("feature_extraction_auto", "FEATURE_EXTRACTOR_MAPPING_NAMES"), + "processor_class": ("processing_auto", "PROCESSOR_MAPPING_NAMES"), + "config_class": ("configuration_auto", "CONFIG_MAPPING_NAMES"), + "model_class": ("modeling_auto", "MODEL_MAPPING_NAMES"), +} + +UNROLL_KWARGS_METHODS = { + "preprocess", + "__call__", +} + +UNROLL_KWARGS_CLASSES = { + "BaseImageProcessor", + "ProcessorMixin", +} +BASIC_KWARGS_TYPES = ["TextKwargs", "ImagesKwargs", "VideosKwargs", "AudioKwargs"] + +# Short indicator added to unrolled kwargs to distinguish them from regular args +KWARGS_INDICATOR = ", *kwargs*" + +HARDCODED_CONFIG_FOR_MODELS = { + "openai": "OpenAIGPTConfig", + "x-clip": "XCLIPConfig", + "kosmos2": "Kosmos2Config", + "kosmos2-5": "Kosmos2_5Config", + "donut": "DonutSwinConfig", + "esmfold": "EsmConfig", + "parakeet": "ParakeetCTCConfig", + "privacy-filter": "OpenAIPrivacyFilterConfig", + "lasr": "LasrCTCConfig", + "wav2vec2-with-lm": "Wav2Vec2Config", +} + +_re_checkpoint = re.compile(r"\[(.+?)\]\((https://huggingface\.co/.+?)\)") + +# Pre-compiled patterns used repeatedly at runtime. Compiling once here avoids +# repeated compilation overhead (and cache lookups) on every decorator call. +_re_example_or_return = re.compile(r"(?m)^([ \t]*)(?=Example|Return|```)") +_re_return = re.compile(r"(?m)^([ \t]*)(?=Return)") +_re_example = re.compile(r"(?m)^([ \t]*)(?=Example|```)") +_re_args_section = re.compile(r"(?:Args:)(\n.*)?(\n)?$", re.DOTALL) +_re_shape = re.compile(r"(of shape\s*(?:`.*?`|\(.*?\)))") +_re_default = re.compile(r"(defaults to \s*[^)]*)") +_re_param = re.compile( + r"^\s{0,0}(\w+)\s*\(\s*([^, \)]*)(\s*.*?)\s*\)\s*:\s*((?:(?!\n^\s{0,0}\w+\s*\().)*)", + re.DOTALL | re.MULTILINE, +) +_re_forward_ref = re.compile(r"ForwardRef\('([\w.]+)'\)") +_re_optional = re.compile(r"Optional\[(.*?)\]") +_re_placeholders = re.compile(r"{(.*?)}") +_re_model_task = None # built lazily because PT_SAMPLE_DOCSTRINGS isn't available yet + + +class ImageProcessorArgs: + images = { + "description": """ + Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If + passing in images with pixel values between 0 and 1, set `do_rescale=False`. + """, + "shape": None, + } + + videos = { + "description": """ + Video to preprocess. Expects a single or batch of videos with pixel values ranging from 0 to 255. If + passing in videos with pixel values between 0 and 1, set `do_rescale=False`. + """, + "shape": None, + } + + do_resize = { + "description": """ + Whether to resize the image. + """, + "shape": None, + } + + size = { + "description": """ + Describes the maximum input dimensions to the model. + """, + "shape": None, + } + + size_divisor = { + "description": """ + The size by which to make sure both the height and width can be divided. + """, + "shape": None, + } + + default_to_square = { + "description": """ + Whether to default to a square image when resizing, if size is an int. + """, + "shape": None, + } + + resample = { + "description": """ + Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only + has an effect if `do_resize` is set to `True`. + """, + "shape": None, + } + + do_center_crop = { + "description": """ + Whether to center crop the image. + """, + "shape": None, + } + + crop_size = { + "description": """ + Size of the output image after applying `center_crop`. + """, + "shape": None, + } + + do_pad = { + "description": """ + Whether to pad the image. Padding is done either to the largest size in the batch + or to a fixed square size per image. The exact padding strategy depends on the model. + """, + "shape": None, + } + + pad_size = { + "description": """ + The size in `{"height": int, "width" int}` to pad the images to. Must be larger than any image size + provided for preprocessing. If `pad_size` is not provided, images will be padded to the largest + height and width in the batch. Applied only when `do_pad=True.` + """, + "shape": None, + } + + do_rescale = { + "description": """ + Whether to rescale the image. + """, + "shape": None, + } + + rescale_factor = { + "description": """ + Rescale factor to rescale the image by if `do_rescale` is set to `True`. + """, + "shape": None, + } + + do_normalize = { + "description": """ + Whether to normalize the image. + """, + "shape": None, + } + + image_mean = { + "description": """ + Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`. + """, + "shape": None, + } + + image_std = { + "description": """ + Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to + `True`. + """, + "shape": None, + } + + do_convert_rgb = { + "description": """ + Whether to convert the image to RGB. + """, + "shape": None, + } + + return_tensors = { + "description": """ + Returns stacked tensors if set to `'pt'`, otherwise returns a list of tensors. + """, + "shape": None, + } + + data_format = { + "description": """ + Only `ChannelDimension.FIRST` is supported. Added for compatibility with slow processors. + """, + "shape": None, + } + + input_data_format = { + "description": """ + The channel dimension format for the input image. If unset, the channel dimension format is inferred + from the input image. Can be one of: + - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. + - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. + - `"none"` or `ChannelDimension.NONE`: image in (height, width) format. + """, + "shape": None, + } + + device = { + "description": """ + The device to process the images on. If unset, the device is inferred from the input images. + """, + "shape": None, + } + + disable_grouping = { + "description": """ + Whether to disable grouping of images by size to process them individually and not in batches. + If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on + empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157 + """, + "shape": None, + } + + image_seq_length = { + "description": """ + The number of image tokens to be used for each image in the input. + Added for backward compatibility but this should be set as a processor attribute in future models. + """, + "shape": None, + } + + # Used for the **kwargs summary line when unrolling typed kwargs (key: "__kwargs__") + __kwargs__ = { + "description": """ + Additional image preprocessing options. Model-specific kwargs are listed above; see the TypedDict class + for the complete list of supported arguments. + """, + "shape": None, + } + + +class ProcessorArgs: + # __init__ arguments + image_processor = { + "description": """ + The image processor is a required input. + """, + "type": "{image_processor_class}", + } + + tokenizer = { + "description": """ + The tokenizer is a required input. + """, + "type": "{tokenizer_class}", + } + + video_processor = { + "description": """ + The video processor is a required input. + """, + "type": "{video_processor_class}", + } + + audio_processor = { + "description": """ + The audio processor is a required input. + """, + "type": "{audio_processor_class}", + } + + feature_extractor = { + "description": """ + The feature extractor is a required input. + """, + "type": "{feature_extractor_class}", + } + + chat_template = { + "description": """ + A Jinja template to convert lists of messages in a chat into a tokenizable string. + """, + "type": "str", + } + + # __call__ arguments + text = { + "description": """ + The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings + (pretokenized string). If you pass a pretokenized input, set `is_split_into_words=True` to avoid ambiguity with batched inputs. + """, + } + + audio = { + "description": """ + The audio or batch of audios to be prepared. Each audio can be a NumPy array or PyTorch tensor. + In case of a NumPy array/PyTorch tensor, each audio should be of shape (C, T), where C is a number of channels, + and T is the sample length of the audio. + """, + } + + audios = { + "description": """ + The audio or batch of audios to be prepared. Each audio can be a NumPy array or PyTorch tensor. + In case of a NumPy array/PyTorch tensor, each audio should be of shape (C, T), where C is a number of channels, + and T is the sample length of the audio. + """, + } + + return_tensors = { + "description": """ + If set, will return tensors of a particular framework. Acceptable values are: + + - `'pt'`: Return PyTorch `torch.Tensor` objects. + - `'np'`: Return NumPy `np.ndarray` objects. + """, + "shape": None, + } + + # Standard tokenizer arguments + add_special_tokens = { + "description": """ + Whether or not to add special tokens when encoding the sequences. This will use the underlying + [`PretrainedTokenizerBase.build_inputs_with_special_tokens`] function, which defines which tokens are + automatically added to the input ids. This is useful if you want to add `bos` or `eos` tokens + automatically. + """, + "type": "bool", + } + + padding = { + "description": """ + Activates and controls padding. Accepts the following values: + + - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single + sequence is provided). + - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum + acceptable input length for the model if that argument is not provided. + - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different + lengths). + """, + "type": "bool, str or [`~utils.PaddingStrategy`]", + } + + truncation = { + "description": """ + Activates and controls truncation. Accepts the following values: + + - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or + to the maximum acceptable input length for the model if that argument is not provided. This will + truncate token by token, removing a token from the longest sequence in the pair if a pair of + sequences (or a batch of pairs) is provided. + - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the + maximum acceptable input length for the model if that argument is not provided. This will only + truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided. + - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the + maximum acceptable input length for the model if that argument is not provided. This will only + truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided. + - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths + greater than the model maximum admissible input size). + """, + "type": "bool, str or [`~tokenization_utils_base.TruncationStrategy`]", + } + + max_length = { + "description": """ + Controls the maximum length to use by one of the truncation/padding parameters. + + If left unset or set to `None`, this will use the predefined model maximum length if a maximum length + is required by one of the truncation/padding parameters. If the model has no specific maximum input + length (like XLNet) truncation/padding to a maximum length will be deactivated. + """, + "type": "int", + } + + stride = { + "description": """ + If set to a number along with `max_length`, the overflowing tokens returned when + `return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence + returned to provide some overlap between truncated and overflowing sequences. The value of this + argument defines the number of overlapping tokens. + """, + "type": "int", + } + + pad_to_multiple_of = { + "description": """ + If set will pad the sequence to a multiple of the provided value. Requires `padding` to be activated. + This is especially useful to enable using Tensor Cores on NVIDIA hardware with compute capability + `>= 7.5` (Volta). + """, + "type": "int", + } + + return_token_type_ids = { + "description": """ + Whether to return token type IDs. If left to the default, will return the token type IDs according to + the specific tokenizer's default, defined by the `return_outputs` attribute. + + [What are token type IDs?](../glossary#token-type-ids) + """, + "type": "bool", + } + + return_attention_mask = { + "description": """ + Whether to return the attention mask. If left to the default, will return the attention mask according + to the specific tokenizer's default, defined by the `return_outputs` attribute. + + [What are attention masks?](../glossary#attention-mask) + """, + "type": "bool", + } + + return_overflowing_tokens = { + "description": """ + Whether or not to return overflowing token sequences. If a pair of sequences of input ids (or a batch + of pairs) is provided with `truncation_strategy = longest_first` or `True`, an error is raised instead + of returning overflowing tokens. + """, + "type": "bool", + } + + return_special_tokens_mask = { + "description": """ + Whether or not to return special tokens mask information. + """, + "type": "bool", + } + + return_offsets_mapping = { + "description": """ + Whether or not to return `(char_start, char_end)` for each token. + + This is only available on fast tokenizers inheriting from [`PreTrainedTokenizerFast`], if using + Python's tokenizer, this method will raise `NotImplementedError`. + """, + "type": "bool", + } + + return_length = { + "description": """ + Whether or not to return the lengths of the encoded inputs. + """, + "type": "bool", + } + + verbose = { + "description": """ + Whether or not to print more information and warnings. + """, + "type": "bool", + } + + text_pair = { + "description": """ + Optional second sequence to be encoded. This can be a string, a list of strings (tokenized string using + the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids` + method). + """, + "type": "str, list[str] or list[int]", + } + + text_target = { + "description": """ + The sequence or batch of sequences to be encoded as target texts. Each sequence can be a string or a + list of strings (pretokenized string). If you pass pretokenized input, set `is_split_into_words=True` + to avoid ambiguity with batched inputs. + """, + "type": "str, list[str] or list[list[str]]", + } + + text_pair_target = { + "description": """ + The sequence or batch of sequences to be encoded as target texts. Each sequence can be a string or a + list of strings (pretokenized string). If you pass pretokenized input, set `is_split_into_words=True` + to avoid ambiguity with batched inputs. + """, + "type": "str, list[str] or list[list[str]]", + } + + is_split_into_words = { + "description": """ + Whether or not the input is already pre-tokenized (e.g., split into words). If set to `True`, the + tokenizer assumes the input is already split into words (for instance, by splitting it on whitespace) + which it will tokenize. This is useful for NER or token classification. + """, + "type": "bool", + } + + boxes = { + "description": """ + Word-level bounding boxes. Each bounding box should be normalized to be on a 0-1000 scale. + """, + "type": "list[list[int]] or list[list[list[int]]]", + } + + word_labels = { + "description": """ + Word-level integer labels (for token classification tasks such as FUNSD, CORD). + """, + "type": "list[int] or list[list[int]]", + } + + # Used for the **kwargs summary line when unrolling typed kwargs (key: "__kwargs__") + __kwargs__ = { + "description": """ + Additional processing options for each modality (text, images, videos, audio). Model-specific parameters + are listed above; see the TypedDict class for the complete list of supported arguments. + """, + "shape": None, + } + + +class ConfigArgs: + output_hidden_states = { + "description": """ + Whether or not the model should return all hidden-states. + """, + } + + chunk_size_feed_forward = { + "description": """ + The `dtype` of the weights. This attribute can be used to initialize the model to a non-default `dtype` + (which is normally `float32`) and thus allow for optimal storage allocation. For example, if the saved + model is `float16`, ideally we want to load it back using the minimal amount of memory needed to load + `float16` weights. + """, + } + + dtype = { + "description": """ + The chunk size of all feed forward layers in the residual attention blocks. A chunk size of `0` means that + the feed forward layer is not chunked. A chunk size of n means that the feed forward layer processes `n` < + sequence_length embeddings at a time. For more information on feed forward chunking, see [How does Feed + Forward Chunking work?](../glossary.html#feed-forward-chunking). + """, + } + + id2label = { + "description": """ + A map from index (for instance prediction index, or target index) to label. + """, + } + + label2id = { + "description": """ + A map from label to index for the model. + """, + } + + problem_type = { + "description": """ + Problem type for `XxxForSequenceClassification` models. Can be one of `"regression"`, + `"single_label_classification"` or `"multi_label_classification"`. + """, + } + + tokenizer_class = { + "description": """ + The class name of model's tokenizer. + """, + } + + vocab_size = { + "description": """ + Vocabulary size of the model. Defines the number of different tokens that can be represented by the `input_ids`. + """, + } + + hidden_size = { + "description": """ + Dimension of the hidden representations. + """, + } + + intermediate_size = { + "description": """ + Dimension of the MLP representations. + """, + } + + head_dim = { + "description": """ + The attention head dimension. If None, it will default to hidden_size // num_attention_heads + """ + } + + num_hidden_layers = { + "description": """ + Number of hidden layers in the Transformer decoder. + """, + } + + num_attention_heads = { + "description": """ + Number of attention heads for each attention layer in the Transformer decoder. + """, + } + + num_key_value_heads = { + "description": """ + This is the number of key_value heads that should be used to implement Grouped Query Attention. If + `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if + `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When + converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed + by meanpooling all the original heads within that group. For more details, check out [this + paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to + `num_attention_heads`. + """, + } + hidden_act = { + "description": """ + The non-linear activation function (function or string) in the decoder. For example, `"gelu"`, + `"relu"`, `"silu"`, etc. + """, + } + + max_position_embeddings = { + "description": """ + The maximum sequence length that this model might ever be used with. + """, + } + + initializer_range = { + "description": """ + The standard deviation of the truncated_normal_initializer for initializing all weight matrices. + """, + } + + rms_norm_eps = { + "description": """ + The epsilon used by the rms normalization layers. + """, + } + + use_cache = { + "description": """ + Whether or not the model should return the last key/values attentions (not used by all models). Only + relevant if `config.is_decoder=True` or when the model is a decoder-only generative model. + """, + } + + rope_parameters = { + "description": """ + Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain + a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE + with longer `max_position_embeddings`. + """, + } + + attention_bias = { + "description": """ + Whether to use a bias in the query, key, value and output projection layers during self-attention. + """, + } + + mlp_bias = { + "description": """ + Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers. + """, + } + + attention_dropout = { + "description": """ + The dropout ratio for the attention probabilities. + """, + } + + pretraining_tp = { + "description": """ + Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this + document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to + understand more about it. This value is necessary to ensure exact reproducibility of the pretraining + results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232). + """, + } + + pad_token_id = { + "description": """ + Token id used for padding in the vocabulary. + """, + } + + eos_token_id = { + "description": """ + Token id used for end-of-stream in the vocabulary. + """, + } + + bos_token_id = { + "description": """ + Token id used for beginning-of-stream in the vocabulary. + """, + } + + sep_token_id = { + "description": """ + Token id used for separator in the vocabulary. + """, + } + + cls_token_id = { + "description": """ + Token id used for CLS in the vocabulary. + """, + } + + tie_word_embeddings = { + "description": """ + Whether to tie weight embeddings according to model's `tied_weights_keys` mapping. + """, + } + + d_model = { + "description": """ + Size of the encoder layers and the pooler layer. + """, + } + + d_kv = { + "description": """ + Size of the key, query, value projections per attention head. The `inner_dim` of the projection layer will + be defined as `num_heads * d_kv`. + """, + } + + num_decoder_layers = { + "description": """ + Number of hidden layers in the Transformer decoder. Will use the same value as `num_layers` if not set. + """, + } + + num_encoder_layers = { + "description": """ + Number of hidden layers in the Transformer encoder. Will use the same value as `num_layers` if not set. + """, + } + + dropout_rate = { + "description": """ + The ratio for all dropout layers. + """, + } + + classifier_dropout = { + "description": """ + The dropout ratio for classifier. + """, + } + + layer_norm_eps = { + "description": """ + The epsilon used by the layer normalization layers. + """, + } + + initializer_factor = { + "description": """ + A factor for initializing all weight matrices (should be kept to 1, used internally for initialization + testing). + """, + } + + encoder_attention_heads = { + "description": """ + Number of attention heads for each attention layer in the Transformer encoder. + """, + } + + decoder_attention_heads = { + "description": """ + Number of attention heads for each attention layer in the Transformer decoder. + """, + } + + decoder_ffn_dim = { + "description": """ + Dimensionality of the "intermediate" (often named feed-forward) layer in decoder. + """, + } + + encoder_ffn_dim = { + "description": """ + Dimensionality of the "intermediate" (often named feed-forward) layer in encoder. + """, + } + + activation_dropout = { + "description": """ + The dropout ratio for activations inside the fully connected layer. + """, + } + + encoder_layerdrop = { + "description": """ + The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556) + for more details. + """, + } + + decoder_layerdrop = { + "description": """ + The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556) + for more details. + """, + } + + scale_embedding = { + "description": """ + Whether to scale embeddings by dividing by sqrt(d_model). + """, + } + + forced_eos_token_id = { + "description": """ + The id of the token to force as the last generated token when `max_length` is reached. Usually set to + `eos_token_id`. + """, + } + + moe_intermediate_size = { + "description": """ + Intermediate size of the routed expert MLPs. + """, + } + + num_experts = { + "description": """ + Number of routed experts in MoE layers. + + """, + } + + num_experts_per_tok = { + "description": """ + Number of experts to route each token to. This is the top-k value for the token-choice routing. + """, + } + + num_shared_experts = { + "description": """ + Number of shared experts that are always activated for all tokens. + """, + } + + layer_types = { + "description": """ + A list that explicitly maps each layer index with its layer type. If not provided, it will be automatically + generated based on config values. + """, + } + + norm_topk_prob = { + "description": """ + Whether to normalize the weights of the routed experts. + + """, + } + + topk_group = { + "description": """ + Number of selected groups for each token (for each token, ensuring the selected experts is only within `topk_group` groups). + """, + } + + qk_rope_head_dim = { + "description": """ + Dimension of the query/key heads that use rotary position embeddings. + """, + } + + v_head_dim = { + "description": """ + Dimension of the value heads. + """, + } + + qk_nope_head_dim = { + "description": """ + Dimension of the query/key heads that don't use rotary position embeddings. + """, + } + + kv_lora_rank = { + "description": """ + Rank of the LoRA matrices for key and value projections. + """, + } + + q_lora_rank = { + "description": """ + Rank of the LoRA matrices for query projections. + """, + } + + routed_scaling_factor = { + "description": """ + Scaling factor or routed experts. + """, + } + + n_routed_experts = { + "description": """ + Number of routed experts. + """, + } + + n_shared_experts = { + "description": """ + Number of shared experts. + """, + } + + vision_config = { + "description": """ + The config object or dictionary of the vision backbone. + """, + } + + text_config = { + "description": """ + The config object or dictionary of the text backbone. + """, + } + + projector_hidden_act = { + "description": """ + The activation function used by the multimodal projector. + """, + } + + vision_feature_select_strategy = { + "description": """ + The feature selection strategy used to select the vision feature from the vision backbone. + """, + } + + vision_feature_layer = { + "description": """ + The index of the layer to select the vision feature. If multiple indices are provided, + the vision feature of the corresponding indices will be concatenated to form the + vision features. + """, + } + + multimodal_projector_bias = { + "description": """ + Whether to use bias in the multimodal projector. + """, + } + + image_token_id = { + "description": """ + The image token index used as a placeholder for input images. + """, + } + + video_token_id = { + "description": """ + The video token index used as a placeholder for input videos. + """, + } + + audio_token_id = { + "description": """ + The audio token index used as a placeholder for input audio. + """, + } + + image_seq_length = { + "description": """ + Sequence length of one image embedding. + """, + } + + video_seq_length = { + "description": """ + Sequence length of one video embedding. + """, + } + + add_cross_attention = { + "description": """ + Whether cross-attention layers should be added to the model. + """, + } + + is_decoder = { + "description": """ + Whether the model is used as a decoder or not. If `False`, the model is used as an encoder. + """, + } + + sliding_window = { + "description": """ + Sliding window attention window size. If `None`, no sliding window is applied. + """, + } + + use_sliding_window = { + "description": """ + Whether to use sliding window attention. + """, + } + + shared_expert_intermediate_size = { + "description": """ + Intermediate size of the shared expert MLPs. + """, + } + + decoder_sparse_step = { + "description": """ + The frequency of adding a sparse MoE layer. The default is 1, which means all decoder layers are sparse MoE. + """, + } + + output_router_logits = { + "description": """ + Whether or not the router logits should be returned by the model. Enabling this will also allow the model + to output the auxiliary loss, including load balancing loss and router z-loss. + """, + } + + router_aux_loss_coef = { + "description": """ + Auxiliary load balancing loss coefficient. Used to penalize uneven expert routing in MoE models. + """, + } + + out_indices = { + "description": """ + Indices of the intermediate hidden states (feature maps) to return from the backbone. Each index + corresponds to one stage of the model. + """, + } + + out_features = { + "description": """ + Names of the intermediate hidden states (feature maps) to return from the backbone. One of `"stem"`, + `"stage1"`, `"stage2"`, etc. + """, + } + + image_size = { + "description": """ + The size (resolution) of each image. + """, + } + + patch_size = { + "description": """ + The size (resolution) of each patch. + """, + } + + num_channels = { + "description": """ + The number of input channels. + """, + } + + num_mel_bins = { + "description": """ + Number of mel features used per input frame. Should correspond to the value used in the + `AutoFeatureExtractor` class. + """, + } + + sampling_rate = { + "description": """ + The sampling rate at which the audio files should be digitalized expressed in hertz (Hz). + """, + } + + hidden_dropout = { + "description": """ + The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. + """, + } + + mlp_ratio = { + "description": """ + Ratio of the MLP hidden dim to the embedding dim. + """, + } + + qkv_bias = { + "description": """ + Whether to add a bias to the queries, keys and values. + """, + } + + n_embd = { + "description": """ + Dimensionality of the embeddings and hidden states. + """, + } + + resid_pdrop = { + "description": """ + The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. + """, + } + + embd_pdrop = { + "description": """ + The dropout ratio for the embeddings. + """, + } + + clip_qkv = { + "description": """ + If not `None`, cap the absolute value of the query, key, and value tensors to this value. + """, + } + + type_vocab_size = { + "description": """ + The vocabulary size of the `token_type_ids`. + """, + } + + audio_config = { + "description": """ + The config object or dictionary of the audio backbone. + """, + } + + layerdrop = { + "description": """ + The LayerDrop probability. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556) for + more details. + """, + } + + expert_capacity = { + "description": """ + The number of tokens that each expert can process. If `None`, `expert_capacity` will be set to + `(sequence_length / num_experts) * capacity_factor`. + """, + } + + decoder_start_token_id = { + "description": """ + If an encoder-decoder model starts decoding with a different token than `bos`, the id of that token. + """, + } + + is_encoder_decoder = { + "description": """ + Whether the model is used as an encoder/decoder or not. + """, + } + + num_codebooks = { + "description": """ + The number of parallel codebooks used by the model. + """, + } + + codebook_dim = { + "description": """ + Dimensionality of each codebook embedding vector. + """, + } + + hidden_sizes = { + "description": """ + Dimensionality (hidden size) at each stage of the model. + """, + } + + depths = { + "description": """ + Depth of each layer in the Transformer. + """, + } + + patch_sizes = { + "description": """ + Patch size at each stage of the model. + """, + } + + strides = { + "description": """ + Stride at each stage of the model. + """, + } + + router_jitter_noise = { + "description": """ + Amount of noise to add to the router logits during training for better load balancing. + """, + } + + num_local_experts = { + "description": """ + Number of local experts on each device. `num_experts` should be divisible by `num_local_experts`. + """, + } + + qk_layernorm = { + "description": """ + Whether to use query-key normalization in the attention. + """, + } + + backbone_config = { + "description": """ + The configuration of the backbone model. + """, + } + + no_object_weight = { + "description": """ + Relative classification weight of the no-object class in the object detection loss. + """, + } + + class_weight = { + "description": """ + Relative weight of the classification error in the Hungarian matching cost. + """, + } + + mask_weight = { + "description": """ + Relative weight of the focal loss in the panoptic segmentation loss. + """, + } + + dice_weight = { + "description": """ + Relative weight of the dice loss in the panoptic segmentation loss. + """, + } + + class_cost = { + "description": """ + Relative weight of the classification error in the Hungarian matching cost. + """, + } + + bbox_cost = { + "description": """ + Relative weight of the L1 bounding box error in the Hungarian matching cost. + """, + } + + giou_cost = { + "description": """ + Relative weight of the generalized IoU loss in the Hungarian matching cost. + """, + } + + focal_alpha = { + "description": """ + Alpha parameter in the focal loss. + """, + } + + mask_loss_coefficient = { + "description": """ + Relative weight of the focal loss in the panoptic segmentation loss. + """, + } + + giou_loss_coefficient = { + "description": """ + Relative weight of the generalized IoU loss in the panoptic segmentation loss. + """, + } + + bbox_loss_coefficient = { + "description": """ + Relative weight of the L1 bounding box loss in the panoptic segmentation loss. + """, + } + + cls_loss_coefficient = { + "description": """ + Relative weight of the classification loss in the panoptic segmentation loss. + """, + } + + dice_loss_coefficient = { + "description": """ + Relative weight of the dice loss in the panoptic segmentation loss. + """, + } + + semantic_loss_ignore_index = { + "description": """ + The index that is ignored by the loss function of the semantic segmentation model. + """, + } + + projection_dim = { + "description": """ + Dimensionality of text and vision projection layers. + """, + } + + logit_scale_init_value = { + "description": """ + The initial value of the *logit_scale* parameter. + """, + } + + num_dense_layers = { + "description": """ + Number of initial dense layers before MoE layers begin. Layers with index < num_dense_layers will use + standard dense MLPs instead of MoE. + """, + } + + drop_path_rate = { + "description": """ + Drop path rate for the patch fusion. + """, + } + + vq_config = { + "description": """ + Configuration dict of the vector quantize module. + """, + } + + num_embeddings = { + "description": """ + Number of codebook embeddings. + """, + } + + double_latent = { + "description": """ + Whether to use double z channels. + """, + } + + latent_channels = { + "description": """ + Number of channels for the latent space. + """, + } + + qformer_config = { + "description": """ + Configuration dict of the Q-Former module. + """, + } + + conv_kernel_size = { + "description": """ + The size of the convolutional kernel. + """, + } + + output_stride = { + "description": """ + The ratio between the spatial resolution of the input and output feature maps. + """, + } + + depth_multiplier = { + "description": """ + Shrinks or expands the number of channels in each layer. This is sometimes also called "alpha" or "width multiplier". + """, + } + + use_absolute_position_embeddings = { + "description": """ + Whether to use absolute position embeddings. + """, + } + + use_relative_position_bias = { + "description": """ + Whether to use relative position bias in the self-attention layers. + """, + } + + layer_scale_init_value = { + "description": """ + Scale to use in the self-attention layers. 0.1 for base, 1e-6 for large. Set 0 to disable layer scale. + """, + } + + vlm_config = { + "description": """ + The config object or dictionary of the vision-language backbone. + """, + } + + init_xavier_std = { + "description": """ + The scaling factor used for the Xavier initialization of the cross-attention weights. + """, + } + + auxiliary_loss = { + "description": """ + Whether auxiliary decoding losses (losses at each decoder layer) are to be used. + """, + } + + encoder_config = { + "description": """ + The config object or dictionary of the encoder backbone. + """, + } + + decoder_config = { + "description": """ + The config object or dictionary of the decoder backbone. + """, + } + + embedding_multiplier = { + "description": """ + Scaling factor applied to the word embeddings. Used to scale the embeddings relative to the hidden size. + """, + } + + logits_scaling = { + "description": """ + Scaling factor applied to the output logits before computing the probability distribution. + """, + } + + residual_multiplier = { + "description": """ + Scaling factor applied to the residual connections. + """, + } + + attention_multiplier = { + "description": """ + Scaling factor applied to the attention weights. + """, + } + + classifier_activation = { + "description": """ + The activation function for the classification head. + """, + } + + return_dict = { + "description": """ + Whether to return a `ModelOutput` (dataclass) instead of a plain tuple. + """, + } + + router_z_loss_coef = { + "description": """ + Coefficient for the router z-loss, which penalizes large router logits to improve training stability. + """, + } + + final_logit_softcapping = { + "description": """ + Soft-capping value applied to the final logits before computing the probability distribution. Logits are + scaled by `tanh(logit / cap) * cap`. + """, + } + + cross_attention_hidden_size = { + "description": """ + Hidden size of the encoder outputs projected into the cross-attention key/value space of the decoder. Used + when the encoder and decoder have different hidden sizes. + """, + } + + input_dim = { + "description": """ + Dimensionality of the input acoustic features (e.g., number of mel-filterbank channels). + """, + } + + use_auxiliary_loss = { + "description": """ + Whether to calculate loss using intermediate predictions from transformer decoder. + """, + } + + batch_norm_eps = { + "description": """ + The epsilon used by the batch normalization layers. + """, + } + + max_window_layers = { + "description": """ + The number of layers using full attention. The first `max_window_layers` layers will use full attention, while any + additional layer afterwards will use SWA (Sliding Window Attention). + """, + } + + ctc_loss_reduction = { + "description": """ + Specifies the reduction to apply to the output of `torch.nn.CTCLoss`. Only relevant when training. + """, + } + + mask_feature_prob = { + "description": """ + Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The + masking procedure generates `mask_feature_prob*len(feature_axis)/mask_time_length` independent masks over + the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector + span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap + may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment` is + `True`. + """, + } + + eos_coefficient = { + "description": """ + Relative classification weight of the 'no-object' class in the object detection loss. + """, + } + + num_labels = { + "description": """ + Number of labels to use in the last layer added to the model, typically for a classification task. + """, + } + + depth = { + "description": """ + Number of Transformer layers in the vision encoder. + """, + } + + temporal_patch_size = { + "description": """ + Temporal patch size used in the 3D patch embedding for video inputs. + """, + } + + spatial_merge_size = { + "description": """ + The size of the spatial merge window used to reduce the number of visual tokens by merging neighboring patches. + """, + } + + vision_start_token_id = { + "description": """ + Token ID that marks the start of a visual segment in the multimodal input sequence. + """, + } + + vision_end_token_id = { + "description": """ + Token ID that marks the end of a visual segment in the multimodal input sequence. + """, + } + + mamba_n_heads = { + "description": """ + The number of mamba heads used in the v2 implementation. + """, + } + + mamba_d_head = { + "description": """ + Head embedding dimension size + """, + } + + mamba_n_groups = { + "description": """ + The number of the mamba groups used in the v2 implementation. + """, + } + + mamba_d_conv = { + "description": """ + The size of the mamba convolution kernel + """, + } + + mamba_expand = { + "description": """ + Expanding factor (relative to hidden_size) used to determine the mamba intermediate size + """, + } + + mamba_chunk_size = { + "description": """ + The chunks in which to break the sequence when doing prefill/training + """, + } + + mamba_conv_bias = { + "description": """ + Flag indicating whether or not to use bias in the convolution layer of the mamba mixer block. + """, + } + + mamba_proj_bias = { + "description": """ + Flag indicating whether or not to use bias in the input and output projections (["in_proj", "out_proj"]) of the mamba mixer block + """, + } + + time_step_min = { + "description": """ + Minimum `time_step` used to bound `dt_proj.bias`. + """, + } + + time_step_max = { + "description": """ + Maximum `time_step` used to bound `dt_proj.bias`. + """, + } + + time_step_limit = { + "description": """ + Accepted range of time step values for clamping. + """, + } + + expand_ratio = { + "description": """ + Expand ratio to set the output dimensions for the expansion + """, + } + + state_size = { + "description": """ + Size of the SSM state (latent state dimension) in the Mamba layers. + """, + } + + time_step_rank = { + "description": """ + Rank of the delta (time step) projection. Can be `"auto"` to set it automatically. + """, + } + + time_step_floor = { + "description": """ + Minimum allowed value for the discrete time step delta after softplus activation. + """, + } + + time_step_scale = { + "description": """ + Scale applied to the time step delta before discretization. + """, + } + + time_step_init_scheme = { + "description": """ + Initialization scheme for the time step delta. Can be `"random"` or `"uniform"`. + """, + } + + mamba_d_ssm = { + "description": """ + Inner state size of the SSM (state-space model) in the Mamba layers of FalconH1. + """, + } + + mamba_norm_before_gate = { + "description": """ + Whether to apply normalization before the gating mechanism in the Mamba mixer. + """, + } + + mamba_rms_norm = { + "description": """ + Whether to use RMS normalization in the Mamba layers (as opposed to standard LayerNorm). + """, + } + + mamba_d_state = state_size + mamba_num_heads = mamba_n_heads + mamba_head_dim = mamba_d_head + num_input_channels = num_channels + audio_channels = num_channels + input_channels = num_channels + in_channels = num_channels + in_chans = num_channels + scale_attn_weights = scale_embedding + attention_probs_dropout_prob = attention_dropout + attn_pdrop = attention_dropout + attn_dropout = attention_dropout + dropout = dropout_rate + resid_dropout = resid_pdrop + residual_dropout = resid_pdrop + emb_pdrop = embd_pdrop + embed_dropout = embd_pdrop + embedding_dropout = embd_pdrop + hidden_dropout_prob = hidden_dropout + hidden_dropout_rate = hidden_dropout + classifier_dropout_prob = classifier_dropout + classifier_dropout_rate = classifier_dropout + dropout_prob = dropout + dropout_p = dropout + decoder_attention_dropout = attention_dropout + decoder_dropout = dropout + encoder_dropout = dropout + + route_scale = routed_scaling_factor + activation_function = hidden_act + hidden_dim = hidden_size + num_decoder_attention_heads = decoder_attention_heads + num_encoder_attention_heads = encoder_attention_heads + decoder_num_heads = decoder_attention_heads + decoder_num_attention_heads = decoder_attention_heads + encoder_num_heads = encoder_attention_heads + encoder_num_attention_heads = encoder_attention_heads + encoder_layers = num_encoder_layers + decoder_layers = num_decoder_layers + decoder_num_layers = num_decoder_layers + encoder_num_layers = num_encoder_layers + d_ff = intermediate_size + dim_ff = intermediate_size + n_inner = intermediate_size + decoder_intermediate_size = intermediate_size + num_kv_heads = num_key_value_heads + num_layers = num_hidden_layers + n_layers = num_hidden_layers + n_layer = num_hidden_layers + layers = num_layers + encoder_num_hidden_layers = encoder_layers + decoder_num_hidden_layers = decoder_layers + num_heads = num_attention_heads + n_heads = num_attention_heads + n_head = num_attention_heads + hidden_activation = hidden_act + activation = hidden_act + mlp_hidden_act = hidden_act + d_head = head_dim + d_inner = intermediate_size + dim_head = head_dim + ffn_dim = intermediate_size + attention_heads = num_attention_heads + n_positions = max_position_embeddings + init_std = initializer_range + initializer_std = initializer_range + projector_bias = multimodal_projector_bias + image_token_index = image_token_id + video_token_index = video_token_id + audio_token_index = audio_token_id + embedding_size = n_embd + embed_dim = n_embd + projection_hidden_act = projector_hidden_act + layer_norm_epsilon = layer_norm_eps + rms_norm = rms_norm_eps + norm_eps = layer_norm_eps + eps = layer_norm_eps + norm_epsilon = layer_norm_eps + qk_layernorms = qk_layernorm + use_qk_norm = qk_layernorm + use_qkv_bias = qkv_bias + + decoder_hidden_act = hidden_act + decoder_hidden_dim = hidden_size + decoder_hidden_size = hidden_size + encoder_hidden_dim = hidden_size + encoder_hidden_size = hidden_size + layer_scale_initial_scale = layer_scale_init_value + multi_modal_projector_bias = projector_bias + projector_hidden_size = projection_dim + projection_size = projection_dim + kernel_size = conv_kernel_size + conv_kernel = conv_kernel_size + use_absolute_embeddings = use_absolute_position_embeddings + use_abs_pos = use_absolute_position_embeddings + use_rel_pos = use_relative_position_bias + aux_loss_coef = router_aux_loss_coef + embedding_dimension = embed_dim + embedding_dim = embed_dim + emb_dim = embed_dim + n_codebooks = num_codebooks + codebook_size = num_codebooks + layers_block_type = layer_types + sample_rate = sampling_rate + text_vocab_size = vocab_size + + +class ModelArgs: + labels = { + "description": """ + Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., + config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored + (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. + """, + "shape": "of shape `(batch_size, sequence_length)`", + } + + num_logits_to_keep = { + "description": """ + Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all + `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that + token can save memory, which becomes pretty significant for long sequences or large vocabulary size. + """, + "shape": None, + } + + input_ids = { + "description": """ + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default. + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + """, + "shape": "of shape `(batch_size, sequence_length)`", + } + + input_values = { + "description": """ + Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file + into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library + (`pip install torchcodec`) or the soundfile library (`pip install soundfile`). + To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion + into a tensor of type `torch.FloatTensor`. See [`{processor_class}.__call__`] for details. + """, + "shape": "of shape `(batch_size, sequence_length)`", + } + + attention_mask = { + "description": """ + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + """, + "shape": "of shape `(batch_size, sequence_length)`", + } + + decoder_attention_mask = { + "description": """ + Mask to avoid performing attention on certain token indices. By default, a causal mask will be used, to + make sure the model can only look at previous inputs in order to predict the future. + """, + "shape": "of shape `(batch_size, target_sequence_length)`", + } + + encoder_hidden_states = { + "description": """ + Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention + if the model is configured as a decoder. + """, + "shape": "of shape `(batch_size, sequence_length, hidden_size)`", + } + + encoder_attention_mask = { + "description": """ + Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in + the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + """, + "shape": "of shape `(batch_size, sequence_length)`", + } + + token_type_ids = { + "description": """ + Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`: + + - 0 corresponds to a *sentence A* token, + - 1 corresponds to a *sentence B* token. + + [What are token type IDs?](../glossary#token-type-ids) + """, + "shape": "of shape `(batch_size, sequence_length)`", + } + + mm_token_type_ids = { + "description": """ + Indices of input sequence tokens matching each modality. For example text (0), image (1), video (2). + Multimodal token type ids can be obtained using [`AutoProcessor`]. See [`ProcessorMixin.__call__`] for details. + + """, + "shape": "of shape `(batch_size, sequence_length)`", + } + + position_ids = { + "description": """ + Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`. + + [What are position IDs?](../glossary#position-ids) + """, + "shape": "of shape `(batch_size, sequence_length)`", + } + + past_key_values = { + "description": """ + Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention + blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values` + returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`. + + Only [`~cache_utils.Cache`] instance is allowed as input, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). + If no `past_key_values` are passed, [`~cache_utils.DynamicCache`] will be initialized by default. + + The model will output the same cache format that is fed as input. + + If `past_key_values` are used, the user is expected to input only unprocessed `input_ids` (those that don't + have their past key value states given to this model) of shape `(batch_size, unprocessed_length)` instead of all `input_ids` + of shape `(batch_size, sequence_length)`. + """, + "shape": None, + } + + inputs_embeds = { + "description": """ + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This + is useful if you want more control over how to convert `input_ids` indices into associated vectors than the + model's internal embedding lookup matrix. + """, + "shape": "of shape `(batch_size, sequence_length, hidden_size)`", + } + + decoder_input_ids = { + "description": """ + Indices of decoder input sequence tokens in the vocabulary. + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are decoder input IDs?](../glossary#decoder-input-ids) + """, + "shape": "of shape `(batch_size, target_sequence_length)`", + } + + decoder_inputs_embeds = { + "description": """ + Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded + representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be + input (see `past_key_values`). This is useful if you want more control over how to convert + `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix. + + If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value + of `inputs_embeds`. + """, + "shape": "of shape `(batch_size, target_sequence_length, hidden_size)`", + } + + use_cache = { + "description": """ + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see + `past_key_values`). + """, + "shape": None, + } + + output_attentions = { + "description": """ + Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned + tensors for more detail. + """, + "shape": None, + } + + output_hidden_states = { + "description": """ + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for + more detail. + """, + "shape": None, + } + + return_dict = { + "description": """ + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. + """, + "shape": None, + } + + hidden_states = { + "description": """ input to the layer of shape `(batch, seq_len, embed_dim)""", + "shape": None, + } + + interpolate_pos_encoding = { + "description": """ + Whether to interpolate the pre-trained position encodings. + """, + "shape": None, + } + + position_embeddings = { + "description": """ + Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`, + with `head_dim` being the embedding dimension of each attention head. + """, + "shape": None, + } + + config = { + "description": """ + Model configuration class with all the parameters of the model. Initializing with a config file does not + load the weights associated with the model, only the configuration. Check out the + [`~PreTrainedModel.from_pretrained`] method to load the model weights. + """, + "shape": None, + } + + start_positions = { + "description": """ + Labels for position (index) of the start of the labelled span for computing the token classification loss. + Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence + are not taken into account for computing the loss. + """, + "shape": "of shape `(batch_size,)`", + } + + end_positions = { + "description": """ + Labels for position (index) of the end of the labelled span for computing the token classification loss. + Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence + are not taken into account for computing the loss. + """, + "shape": "of shape `(batch_size,)`", + } + + encoder_outputs = { + "description": """ + Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`) + `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of + hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder. + """, + "shape": None, + } + + output_router_logits = { + "description": """ + Whether or not to return the logits of all the routers. They are useful for computing the router loss, and + should not be returned during inference. + """, + "shape": None, + } + + logits_to_keep = { + "description": """ + If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all + `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that + token can save memory, which becomes pretty significant for long sequences or large vocabulary size. + If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension. + This is useful when using packed tensor format (single dimension for batch and sequence length). + """, + "shape": None, + } + + pixel_values = { + "description": """ + The tensors corresponding to the input images. Pixel values can be obtained using + [`{image_processor_class}`]. See [`{image_processor_class}.__call__`] for details ([`{processor_class}`] uses + [`{image_processor_class}`] for processing images). + """, + "shape": "of shape `(batch_size, num_channels, image_size, image_size)`", + } + + pixel_values_videos = { + "description": """ + The tensors corresponding to the input video. Pixel values for videos can be obtained using + [`{video_processor_class}`]. See [`{video_processor_class}.__call__`] for details ([`{processor_class}`] uses + [`{video_processor_class}`] for processing videos). + """, + "shape": "of shape `(batch_size, num_frames, num_channels, frame_size, frame_size)`", + } + + vision_feature_layer = { + "description": """ + The index of the layer to select the vision feature. If multiple indices are provided, + the vision feature of the corresponding indices will be concatenated to form the + vision features. + """, + "shape": None, + } + + vision_feature_select_strategy = { + "description": """ + The feature selection strategy used to select the vision feature from the vision backbone. + Can be one of `"default"` or `"full"`. + """, + "shape": None, + } + + image_sizes = { + "description": """ + The sizes of the images in the batch, being (height, width) for each image. + """, + "shape": "of shape `(batch_size, 2)`", + } + + pixel_mask = { + "description": """ + Mask to avoid performing attention on padding pixel values. Mask values selected in `[0, 1]`: + + - 1 for pixels that are real (i.e. **not masked**), + - 0 for pixels that are padding (i.e. **masked**). + + [What are attention masks?](../glossary#attention-mask) + """, + "shape": "of shape `(batch_size, height, width)`", + } + + input_features = { + "description": """ + The tensors corresponding to the input audio features. Audio features can be obtained using + [`{feature_extractor_class}`]. See [`{feature_extractor_class}.__call__`] for details ([`{processor_class}`] uses + [`{feature_extractor_class}`] for processing audios). + """, + "shape": "of shape `(batch_size, sequence_length, feature_dim)`", + } + + +class ModelOutputArgs: + last_hidden_state = { + "description": """ + Sequence of hidden-states at the output of the last layer of the model. + """, + "shape": "of shape `(batch_size, sequence_length, hidden_size)`", + } + + past_key_values = { + "description": """ + It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). + + Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if + `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values` + input) to speed up sequential decoding. + """, + "shape": None, + "additional_info": "returned when `use_cache=True` is passed or when `config.use_cache=True`", + } + + hidden_states = { + "description": """ + Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. + + Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. + """, + "shape": None, + "additional_info": "returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`", + } + + attentions = { + "description": """ + Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, + sequence_length)`. + + Attentions weights after the attention softmax, used to compute the weighted average in the self-attention + heads. + """, + "shape": None, + "additional_info": "returned when `output_attentions=True` is passed or when `config.output_attentions=True`", + } + + pooler_output = { + "description": """ + Last layer hidden-state after a pooling operation on the spatial dimensions. + """, + "shape": "of shape `(batch_size, hidden_size)`", + } + + cross_attentions = { + "description": """ + Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, + sequence_length)`. + + Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the + weighted average in the cross-attention heads. + """, + "shape": None, + "additional_info": "returned when `output_attentions=True` is passed or when `config.output_attentions=True`", + } + + decoder_hidden_states = { + "description": """ + Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. + + Hidden-states of the decoder at the output of each layer plus the initial embedding outputs. + """, + "shape": None, + "additional_info": "returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`", + } + + decoder_attentions = { + "description": """ + Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, + sequence_length)`. + + Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the + self-attention heads. + """, + "shape": None, + "additional_info": "returned when `output_attentions=True` is passed or when `config.output_attentions=True`", + } + + encoder_last_hidden_state = { + "description": """ + Sequence of hidden-states at the output of the last layer of the encoder of the model. + """, + "shape": "of shape `(batch_size, sequence_length, hidden_size)`", + } + + encoder_hidden_states = { + "description": """ + Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. + + Hidden-states of the encoder at the output of each layer plus the initial embedding outputs. + """, + "shape": None, + "additional_info": "returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`", + } + + encoder_attentions = { + "description": """ + Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, + sequence_length)`. + + Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the + self-attention heads. + """, + "shape": None, + "additional_info": "returned when `output_attentions=True` is passed or when `config.output_attentions=True`", + } + + router_logits = { + "description": """ + Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, sequence_length, num_experts)`. + + Router logits of the model, useful to compute the auxiliary loss for Mixture of Experts models. + """, + "shape": None, + "additional_info": "returned when `output_router_logits=True` is passed or when `config.add_router_probs=True`", + } + + router_probs = { + "description": """ + Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, sequence_length, num_experts)`. + + Raw router probabilities that are computed by MoE routers, these terms are used to compute the auxiliary + loss and the z_loss for Mixture of Experts models. + """, + "shape": None, + "additional_info": "returned when `output_router_probs=True` and `config.add_router_probs=True` is passed or when `config.output_router_probs=True`", + } + + z_loss = { + "description": """ + z_loss for the sparse modules. + """, + "shape": None, + "additional_info": "returned when `labels` is provided", + } + + aux_loss = { + "description": """ + aux_loss for the sparse modules. + """, + "shape": None, + "additional_info": "returned when `labels` is provided", + } + + start_logits = { + "description": """ + Span-start scores (before SoftMax). + """, + "shape": "of shape `(batch_size, sequence_length)`", + } + + end_logits = { + "description": """ + Span-end scores (before SoftMax). + """, + "shape": "of shape `(batch_size, sequence_length)`", + } + + feature_maps = { + "description": """ + Feature maps of the stages. + """, + "shape": "of shape `(batch_size, num_channels, height, width)`", + } + + reconstruction = { + "description": """ + Reconstructed / completed images. + """, + "shape": "of shape `(batch_size, num_channels, height, width)`", + } + + spectrogram = { + "description": """ + The predicted spectrogram. + """, + "shape": "of shape `(batch_size, sequence_length, num_bins)`", + } + + predicted_depth = { + "description": """ + Predicted depth for each pixel. + """, + "shape": "of shape `(batch_size, height, width)`", + } + + sequences = { + "description": """ + Sampled values from the chosen distribution. + """, + "shape": "of shape `(batch_size, num_samples, prediction_length)` or `(batch_size, num_samples, prediction_length, input_size)`", + } + + params = { + "description": """ + Parameters of the chosen distribution. + """, + "shape": "of shape `(batch_size, num_samples, num_params)`", + } + + loc = { + "description": """ + Shift values of each time series' context window which is used to give the model inputs of the same + magnitude and then used to shift back to the original magnitude. + """, + "shape": "of shape `(batch_size,)` or `(batch_size, input_size)`", + } + + scale = { + "description": """ + Scaling values of each time series' context window which is used to give the model inputs of the same + magnitude and then used to rescale back to the original magnitude. + """, + "shape": "of shape `(batch_size,)` or `(batch_size, input_size)`", + } + + static_features = { + "description": """ + Static features of each time series' in a batch which are copied to the covariates at inference time. + """, + "shape": "of shape `(batch_size, feature size)`", + } + + embeddings = { + "description": """ + Utterance embeddings used for vector similarity-based retrieval. + """, + "shape": "of shape `(batch_size, config.xvector_output_dim)`", + } + + extract_features = { + "description": """ + Sequence of extracted feature vectors of the last convolutional layer of the model. + """, + "shape": "of shape `(batch_size, sequence_length, conv_dim[-1])`", + } + + projection_state = { + "description": """ + Text embeddings before the projection layer, used to mimic the last hidden state of the teacher encoder. + """, + "shape": "of shape `(batch_size,config.project_dim)`", + } + + image_hidden_states = { + "description": """ + Image hidden states of the model produced by the vision encoder and after projecting the last hidden state. + """, + "shape": "of shape `(batch_size, num_images, sequence_length, hidden_size)`", + } + + video_hidden_states = { + "description": """ + Video hidden states of the model produced by the vision encoder and after projecting the last hidden state. + """, + "shape": "of shape `(batch_size * num_frames, num_images, sequence_length, hidden_size)`", + } + + +class ClassDocstring: + Config = r""" + This is the configuration class to store the configuration of a {model_base_class}. It is used to instantiate a {model_name} + model according to the specified arguments, defining the model architecture. Instantiating a configuration with the + defaults will yield a similar configuration to that of the [{model_checkpoint}](https://huggingface.co/{model_checkpoint}) + + Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the + documentation from [`PreTrainedConfig`] for more information. + """ + + PreTrainedModel = r""" + This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the + library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads + etc.) + + This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. + Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage + and behavior. + """ + + Model = r""" + The bare {model_name} Model outputting raw hidden-states without any specific head on top. + """ + + ForPreTraining = r""" + The {model_name} Model with a specified pretraining head on top. + """ + + Decoder = r""" + The bare {model_name} Decoder outputting raw hidden-states without any specific head on top. + """ + + TextModel = r""" + The bare {model_name} Text Model outputting raw hidden-states without any specific head on to. + """ + + ForSequenceClassification = r""" + The {model_name} Model with a sequence classification/regression head on top e.g. for GLUE tasks. + """ + + ForQuestionAnswering = r""" + The {model_name} transformer with a span classification head on top for extractive question-answering tasks like + SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`). + """ + + ForMultipleChoice = r""" + The {model_name} Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a + softmax) e.g. for RocStories/SWAG tasks. + """ + + ForMaskedLM = r""" + The {model_name} Model with a `language modeling` head on top." + """ + + ForTokenClassification = r""" + The {model_name} transformer with a token classification head on top (a linear layer on top of the hidden-states + output) e.g. for Named-Entity-Recognition (NER) tasks. + """ + + ForConditionalGeneration = r""" + The {model_name} Model for token generation conditioned on other modalities (e.g. image-text-to-text generation). + """ + + ForCausalLM = r""" + The {model_name} Model for causal language modeling. + """ + + Backbone = r""" + The {model_name} backbone. + """ + + ForImageClassification = r""" + The {model_name} Model with an image classification head on top e.g. for ImageNet. + """ + ForSemanticSegmentation = r""" + The {model_name} Model with a semantic segmentation head on top e.g. for ADE20K, CityScapes. + """ + ForAudioClassification = r""" + The {model_name} Model with an audio classification head on top (a linear layer on top of the pooled + output). + """ + + ForAudioFrameClassification = r""" + The {model_name} Model with a frame classification head on top for tasks like Speaker Diarization. + """ + + ForPrediction = r""" + The {model_name} Model with a distribution head on top for time-series forecasting. + """ + + WithProjection = r""" + The {model_name} Model with a projection layer on top (a linear layer on top of the pooled output). + """ + + +class ClassAttrs: + # fmt: off + base_model_prefix = r""" + A string indicating the attribute associated to the base model in derived classes of the same architecture adding modules on top of the base model. + """ + supports_gradient_checkpointing = r""" + Whether the model supports gradient checkpointing or not. Gradient checkpointing is a memory-saving technique that trades compute for memory, by storing only a subset of activations (checkpoints) and recomputing the activations that are not stored during the backward pass. + """ + _no_split_modules = r""" + Layers of modules that should not be split across devices should be added to `_no_split_modules`. This can be useful for modules that contains skip connections or other operations that are not compatible with splitting the module across devices. Setting this attribute will enable the use of `device_map="auto"` in the `from_pretrained` method. + """ + _skip_keys_device_placement = r""" + A list of keys to ignore when moving inputs or outputs between devices when using the `accelerate` library. + """ + _supports_flash_attn = r""" + Whether the model's attention implementation supports FlashAttention. + """ + _supports_sdpa = r""" + Whether the model's attention implementation supports SDPA (Scaled Dot Product Attention). + """ + _supports_flex_attn = r""" + Whether the model's attention implementation supports FlexAttention. + """ + _can_compile_fullgraph = r""" + Whether the model can `torch.compile` fullgraph without graph breaks. Models will auto-compile if this flag is set to `True` + in inference, if a compilable cache is used. + """ + _supports_attention_backend = r""" + Whether the model supports attention interface functions. This flag signal that the model can be used as an efficient backend in TGI and vLLM. + """ + _tied_weights_keys = r""" + A list of `state_dict` keys that are potentially tied to another key in the state_dict. + """ + # fmt: on + + +ARGS_TO_IGNORE = {"self", "kwargs", "args", "deprecated_arguments"} +ARGS_TO_RENAME = {"_out_features": "out_features", "_out_indices": "out_indices"} + + +def get_indent_level(func): + # Use this instead of `inspect.getsource(func)` as getsource can be very slow + return (len(func.__qualname__.split(".")) - 1) * 4 + + +def equalize_indent(docstring: str, indent_level: int) -> str: + """ + Adjust the indentation of a docstring to match the specified indent level. + """ + prefix = " " * indent_level + # Uses splitlines() (no keepends) to match previous behaviour that dropped + # any trailing newline via the old splitlines() + "\n".join() + textwrap.indent path. + return "\n".join(prefix + line.lstrip() if line.strip() else "" for line in docstring.splitlines()) + + +def set_min_indent(docstring: str, indent_level: int) -> str: + """ + Adjust the indentation of a docstring to match the specified indent level. + """ + # Equivalent to textwrap.dedent + textwrap.indent but avoids the two regex + # passes that textwrap uses internally (one per call in dedent, one in indent). + lines = docstring.split("\n") + min_indent = min( + (len(line) - len(line.lstrip()) for line in lines if line.strip()), + default=0, + ) + prefix = " " * indent_level + return "\n".join(prefix + line[min_indent:] if line.strip() else "" for line in lines) + + +def parse_shape(docstring): + match = _re_shape.search(docstring) + if match: + return " " + match.group(1) + return None + + +def parse_default(docstring): + match = _re_default.search(docstring) + if match: + return " " + match.group(1) + return None + + +def parse_docstring(docstring, max_indent_level=0, return_intro=False): + """ + Parse the docstring to extract the Args section and return it as a dictionary. + The docstring is expected to be in the format: + Args: + arg1 (type): + Description of arg1. + arg2 (type): + Description of arg2. + + # This function will also return the remaining part of the docstring after the Args section. + Returns:/Example: + ... + """ + match = _re_example_or_return.search(docstring) + if match: + remainder_docstring = docstring[match.start() :] + docstring = docstring[: match.start()] + else: + remainder_docstring = "" + + args_match = _re_args_section.search(docstring) + # still try to find args description in the docstring, if args are not preceded by "Args:" + docstring_intro = None + if args_match: + docstring_intro = docstring[: args_match.start()] + if docstring_intro.split("\n")[-1].strip() == '"""': + docstring_intro = "\n".join(docstring_intro.split("\n")[:-1]) + if docstring_intro.split("\n")[0].strip() == 'r"""' or docstring_intro.split("\n")[0].strip() == '"""': + docstring_intro = "\n".join(docstring_intro.split("\n")[1:]) + if docstring_intro.strip() == "": + docstring_intro = None + args_section = args_match.group(1).lstrip("\n") if args_match else docstring + if args_section.split("\n")[-1].strip() == '"""': + args_section = "\n".join(args_section.split("\n")[:-1]) + if args_section.split("\n")[0].strip() == 'r"""' or args_section.split("\n")[0].strip() == '"""': + args_section = "\n".join(args_section.split("\n")[1:]) + args_section = set_min_indent(args_section, 0) + params = {} + if args_section: + # Use the pre-compiled pattern (max_indent_level is always 0 at all call + # sites; if a non-zero value is ever needed, compile a fresh pattern). + if max_indent_level == 0: + param_pattern = _re_param + else: + param_pattern = re.compile( + # |--- Group 1 ---|| Group 2 ||- Group 3 -||---------- Group 4 ----------| + rf"^\s{{0,{max_indent_level}}}(\w+)\s*\(\s*([^, \)]*)(\s*.*?)\s*\)\s*:\s*((?:(?!\n^\s{{0,{max_indent_level}}}\w+\s*\().)*)", + re.DOTALL | re.MULTILINE, + ) + for match in param_pattern.finditer(args_section): + param_name = match.group(1) + param_type = match.group(2) + additional_info = match.group(3) + optional = "optional" in additional_info + shape = parse_shape(additional_info) + default = parse_default(additional_info) + param_description = match.group(4).strip() + # indent the first line of param_description to 4 spaces: + param_description = " " * 4 + param_description + param_description = f"\n{param_description}" + params[param_name] = { + "type": param_type, + "description": param_description, + "optional": optional, + "shape": shape, + "default": default, + "additional_info": additional_info, + } + + if params and remainder_docstring: + remainder_docstring = "\n" + remainder_docstring + + remainder_docstring = set_min_indent(remainder_docstring, 0) + + if return_intro: + return params, remainder_docstring, docstring_intro + return params, remainder_docstring + + +def contains_type(type_hint, target_type) -> tuple[bool, object | None]: + """ + Check if a "nested" type hint contains a specific target type, + return the first-level type containing the target_type if found. + """ + args = get_args(type_hint) + if args == (): + try: + return issubclass(type_hint, target_type), type_hint + except Exception: + return issubclass(type(type_hint), target_type), type_hint + found_type_tuple = [contains_type(arg, target_type)[0] for arg in args] + found_type = any(found_type_tuple) + if found_type: + type_hint = args[found_type_tuple.index(True)] + return found_type, type_hint + + +def get_model_name(obj): + """ + Get the model name from the file path of the object. + """ + + path = inspect.getsourcefile(obj) + if path is None: + return None + if path.split(os.path.sep)[-3] != "models": + return None + file_name = path.split(os.path.sep)[-1] + model_name_lowercase_from_folder = path.split(os.path.sep)[-2] + model_name_lowercase_from_file = None + for file_type in AUTODOC_FILES: + start = file_type.split("*")[0] + end = file_type.split("*")[-1] if "*" in file_type else "" + if file_name.startswith(start) and file_name.endswith(end): + model_name_lowercase_from_file = file_name[len(start) : -len(end)] + break + if model_name_lowercase_from_file and model_name_lowercase_from_folder != model_name_lowercase_from_file: + from transformers.models.auto.configuration_auto import SPECIAL_MODEL_TYPE_TO_MODULE_NAME + + if ( + model_name_lowercase_from_file in SPECIAL_MODEL_TYPE_TO_MODULE_NAME + or model_name_lowercase_from_file.replace("_", "-") in SPECIAL_MODEL_TYPE_TO_MODULE_NAME + ): + return model_name_lowercase_from_file + return model_name_lowercase_from_folder + return model_name_lowercase_from_folder + + +def generate_processor_intro(cls) -> str: + """ + Generate the intro docstring for a processor class based on its attributes. + + Args: + cls: Processor class to generate intro for + + Returns: + str: Generated intro text + """ + class_name = cls.__name__ + + # Get attributes and their corresponding class names + attributes = cls.get_attributes() + if not attributes: + return "" + + # Build list of component names and their classes + components = [] + component_classes = [] + + for attr in attributes: + # Get the class name for this attribute + class_attr = f"{attr}_class" + # Format attribute name for display + attr_display = attr.replace("_", " ") + components.append(attr_display) + component_classes.append(f"[`{{{class_attr}}}`]") + if not components: + return "" + + # Generate the intro text + if len(components) == 1: + components_text = f"a {components[0]}" + classes_text = component_classes[0] + classes_text_short = component_classes[0].replace("[`", "[`~") + elif len(components) == 2: + components_text = f"a {components[0]} and a {components[1]}" + classes_text = f"{component_classes[0]} and {component_classes[1]}" + classes_text_short = ( + f"{component_classes[0].replace('[`', '[`~')} and {component_classes[1].replace('[`', '[`~')}" + ) + else: + components_text = ", ".join(f"a {c}" for c in components[:-1]) + f", and a {components[-1]}" + classes_text = ", ".join(component_classes[:-1]) + f", and {component_classes[-1]}" + classes_short = [c.replace("[`", "[`~") for c in component_classes] + classes_text_short = ", ".join(classes_short[:-1]) + f", and {classes_short[-1]}" + + intro = f"""Constructs a {class_name} which wraps {components_text} into a single processor. + +[`{class_name}`] offers all the functionalities of {classes_text}. See the +{classes_text_short} for more information. +""" + + return intro + + +def get_placeholders_dict(placeholders: set[str], model_name: str) -> Mapping[str, str | None]: + """ + Get the dictionary of placeholders for the given model name. + """ + # import here to avoid circular import + from transformers.models import auto as auto_module + + placeholders_dict = {} + for placeholder in placeholders: + # Infer placeholders from the model name and the auto modules + if placeholder in PLACEHOLDER_TO_AUTO_MODULE: + try: + place_holder_value = getattr( + getattr(auto_module, PLACEHOLDER_TO_AUTO_MODULE[placeholder][0]), + PLACEHOLDER_TO_AUTO_MODULE[placeholder][1], + ).get(model_name, None) + except ImportError: + # In case a library is not installed, we don't want to fail the docstring generation + place_holder_value = None + if place_holder_value is not None: + if isinstance(place_holder_value, list | tuple): + place_holder_value = ( + place_holder_value[-1] if place_holder_value[-1] is not None else place_holder_value[0] + ) + placeholders_dict[placeholder] = place_holder_value if place_holder_value is not None else placeholder + else: + placeholders_dict[placeholder] = placeholder + + return placeholders_dict + + +def format_args_docstring(docstring: str, model_name: str) -> str: + """ + Replaces placeholders such as {image_processor_class} in the docstring with the actual values, + deducted from the model name and the auto modules. + """ + # first check if there are any placeholders in the docstring, if not return it as is + placeholders = set(_re_placeholders.findall(docstring)) + if not placeholders: + return docstring + + # get the placeholders dictionary for the given model name + placeholders_dict = get_placeholders_dict(placeholders, model_name) + # replace the placeholders in the docstring with the values from the placeholders_dict + for placeholder, value in placeholders_dict.items(): + if isinstance(value, dict) and placeholder == "image_processor_class": + value = value.get("torchvision", value.get("pil", None)) + if placeholder is not None: + docstring = docstring.replace(f"{{{placeholder}}}", value) + return docstring + + +def get_args_doc_from_source(args_classes: object | list[object]) -> dict: + if isinstance(args_classes, list | tuple): + return _merge_args_dicts(tuple(args_classes)) + return args_classes.__dict__ + + +@lru_cache(maxsize=16) +def _merge_args_dicts(args_classes_tuple: tuple) -> dict: + """Cached merger of args-doc dicts. The input classes are static so caching is safe.""" + result = {} + for cls in args_classes_tuple: + result.update(cls.__dict__) + return result + + +def get_checkpoint_from_config_class(config_class): + checkpoint = None + + # source code of `config_class` + # config_source = inspect.getsource(config_class) + config_source = config_class.__doc__ + if not config_source: + return None + + checkpoints = _re_checkpoint.findall(config_source) + # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. + # For example, `('google-bert/bert-base-uncased', 'https://huggingface.co/google-bert/bert-base-uncased')` + for ckpt_name, ckpt_link in checkpoints: + # allow the link to end with `/` + ckpt_link = ckpt_link.removesuffix("/") + + # verify the checkpoint name corresponds to the checkpoint link + ckpt_link_from_name = f"https://huggingface.co/{ckpt_name}" + if ckpt_link == ckpt_link_from_name: + checkpoint = ckpt_name + break + + return checkpoint + + +def add_intro_docstring(func, class_name, indent_level=0): + intro_docstring = "" + if func.__name__ == "forward": + intro_docstring = rf"""The [`{class_name}`] forward method, overrides the `__call__` special method. + + + + Although the recipe for forward pass needs to be defined within this function, one should call the [`Module`] + instance afterwards instead of this since the former takes care of running the pre and post processing steps while + the latter silently ignores them. + + + + """ + intro_docstring = equalize_indent(intro_docstring, indent_level + 4) + + return intro_docstring + + +def _get_model_info(func, parent_class): + """ + Extract model information from a function or its parent class. + + Args: + func (`function`): The function to extract information from + parent_class (`class`): Optional parent class of the function + """ + # import here to avoid circular import + from transformers.models import auto as auto_module + + # Get model name from either parent class or function + if parent_class is not None: + model_name_lowercase = get_model_name(parent_class) + else: + model_name_lowercase = get_model_name(func) + + # Normalize model name if needed + if model_name_lowercase and model_name_lowercase not in getattr( + getattr(auto_module, PLACEHOLDER_TO_AUTO_MODULE["config_class"][0]), + PLACEHOLDER_TO_AUTO_MODULE["config_class"][1], + ): + model_name_lowercase = model_name_lowercase.replace("_", "-") + + # Get class name from function's qualified name + class_name = func.__qualname__.split(".")[0] + + # Get config class for the model + if model_name_lowercase is None: + config_class = None + else: + try: + config_class = getattr( + getattr(auto_module, PLACEHOLDER_TO_AUTO_MODULE["config_class"][0]), + PLACEHOLDER_TO_AUTO_MODULE["config_class"][1], + )[model_name_lowercase] + except KeyError: + if model_name_lowercase in HARDCODED_CONFIG_FOR_MODELS: + config_class = HARDCODED_CONFIG_FOR_MODELS[model_name_lowercase] + else: + config_class = "ModelConfig" + print( + f"[ERROR] Config not found for {model_name_lowercase}. You can manually add it to HARDCODED_CONFIG_FOR_MODELS in utils/auto_docstring.py" + ) + return model_name_lowercase, class_name, config_class + + +def _format_type_annotation_recursive(type_hint): + """ + Recursively format a type annotation object as a string, preserving generic type arguments. + + This is an internal helper used by process_type_annotation for the type object path. + + Args: + type_hint: A type annotation object + + Returns: + str: Formatted type string + """ + # Handle special cases + if type_hint is type(...) or type_hint is Ellipsis: + return "..." + # Note: NoneType handling is done later to preserve "NoneType" in Union[] but "None" in | syntax + + # Check if this is a generic type (e.g., list[str], dict[str, int]) + origin = get_origin(type_hint) + args = get_args(type_hint) + + if origin is not None and args: + # This is a generic type - format it with its arguments + # Get the origin type name + if hasattr(origin, "__module__") and hasattr(origin, "__name__"): + # Clean up module name - need to handle both 'typing.' prefix and just 'typing' + module_name = origin.__module__ + if module_name in ("typing", "types", "builtins"): + module_name = "" + else: + module_name = ( + module_name.replace("transformers.", "~") + .replace("typing.", "") + .replace("types.", "") + .replace("builtins.", "") + ) + + if module_name: + origin_str = f"{module_name}.{origin.__name__}" + else: + origin_str = origin.__name__ + else: + origin_str = str(origin) + + # Handle special origin types + if origin_str == "UnionType": + # Python 3.13's X | Y syntax - format it nicely + arg_strs = [_format_type_annotation_recursive(arg) for arg in args] + return " | ".join(arg_strs) + + # Special handling for Annotated[Union[...], ...] and Annotated[UnionType[...], ...] + # Check if first arg is a Union/UnionType and format it specially + if origin_str == "Annotated" and args: + first_arg_origin = get_origin(args[0]) + # Check if it's a UnionType (modern | syntax) or Union (old Union[] syntax) + if first_arg_origin is UnionType: + # Modern union type - format as X | Y | Z (with None not NoneType) + union_args = get_args(args[0]) + union_strs = [] + for arg in union_args: + if arg is type(None): + union_strs.append("None") # Modern syntax uses "None" + else: + union_strs.append(_format_type_annotation_recursive(arg)) + formatted_union = " | ".join(union_strs) + # Include the rest of the Annotated metadata + remaining_args = [_format_type_annotation_recursive(arg) for arg in args[1:]] + all_args = [formatted_union] + remaining_args + return f"{origin_str}[{', '.join(all_args)}]" + elif first_arg_origin is Union: + # Old-style Union - format as Union[X, Y, Z] + union_args = get_args(args[0]) + union_strs = [_format_type_annotation_recursive(arg) for arg in union_args] + formatted_union = f"Union[{', '.join(union_strs)}]" + # Include the rest of the Annotated metadata + remaining_args = [_format_type_annotation_recursive(arg) for arg in args[1:]] + all_args = [formatted_union] + remaining_args + return f"{origin_str}[{', '.join(all_args)}]" + + # Recursively format the generic arguments + arg_strs = [_format_type_annotation_recursive(arg) for arg in args] + return f"{origin_str}[{', '.join(arg_strs)}]" + elif hasattr(type_hint, "__module__") and hasattr(type_hint, "__name__"): + # Simple type with module and name + # Clean up module name - need to handle both 'typing.' prefix and just 'typing' + module_name = type_hint.__module__ + if module_name in ("typing", "types", "builtins"): + module_name = "" + else: + module_name = ( + module_name.replace("transformers.", "~") + .replace("typing.", "") + .replace("types.", "") + .replace("builtins.", "") + ) + + if module_name: + type_name = f"{module_name}.{type_hint.__name__}" + else: + type_name = type_hint.__name__ + + return type_name + else: + # Fallback to string representation + type_str = str(type_hint) + # Clean up ForwardRef + if "ForwardRef" in type_str: + type_str = _re_forward_ref.sub(r"\1", type_str) + # Clean up module prefixes + type_str = type_str.replace("typing.", "").replace("types.", "") + return type_str + + +def process_type_annotation(type_input, param_name: str | None = None) -> tuple[str, bool]: + """ + Unified function to process and format a parameter's type annotation. + + This function intelligently handles both type objects (from inspect.Parameter.annotation) + and string representations of types. It will: + - Use type introspection when given a type object (preserves generic arguments) + - Parse string representations when that's all that's available + - Always return a formatted type string and optional flag + + Handles various type representations including: + - Type objects with generics (e.g., list[str], Optional[int]) + - Union types (both Union[X, Y] and X | Y syntax) + - Modern union syntax with | (e.g., "bool | None") + - Complex typing constructs (Union, Optional, Annotated, etc.) + - Generic types with brackets + - Class type strings + - Simple types and module paths + + Args: + type_input: Either a type annotation object or a string representation of a type + param_name (`str | None`): The parameter name (used for legacy module path handling) + + Returns: + tuple[str, bool]: (formatted_type_string, is_optional) + """ + optional = False + + # Path 1: Type object (best approach - preserves generic type information) + if not isinstance(type_input, str): + # Handle None type + if type_input is None or type_input is type(None): + return "None", True + + # Handle Union types and modern UnionType (X | Y) + if get_origin(type_input) is Union or get_origin(type_input) is UnionType: + subtypes = get_args(type_input) + out_str = [] + for subtype in subtypes: + if subtype is type(None): + optional = True + continue + formatted_type = _format_type_annotation_recursive(subtype) + out_str.append(formatted_type) + + if not out_str: + return "", optional + elif len(out_str) == 1: + return out_str[0], optional + else: + return f"Union[{', '.join(out_str)}]", optional + + # Single type (not a Union) + formatted_type = _format_type_annotation_recursive(type_input) + return formatted_type, optional + + # Path 2: String representation (fallback when we only have strings) + param_type = type_input + + # Handle Union types with | syntax + if " | " in param_type: + # Modern union syntax (e.g., "bool | None") + parts = [p.strip() for p in param_type.split(" | ")] + if "None" in parts: + optional = True + parts = [p for p in parts if p != "None"] + param_type = " | ".join(parts) if parts else "" + # Clean up module prefixes including typing + param_type = "".join(param_type.split("typing.")).replace("transformers.", "~").replace("builtins.", "") + + elif "typing" in param_type or "Union[" in param_type or "Optional[" in param_type or "[" in param_type: + # Complex typing construct or generic type - clean up typing module references + param_type = "".join(param_type.split("typing.")).replace("transformers.", "~") + + elif "" - should NOT append param_name + param_type = ( + param_type.replace("transformers.", "~").replace("builtins.", "").replace("", "") + ) + + else: + # Simple type or module path - only append param_name if it looks like a module path + # This is legacy behavior for backwards compatibility + if param_name and "." in param_type and not param_type.split(".")[-1][0].isupper(): + # Looks like a module path ending with an attribute + param_type = f"{param_type.replace('transformers.', '~').replace('builtins', '')}.{param_name}" + else: + # Simple type name, don't append param_name + param_type = param_type.replace("transformers.", "~").replace("builtins.", "") + + # Clean up ForwardRef + if "ForwardRef" in param_type: + param_type = _re_forward_ref.sub(r"\1", param_type) + + # Handle Optional wrapper + if "Optional" in param_type: + param_type = _re_optional.sub(r"\1", param_type) + optional = True + + return param_type, optional + + +def _process_parameter_type(param): + """ + Process and format a parameter's type annotation from an inspect.Parameter object. + + Args: + param (`inspect.Parameter`): The parameter from the function signature + + Returns: + tuple[str, bool]: (formatted_type_string, is_optional) + """ + if param.annotation == inspect.Parameter.empty: + return "", False + + # Use the unified function to process the type annotation + formatted_type, optional = process_type_annotation(param.annotation) + + # Check if parameter has a default value (makes it optional) + if param.default is not inspect.Parameter.empty: + optional = True + + return formatted_type, optional + + +def _get_parameter_info(param_name, documented_params, source_args_dict, param_type, optional): + """ + Get parameter documentation details from the appropriate source. + Tensor shape, optional status and description are taken from the custom docstring in priority if available. + Type is taken from the function signature first, then from the custom docstring if missing from the signature + + Args: + param_name (`str`): Name of the parameter + documented_params (`dict`): Dictionary of documented parameters (manually specified in the docstring) + source_args_dict (`dict`): Default source args dictionary to use if not in documented_params + param_type (`str`): Current parameter type (may be updated) + optional (`bool`): Whether the parameter is optional (may be updated) + """ + description = None + shape = None + shape_string = "" + is_documented = True + additional_info = None + optional_string = r", *optional*" if optional else "" + + if param_name in documented_params: + # Parameter is documented in the function's docstring + if ( + param_type == "" + and documented_params[param_name].get("type", None) is not None + or documented_params[param_name]["additional_info"] + ): + param_type = documented_params[param_name]["type"] + optional = documented_params[param_name]["optional"] + shape = documented_params[param_name].get("shape", None) + shape_string = shape if shape else "" + additional_info = documented_params[param_name]["additional_info"] or "" + description = f"{documented_params[param_name]['description']}\n" + elif param_name in source_args_dict: + # Parameter is documented in ModelArgs or ImageProcessorArgs + param_type = source_args_dict[param_name].get("type", param_type) + shape = source_args_dict[param_name].get("shape", None) + shape_string = " " + shape if shape else "" + description = source_args_dict[param_name]["description"] + additional_info = source_args_dict[param_name].get("additional_info", None) + if additional_info: + additional_info = shape_string + optional_string + ", " + additional_info + else: + # Parameter is not documented + is_documented = False + + return param_type, optional_string, shape_string, additional_info, description, is_documented + + +def _process_regular_parameters( + sig, + func, + class_name, + documented_params, + indent_level, + undocumented_parameters, + source_args_dict, + parent_class, + allowed_params=None, +): + """ + Process all regular parameters (not kwargs parameters) from the function signature. + + Args: + sig (`inspect.Signature`): Function signature + func (`function`): Function the parameters belong to + class_name (`str`): Name of the class + documented_params (`dict`): Dictionary of parameters that are already documented + indent_level (`int`): Indentation level + undocumented_parameters (`list`): List to append undocumented parameters to + """ + docstring = "" + # Check if this is a processor by inspecting class hierarchy + is_processor = _is_processor_class(func, parent_class) + + # Use appropriate args source based on whether it's a processor or not + if source_args_dict is None: + if is_processor: + source_args_dict = get_args_doc_from_source([ModelArgs, ImageProcessorArgs, ProcessorArgs]) + else: + source_args_dict = get_args_doc_from_source([ModelArgs, ImageProcessorArgs]) + + missing_args = {} + + for param_name, param in sig.parameters.items(): + # Skip parameters that should be ignored + if ( + param_name in ARGS_TO_IGNORE + or param_name.startswith("_") # Private/internal params (e.g. ClassVar-backed fields in configs) + or param.kind == inspect.Parameter.VAR_POSITIONAL + or param.kind == inspect.Parameter.VAR_KEYWORD + ): + continue + # When a filter is active (e.g. config classes: only own annotations), skip inherited params + if allowed_params is not None and param_name not in allowed_params: + continue + + # When a filter is active (e.g. config classes: only own annotations), skip inherited params + if allowed_params is not None and param_name not in allowed_params: + continue + + param_name = ARGS_TO_RENAME.get(param_name, param_name) + + # Process parameter type and optional status + param_type, optional = _process_parameter_type(param) + + # Check for default value + param_default = "" + if param.default != inspect._empty and param.default is not None: + param_default = f", defaults to `{str(param.default)}`" + + param_type, optional_string, shape_string, additional_info, description, is_documented = _get_parameter_info( + param_name, documented_params, source_args_dict, param_type, optional + ) + + if is_documented: + if param_name == "config": + if param_type == "": + param_type = f"[`{class_name}`]" + else: + param_type = f"[`{param_type.split('.')[-1]}`]" + # elif param_type == "" and False: # TODO: Enforce typing for all parameters + # print(f"[ERROR] {param_name} for {func.__qualname__} in file {func.__code__.co_filename} has no type") + param_type = param_type if "`" in param_type else f"`{param_type}`" + # Format the parameter docstring + if additional_info: + param_docstring = f"{param_name} ({param_type}{additional_info}):{description}" + else: + param_docstring = ( + f"{param_name} ({param_type}{shape_string}{optional_string}{param_default}):{description}" + ) + docstring += set_min_indent( + param_docstring, + indent_level + 8, + ) + else: + missing_args[param_name] = { + "type": param_type if param_type else "", + "optional": optional, + "shape": shape_string, + "description": description if description else "\n ", + "default": param_default, + } + # Try to get the correct source file; for classes decorated with @strict (huggingface_hub), + # func.__code__.co_filename points to the wrapper in huggingface_hub, not the config file. + try: + if parent_class is not None: + _source_file = inspect.getsourcefile(parent_class) or func.__code__.co_filename + else: + _source_file = inspect.getsourcefile(inspect.unwrap(func)) or func.__code__.co_filename + except (TypeError, OSError): + _source_file = func.__code__.co_filename + undocumented_parameters.append( + f"[ERROR] `{param_name}` is part of {func.__qualname__}'s signature, but not documented. Make sure to add it to the docstring of the function in {_source_file}." + ) + + return docstring, missing_args + + +def find_sig_line(lines, line_end): + parenthesis_count = 0 + sig_line_end = line_end + found_sig = False + while not found_sig: + for char in lines[sig_line_end]: + if char == "(": + parenthesis_count += 1 + elif char == ")": + parenthesis_count -= 1 + if parenthesis_count == 0: + found_sig = True + break + sig_line_end += 1 + return sig_line_end + + +def _is_image_processor_class(func, parent_class): + """ + Check if a function belongs to a ProcessorMixin class. + + Uses two methods: + 1. Check parent_class inheritance (if provided) + 2. Check if the source file is named processing_*.py (multimodal processors) + vs image_processing_*.py, video_processing_*.py, etc. (single-modality processors) + + Args: + func: The function to check + parent_class: Optional parent class (if available) + + Returns: + bool: True if this is a multimodal processor (inherits from ProcessorMixin), False otherwise + """ + # First, check if parent_class is provided and use it + if parent_class is not None: + return "BaseImageProcessor" in parent_class.__name__ or any( + "BaseImageProcessor" in base.__name__ for base in parent_class.__mro__ + ) + + # If parent_class is None, check the filename + # Multimodal processors are in files named "processing_*.py" + # Single-modality processors are in "image_processing_*.py", "video_processing_*.py", etc. + try: + source_file = inspect.getsourcefile(func) + except TypeError: + return False + if not source_file: + return False + + # Exception for DummyProcessorForTest + if func.__qualname__.split(".")[0] == "DummyForTestImageProcessorFast": + return True + + filename = os.path.basename(source_file) + + # Multimodal processors are implemented in processing_*.py modules + # (single-modality processors use image_processing_*, video_processing_*, etc.)self. + return filename.startswith("image_processing_") and filename.endswith(".py") + + +def _is_processor_class(func, parent_class): + """ + Check if a function belongs to a ProcessorMixin class. + + Uses two methods: + 1. Check parent_class inheritance (if provided) + 2. Check if the source file is named processing_*.py (multimodal processors) + vs image_processing_*.py, video_processing_*.py, etc. (single-modality processors) + + Args: + func: The function to check + parent_class: Optional parent class (if available) + + Returns: + bool: True if this is a multimodal processor (inherits from ProcessorMixin), False otherwise + """ + # First, check if parent_class is provided and use it + if parent_class is not None: + return "ProcessorMixin" in parent_class.__name__ or any( + "ProcessorMixin" in base.__name__ for base in parent_class.__mro__ + ) + + # If parent_class is None, check the filename + # Multimodal processors are in files named "processing_*.py" + # Single-modality processors are in "image_processing_*.py", "video_processing_*.py", etc. + try: + source_file = inspect.getsourcefile(func) + except TypeError: + return False + if not source_file: + return False + + # Exception for DummyProcessorForTest + if func.__qualname__.split(".")[0] == "DummyProcessorForTest": + return True + + filename = os.path.basename(source_file) + + # Multimodal processors are implemented in processing_*.py modules + # (single-modality processors use image_processing_*, video_processing_*, etc.)self. + return filename.startswith("processing_") and filename.endswith(".py") + + +# Python < 3.12 fallback: naming heuristics when __orig_bases__ is not set (cpython#103699). +# Order matters: check ImageProcessorKwargs before ProcessorKwargs. +_BASIC_KWARGS_NAMES = frozenset({"ImagesKwargs", "ProcessingKwargs", "TextKwargs", "VideosKwargs", "AudioKwargs"}) +_BASIC_KWARGS_CLASSES = None # Lazy-loaded name -> class mapping + + +def _get_base_kwargs_class_from_name(cls_name: str) -> str | None: + """Map kwargs class name to base using naming conventions. Returns base class name or None.""" + if cls_name in _BASIC_KWARGS_NAMES: + return cls_name + if "ImageProcessorKwargs" in cls_name or cls_name.endswith("ImagesKwargs"): + return "ImagesKwargs" + if "ProcessorKwargs" in cls_name: + return "ProcessingKwargs" + if "VideoProcessorKwargs" in cls_name or cls_name.endswith("VideosKwargs"): + return "VideosKwargs" + if "AudioProcessorKwargs" in cls_name or cls_name.endswith("AudioKwargs"): + return "AudioKwargs" + if "TextKwargs" in cls_name: + return "TextKwargs" + return None + + +def _get_base_kwargs_class(cls): + """ + Get the root/base TypedDict class by walking the inheritance chain. + For model-specific kwargs like ComplexProcessingKwargs(ProcessingKwargs), returns ProcessingKwargs. + For model-specific kwargs like DummyImageProcessorKwargs(ImagesKwargs), returns ImagesKwargs. + + Compatibility: On Python < 3.12, non-generic TypedDict subclasses do not have __orig_bases__ set + (cpython#103699). We fall back to naming heuristics (e.g. *ImageProcessorKwargs -> ImagesKwargs). + """ + current = cls + while True: + bases = typing_extensions.get_original_bases(current) + parent = None + for base in bases: + if isinstance(base, type) and base not in (dict, object): + if getattr(base, "__name__", "") == "TypedDict" and getattr(base, "__module__", "") == "typing": + continue + parent = base + break + if parent is None: + # Python < 3.12 fallback: use naming heuristics + base_name = _get_base_kwargs_class_from_name(current.__name__) + if base_name is not None: + global _BASIC_KWARGS_CLASSES + if _BASIC_KWARGS_CLASSES is None: + from transformers.processing_utils import ( + AudioKwargs, + ImagesKwargs, + ProcessingKwargs, + TextKwargs, + VideosKwargs, + ) + + _BASIC_KWARGS_CLASSES = { + "ImagesKwargs": ImagesKwargs, + "ProcessingKwargs": ProcessingKwargs, + "TextKwargs": TextKwargs, + "VideosKwargs": VideosKwargs, + "AudioKwargs": AudioKwargs, + } + parent = _BASIC_KWARGS_CLASSES[base_name] + if parent is None or parent == current: + return current + current = parent + + +def _process_kwargs_parameters(sig, func, parent_class, documented_kwargs, indent_level, undocumented_parameters): + """ + Process **kwargs parameters if needed. + + Args: + sig (`inspect.Signature`): Function signature + func (`function`): Function the parameters belong to + parent_class (`class`): Parent class of the function + documented_kwargs (`dict`): Dictionary of kwargs that are already documented + indent_level (`int`): Indentation level + undocumented_parameters (`list`): List to append undocumented parameters to + + Returns: + tuple[str, str]: (kwargs docstring, kwargs summary line to add after return_tensors) + """ + docstring = "" + kwargs_summary = "" + # Check if we need to add typed kwargs description to the docstring + unroll_kwargs = func.__name__ in UNROLL_KWARGS_METHODS + if not unroll_kwargs and parent_class is not None: + # Check if the function has a parent class with unroll kwargs + unroll_kwargs = any( + any(unroll_kwargs_class in base.__name__ for base in parent_class.__mro__) + for unroll_kwargs_class in UNROLL_KWARGS_CLASSES + ) + if not unroll_kwargs: + return docstring, kwargs_summary + + # Check if this is a processor by inspecting class hierarchy + is_processor = _is_processor_class(func, parent_class) + is_image_processor = _is_image_processor_class(func, parent_class) + + # Use appropriate args source based on whether it's a processor or not + if is_processor: + source_args_dict = get_args_doc_from_source([ImageProcessorArgs, ProcessorArgs]) + elif is_image_processor: + source_args_dict = get_args_doc_from_source(ImageProcessorArgs) + else: + raise ValueError( + f"Unrolling kwargs is not supported for {func.__name__} of {parent_class.__name__ if parent_class else 'None'} class" + ) + + # get all unpackable "kwargs" parameters + kwargs_parameters = [ + kwargs_param + for _, kwargs_param in sig.parameters.items() + if kwargs_param.kind == inspect.Parameter.VAR_KEYWORD + ] + for kwarg_param in kwargs_parameters: + # If kwargs not typed, skip + if kwarg_param.annotation == inspect.Parameter.empty: + continue + + if not hasattr(kwarg_param.annotation, "__args__") or not hasattr( + kwarg_param.annotation.__args__[0], "__name__" + ): + continue + + if kwarg_param.annotation.__args__[0].__name__ not in BASIC_KWARGS_TYPES: + # Extract documentation for kwargs + kwargs_documentation = kwarg_param.annotation.__args__[0].__doc__ + if kwargs_documentation is not None: + documented_kwargs = parse_docstring(kwargs_documentation)[0] + # Process each kwarg parameter + for param_name, param_type_annotation in kwarg_param.annotation.__args__[0].__annotations__.items(): + # Handle nested kwargs structures for processors + + if is_processor and param_name.endswith("_kwargs"): + # Check if this is a basic kwargs type that should be skipped + # Basic kwargs types are generic containers that shouldn't be documented as individual params + + # Get the actual type (unwrap Optional if needed) + actual_type = param_type_annotation + type_name = getattr(param_type_annotation, "__name__", None) + if type_name is None and hasattr(param_type_annotation, "__origin__"): + # Handle Optional[Type] or Union cases + args = getattr(param_type_annotation, "__args__", ()) + for arg in args: + if arg is not type(None): + actual_type = arg + type_name = getattr(arg, "__name__", None) + break + + # Skip only if it's one of the basic kwargs types + if type_name in BASIC_KWARGS_TYPES: + continue + + # Otherwise, unroll the custom typed kwargs + # Get the nested TypedDict's annotations + if hasattr(actual_type, "__annotations__"): + nested_kwargs_doc = getattr(actual_type, "__doc__", None) + documented_nested_kwargs = {} + if nested_kwargs_doc: + documented_nested_kwargs = parse_docstring(nested_kwargs_doc)[0] + + # Only process fields that are documented in the custom kwargs class's own docstring + # This prevents showing too many inherited parameters + if not documented_nested_kwargs: + # No documentation in the custom kwargs class, skip unrolling + continue + + # Process each field in the custom typed kwargs + for nested_param_name, nested_param_type in actual_type.__annotations__.items(): + # Only document parameters that are explicitly documented in the TypedDict's docstring + if nested_param_name not in documented_nested_kwargs: + continue + nested_param_type_str, nested_optional = process_type_annotation( + nested_param_type, nested_param_name + ) + + # Check for default value + nested_param_default = "" + if parent_class is not None: + nested_param_default = str(getattr(parent_class, nested_param_name, "")) + nested_param_default = ( + f", defaults to `{nested_param_default}`" if nested_param_default != "" else "" + ) + + # Only use the TypedDict's own docstring, not source_args_dict + # This prevents pulling in too many inherited parameters + ( + nested_param_type_str, + nested_optional_string, + nested_shape_string, + nested_additional_info, + nested_description, + nested_is_documented, + ) = _get_parameter_info( + nested_param_name, + documented_nested_kwargs, + {}, # Empty dict - only use TypedDict's own docstring + nested_param_type_str, + nested_optional, + ) + + # nested_is_documented should always be True here since we filter for it above + # Check if type is missing + if nested_param_type_str == "": + print( + f"🚨 {nested_param_name} for {type_name} in file {func.__code__.co_filename} has no type" + ) + nested_param_type_str = ( + nested_param_type_str if "`" in nested_param_type_str else f"`{nested_param_type_str}`" + ) + # Format the parameter docstring (KWARGS_INDICATOR distinguishes from regular args) + if nested_additional_info: + docstring += set_min_indent( + f"{nested_param_name} ({nested_param_type_str}{KWARGS_INDICATOR}{nested_additional_info}):{nested_description}", + indent_level + 8, + ) + else: + docstring += set_min_indent( + f"{nested_param_name} ({nested_param_type_str}{KWARGS_INDICATOR}{nested_shape_string}{nested_optional_string}{nested_param_default}):{nested_description}", + indent_level + 8, + ) + + # Skip processing the _kwargs parameter itself since we've processed its contents + continue + else: + # If we can't get annotations, skip this parameter + continue + + if documented_kwargs and param_name not in documented_kwargs: + continue + param_type, optional = process_type_annotation(param_type_annotation, param_name) + + # Check for default value + param_default = "" + if parent_class is not None: + param_default = str(getattr(parent_class, param_name, "")) + param_default = f", defaults to `{param_default}`" if param_default != "" else "" + + param_type, optional_string, shape_string, additional_info, description, is_documented = ( + _get_parameter_info(param_name, documented_kwargs, source_args_dict, param_type, optional) + ) + + if is_documented: + # Check if type is missing + if param_type == "": + print( + f"[ERROR] {param_name} for {kwarg_param.annotation.__args__[0].__qualname__} in file {func.__code__.co_filename} has no type" + ) + param_type = param_type if "`" in param_type else f"`{param_type}`" + # Format the parameter docstring (KWARGS_INDICATOR distinguishes from regular args) + if additional_info: + docstring += set_min_indent( + f"{param_name} ({param_type}{KWARGS_INDICATOR}{additional_info}):{description}", + indent_level + 8, + ) + else: + docstring += set_min_indent( + f"{param_name} ({param_type}{KWARGS_INDICATOR}{shape_string}{optional_string}{param_default}):{description}", + indent_level + 8, + ) + else: + undocumented_parameters.append( + f"[ERROR] `{param_name}` is part of {kwarg_param.annotation.__args__[0].__qualname__}, but not documented. Make sure to add it to the docstring of the function in {func.__code__.co_filename}." + ) + + # Build **kwargs summary line (added after return_tensors in _process_parameters_section) + kwargs_annot_cls = kwarg_param.annotation.__args__[0] + kwargs_type_name = _get_base_kwargs_class(kwargs_annot_cls).__name__ + kwargs_info = source_args_dict.get("__kwargs__", {}) + kwargs_description = kwargs_info.get( + "description", + "Additional keyword arguments. Model-specific parameters are listed above.", + ) + kwargs_summary = set_min_indent( + f"**kwargs ([`{kwargs_type_name}`], *optional*):{kwargs_description}", + indent_level + 8, + ) + + return docstring, kwargs_summary + + +def _add_return_tensors_to_docstring(func, parent_class, docstring, indent_level): + """ + Add return_tensors parameter documentation for processor __call__ methods if not already present. + + Args: + func (`function`): Function being processed + parent_class (`class`): Parent class of the function + docstring (`str`): Current docstring being built + indent_level (`int`): Indentation level + + Returns: + str: Updated docstring with return_tensors if applicable + """ + # Check if this is a processor __call__ method or an image processor preprocess method + is_processor_call = False + is_image_processor_preprocess = False + if func.__name__ == "__call__": + # Check if this is a processor by inspecting class hierarchy + is_processor_call = _is_processor_class(func, parent_class) + + if func.__name__ == "preprocess": + is_image_processor_preprocess = _is_image_processor_class(func, parent_class) + + # If it's a processor __call__ method or an image processor preprocess method and return_tensors is not already documented + if (is_processor_call or is_image_processor_preprocess) and "return_tensors" not in docstring: + # Get the return_tensors documentation from ImageProcessorArgs + source_args_dict = ( + get_args_doc_from_source(ProcessorArgs) + if is_processor_call + else get_args_doc_from_source(ImageProcessorArgs) + ) + return_tensors_info = source_args_dict["return_tensors"] + param_type = return_tensors_info.get("type", "`str` or [`~utils.TensorType`]") + description = return_tensors_info["description"] + + # Format the parameter type + param_type = param_type if "`" in param_type else f"`{param_type}`" + + # Format the parameter docstring + param_docstring = f"return_tensors ({param_type}, *optional*):{description}" + docstring += set_min_indent(param_docstring, indent_level + 8) + + return docstring + + +def _process_parameters_section( + func_documentation, + sig, + func, + class_name, + model_name_lowercase, + parent_class, + indent_level, + source_args_dict, + allowed_params, +): + """ + Process the parameters section of the docstring. + + Args: + func_documentation (`str`): Existing function documentation (manually specified in the docstring) + sig (`inspect.Signature`): Function signature + func (`function`): Function the parameters belong to + class_name (`str`): Name of the class the function belongs to + model_name_lowercase (`str`): Lowercase model name + parent_class (`class`): Parent class of the function (if any) + indent_level (`int`): Indentation level + """ + # Start Args section — constant string, min_indent is always 0, so skip set_min_indent + docstring = " " * (indent_level + 4) + "Args:\n" + undocumented_parameters = [] + documented_params = {} + documented_kwargs = {} + + # Parse existing docstring if available + if func_documentation is not None: + documented_params, func_documentation = parse_docstring(func_documentation) + + # Process regular parameters + param_docstring, missing_args = _process_regular_parameters( + sig, + func, + class_name, + documented_params, + indent_level, + undocumented_parameters, + source_args_dict, + parent_class, + allowed_params, + ) + docstring += param_docstring + + # Process **kwargs parameters if needed + kwargs_docstring, kwargs_summary = _process_kwargs_parameters( + sig, func, parent_class, documented_kwargs, indent_level, undocumented_parameters + ) + docstring += kwargs_docstring + + # Add return_tensors for processor __call__ methods if not already present + docstring = _add_return_tensors_to_docstring(func, parent_class, docstring, indent_level) + + # Add **kwargs summary line after return_tensors + docstring += kwargs_summary + + # Report undocumented parameters + if len(undocumented_parameters) > 0: + print("\n".join(undocumented_parameters)) + + return docstring + + +def _prepare_return_docstring(output_type, config_class, add_intro=True): + """ + Prepare the return docstring from a ModelOutput class. + + This is a robust replacement for the old _prepare_output_docstrings from doc.py, + using the same parsing and formatting methods as the rest of auto_docstring. + + Args: + output_type: The ModelOutput class to generate documentation for + config_class (`str`): Config class for the model + add_intro (`bool`): Whether to add the introduction text + + Returns: + str: Formatted return docstring + """ + output_docstring = output_type.__doc__ + + # If the class has no docstring, try to use the parent class's docstring + if output_docstring is None and hasattr(output_type, "__mro__"): + for base in output_type.__mro__[1:]: # Skip the class itself + if base.__doc__ is not None: + output_docstring = base.__doc__ + break + + if output_docstring is None: + if add_intro: + raise ValueError( + f"No docstring found for `{output_type.__name__}` or its parent classes. " + "Make sure the ModelOutput class or one of its parents has a docstring." + ) + return "" + + # Parse the output class docstring to extract parameters + documented_params, _ = parse_docstring(output_docstring) + + if not documented_params and add_intro: + raise ValueError( + f"No `Args` or `Parameters` section is found in the docstring of `{output_type.__name__}`. " + "Make sure it has a docstring and contains either `Args` or `Parameters`." + ) + + # Build the return section + full_output_type, _ = process_type_annotation(output_type) + if add_intro: + # Import here to avoid circular import + from .doc import PT_RETURN_INTRODUCTION + + intro = PT_RETURN_INTRODUCTION.format(full_output_type=full_output_type, config_class=config_class) + else: + intro = f"Returns:\n `{full_output_type}`" + if documented_params: + intro += ":\n" + else: + intro += "\n" + + # Build the parameters section + params_text = "" + if documented_params: + for param_name, param_info in documented_params.items(): + param_type = param_info.get("type", "") + param_description = param_info.get("description", "").strip() + additional_info = param_info.get("additional_info", "") + + # Handle types with unbalanced backticks due to nested parentheses + # The parse_docstring function splits types like `tuple(torch.FloatTensor)` incorrectly + # so we need to reconstruct the complete type by grabbing the closing part from additional_info + if param_type.startswith("`") and not param_type.endswith("`"): + # Find the closing backtick in additional_info + closing_backtick_idx = additional_info.find("`") + if closing_backtick_idx != -1: + # Grab everything up to and including the closing backtick + param_type += additional_info[: closing_backtick_idx + 1] + # Remove that part from additional_info + additional_info = additional_info[closing_backtick_idx + 1 :] + + # Strip backticks from type to add them back consistently + param_type = param_type.strip("`") + + # Use process_type_annotation to ensure consistent type formatting + # This applies the same formatting rules as the rest of auto_docstring + if param_type: + param_type, _ = process_type_annotation(param_type) + + # Build the parameter line + if additional_info: + # additional_info contains shape and optional status + param_line = f"- **{param_name}** (`{param_type}`{additional_info}) -- {param_description}" + else: + param_line = f"- **{param_name}** (`{param_type}`) -- {param_description}" + + # Handle multi-line descriptions: + # Split the description to handle continuations with proper indentation + lines = param_line.split("\n") + formatted_lines = [] + for i, line in enumerate(lines): + if i == 0: + # First line gets no extra indent (just the bullet point) + formatted_lines.append(line) + else: + # Continuation lines: strip existing indentation and add 2 spaces (relative to the bullet) + formatted_lines.append(" " + line.lstrip()) + + param_text = "\n".join(formatted_lines) + + # Indent everything to 4 spaces and append with newline + param_text_indented = set_min_indent(param_text, 4) + params_text += param_text_indented + "\n" + + result = intro + params_text + + return result + + +def _process_returns_section(func_documentation, sig, config_class, indent_level): + """ + Process the returns section of the docstring. + + Args: + func_documentation (`str`): Existing function documentation (manually specified in the docstring) + sig (`inspect.Signature`): Function signature + config_class (`str`): Config class for the model + indent_level (`int`): Indentation level + """ + return_docstring = "" + + # Extract returns section from existing docstring if available + if func_documentation is not None and (match_start := _re_return.search(func_documentation)) is not None: + match_end = _re_example.search(func_documentation) + if match_end: + return_docstring = func_documentation[match_start.start() : match_end.start()] + func_documentation = func_documentation[match_end.start() :] + else: + return_docstring = func_documentation[match_start.start() :] + func_documentation = "" + return_docstring = set_min_indent(return_docstring, indent_level + 4) + # Otherwise, generate return docstring from return annotation if available + elif sig.return_annotation is not None and sig.return_annotation != inspect._empty: + add_intro, return_annotation = contains_type(sig.return_annotation, ModelOutput) + return_docstring = _prepare_return_docstring(return_annotation, config_class, add_intro=add_intro) + # PT_RETURN_INTRODUCTION already starts with \n, so only add blank line if it doesn't start with one + if not return_docstring.startswith("\n"): + return_docstring = "\n" + return_docstring + return_docstring = set_min_indent(return_docstring, indent_level + 4) + + return return_docstring, func_documentation + + +def _process_example_section( + func_documentation, func, parent_class, class_name, model_name_lowercase, config_class, checkpoint, indent_level +): + """ + Process the example section of the docstring. + + Args: + func_documentation (`str`): Existing function documentation (manually specified in the docstring) + func (`function`): Function being processed + parent_class (`class`): Parent class of the function + class_name (`str`): Name of the class + model_name_lowercase (`str`): Lowercase model name + config_class (`str`): Config class for the model + checkpoint: Checkpoint to use in examples + indent_level (`int`): Indentation level + """ + # Import here to avoid circular import + from transformers.models import auto as auto_module + + example_docstring = "" + + # Use existing example section if available (with or without an "Example:" header) + if func_documentation is not None and (match := _re_example.search(func_documentation)): + example_docstring = func_documentation[match.start() :] + example_docstring = "\n" + set_min_indent(example_docstring, indent_level + 4) + # Skip examples for processors + elif _is_processor_class(func, parent_class): + # Processors don't get auto-generated examples + return example_docstring + # No examples for __init__ methods or if the class is not a model + elif parent_class is None and model_name_lowercase is not None: + global _re_model_task + if _re_model_task is None: + _re_model_task = re.compile(rf"({'|'.join(PT_SAMPLE_DOCSTRINGS.keys())})") + model_task = _re_model_task.search(class_name) + CONFIG_MAPPING = auto_module.configuration_auto.CONFIG_MAPPING + + # Get checkpoint example + if (checkpoint_example := checkpoint) is None: + try: + checkpoint_example = get_checkpoint_from_config_class(CONFIG_MAPPING[model_name_lowercase]) + except KeyError: + # For models with inconsistent lowercase model name + if model_name_lowercase in HARDCODED_CONFIG_FOR_MODELS: + CONFIG_MAPPING_NAMES = auto_module.configuration_auto.CONFIG_MAPPING_NAMES + config_class_name = HARDCODED_CONFIG_FOR_MODELS[model_name_lowercase] + if config_class_name in CONFIG_MAPPING_NAMES.values(): + model_name_for_auto_config = [ + k for k, v in CONFIG_MAPPING_NAMES.items() if v == config_class_name + ][0] + if model_name_for_auto_config in CONFIG_MAPPING: + checkpoint_example = get_checkpoint_from_config_class( + CONFIG_MAPPING[model_name_for_auto_config] + ) + + # Add example based on model task + if model_task is not None: + if checkpoint_example is not None: + example_annotation = "" + task = model_task.group() + example_annotation = PT_SAMPLE_DOCSTRINGS[task].format( + model_class=class_name, + checkpoint=checkpoint_example, + expected_output="...", + expected_loss="...", + qa_target_start_index=14, + qa_target_end_index=15, + mask="", + ) + example_docstring = set_min_indent(example_annotation, indent_level + 4) + else: + print( + f"[ERROR] No checkpoint found for {class_name}.{func.__name__}. Please add a `checkpoint` arg to `auto_docstring` or add one in {config_class}'s docstring" + ) + else: + # Check if the model is in a pipeline to get an example + for name_model_list_for_task in MODELS_TO_PIPELINE: + try: + model_list_for_task = getattr(auto_module.modeling_auto, name_model_list_for_task) + except (ImportError, AttributeError): + continue + if class_name in model_list_for_task.values(): + pipeline_name = MODELS_TO_PIPELINE[name_model_list_for_task] + example_annotation = PIPELINE_TASKS_TO_SAMPLE_DOCSTRINGS[pipeline_name].format( + model_class=class_name, + checkpoint=checkpoint_example, + expected_output="...", + expected_loss="...", + qa_target_start_index=14, + qa_target_end_index=15, + ) + example_docstring = set_min_indent(example_annotation, indent_level + 4) + break + + return example_docstring + + +def auto_method_docstring( + func, + parent_class=None, + custom_intro=None, + custom_args=None, + checkpoint=None, + source_args_dict=None, + allowed_params=None, +): + """ + Wrapper that automatically generates docstring. + """ + + # Use inspect to retrieve the method's signature + sig = inspect.signature(func) + indent_level = get_indent_level(func) if not parent_class else get_indent_level(parent_class) + + # Get model information + model_name_lowercase, class_name, config_class = _get_model_info(func, parent_class) + func_documentation = func.__doc__ + + if custom_args is not None and func_documentation is not None: + func_documentation = "\n" + set_min_indent(custom_args.strip("\n"), 0) + "\n" + func_documentation + elif custom_args is not None: + func_documentation = "\n" + set_min_indent(custom_args.strip("\n"), 0) + + # Add intro to the docstring before args description if needed + if custom_intro is not None: + docstring = set_min_indent(custom_intro, indent_level + 4) + if not docstring.strip().endswith("\n"): + docstring += "\n" + else: + docstring = add_intro_docstring(func, class_name=class_name, indent_level=indent_level) + + # Process Parameters section + docstring += _process_parameters_section( + func_documentation, + sig, + func, + class_name, + model_name_lowercase, + parent_class, + indent_level, + source_args_dict, + allowed_params, + ) + + # Process Returns section + return_docstring, func_documentation = _process_returns_section( + func_documentation, sig, config_class, indent_level + ) + docstring += return_docstring + + # Process Example section + example_docstring = _process_example_section( + func_documentation, + func, + parent_class, + class_name, + model_name_lowercase, + config_class, + checkpoint, + indent_level, + ) + docstring += example_docstring + + # Format the docstring with the placeholders + docstring = format_args_docstring(docstring, model_name_lowercase) + + # Assign the dynamically generated docstring to the wrapper function + func.__doc__ = docstring + return func + + +def auto_class_docstring(cls, custom_intro=None, custom_args=None, checkpoint=None): + """ + Wrapper that automatically generates a docstring for classes based on their attributes and methods. + """ + # import here to avoid circular import + from transformers.models import auto as auto_module + + is_dataclass = False + is_processor = False + is_config = False + is_image_processor = False + docstring_init = "" + docstring_args = "" + if "PreTrainedModel" in (x.__name__ for x in cls.__mro__): + docstring_init = auto_method_docstring( + cls.__init__, parent_class=cls, custom_args=custom_args, checkpoint=checkpoint + ).__doc__.replace("Args:", "Parameters:") + elif "ProcessorMixin" in (x.__name__ for x in cls.__mro__): + is_processor = True + docstring_init = auto_method_docstring( + cls.__init__, + parent_class=cls, + custom_args=custom_args, + checkpoint=checkpoint, + source_args_dict=get_args_doc_from_source([ModelArgs, ImageProcessorArgs, ProcessorArgs]), + ).__doc__.replace("Args:", "Parameters:") + elif "ModelOutput" in (x.__name__ for x in cls.__mro__): + # We have a data class + is_dataclass = True + doc_class = cls.__doc__ + if custom_args is None and doc_class: + custom_args = doc_class + docstring_args = auto_method_docstring( + cls.__init__, + parent_class=cls, + custom_args=custom_args, + checkpoint=checkpoint, + source_args_dict=get_args_doc_from_source(ModelOutputArgs), + ).__doc__ + elif any("BaseImageProcessor" in x.__name__ for x in cls.__mro__): + is_image_processor = True + docstring_init = auto_method_docstring( + cls.__init__, + parent_class=cls, + custom_args=custom_args, + checkpoint=checkpoint, + source_args_dict=get_args_doc_from_source(ImageProcessorArgs), + ).__doc__ + elif "PreTrainedConfig" in (x.__name__ for x in cls.__mro__): + is_config = True + doc_class = cls.__doc__ + if custom_args is None and doc_class: + custom_args = doc_class + + # Collect all non-ClassVar annotations from the class and its ancestors up to + # (but not including) PreTrainedConfig. This allows inherited params from intermediate + # config base classes to be documented, while naturally excluding PreTrainedConfig-specific + # quasi-ClassVar params (e.g. `transformers_version`, `architectures`). + own_config_params = set() + for ancestor in cls.__mro__: + if ancestor.__name__ == "PreTrainedConfig": + break + own_config_params |= { + k for k, v in getattr(ancestor, "__annotations__", {}).items() if get_origin(v) is not ClassVar + } + allowed_params = own_config_params if own_config_params else None + docstring_init = auto_method_docstring( + cls.__init__, + parent_class=cls, + custom_args=custom_args, + checkpoint=checkpoint, + source_args_dict=get_args_doc_from_source([ConfigArgs]), + allowed_params=allowed_params, + ).__doc__ + + indent_level = get_indent_level(cls) + model_name_lowercase = get_model_name(cls) + model_name_title = " ".join([k.title() for k in model_name_lowercase.split("_")]) if model_name_lowercase else None + model_base_class = f"{model_name_title.title()}Model" if model_name_title is not None else None + if model_name_lowercase is not None: + try: + model_base_class = getattr( + getattr(auto_module, PLACEHOLDER_TO_AUTO_MODULE["model_class"][0]), + PLACEHOLDER_TO_AUTO_MODULE["model_class"][1], + )[model_name_lowercase] + except KeyError: + pass + except ImportError: + # In some environments, certain model classes might not be available. In that case, we can skip this part. + pass + + if model_name_lowercase and model_name_lowercase not in getattr( + getattr(auto_module, PLACEHOLDER_TO_AUTO_MODULE["config_class"][0]), + PLACEHOLDER_TO_AUTO_MODULE["config_class"][1], + ): + model_name_lowercase = model_name_lowercase.replace("_", "-") + + name = re.findall(rf"({'|'.join(ClassDocstring.__dict__.keys())})$", cls.__name__) + + if name == [] and custom_intro is None and not is_dataclass and not is_processor and not is_image_processor: + raise ValueError( + f"`{cls.__name__}` is not registered in the auto doc. Here are the available classes: {ClassDocstring.__dict__.keys()}.\n" + "Add a `custom_intro` to the decorator if you want to use `auto_docstring` on a class not registered in the auto doc." + ) + if name != [] or custom_intro is not None or is_config or is_dataclass or is_processor or is_image_processor: + name = name[0] if name else None + formatting_kwargs = {"model_name": model_name_title} + if name == "Config": + formatting_kwargs.update({"model_base_class": model_base_class, "model_checkpoint": checkpoint}) + if custom_intro is not None: + pre_block = equalize_indent(custom_intro, indent_level) + if not pre_block.endswith("\n"): + pre_block += "\n" + elif is_processor: + # Generate processor intro dynamically + pre_block = generate_processor_intro(cls) + if pre_block: + pre_block = equalize_indent(pre_block, indent_level) + pre_block = format_args_docstring(pre_block, model_name_lowercase) + elif is_image_processor: + pre_block = r"Constructs a {image_processor_class} image processor." + if pre_block: + pre_block = equalize_indent(pre_block, indent_level) + pre_block = format_args_docstring(pre_block, model_name_lowercase) + elif model_name_title is None or name is None: + pre_block = "" + else: + pre_block = getattr(ClassDocstring, name).format(**formatting_kwargs) + # Start building the docstring + docstring = set_min_indent(f"{pre_block}", indent_level) if len(pre_block) else "" + if name != "PreTrainedModel" and "PreTrainedModel" in (x.__name__ for x in cls.__mro__): + docstring += set_min_indent(f"{ClassDocstring.PreTrainedModel}", indent_level) + # Add the __init__ docstring + if docstring_init: + docstring += set_min_indent(f"\n{docstring_init}", indent_level) + elif is_dataclass or is_config: + # No init function, we have a data class + docstring += docstring_args if docstring_args else "\nArgs:\n" + source_args_dict = get_args_doc_from_source(ModelOutputArgs) + doc_class = cls.__doc__ if cls.__doc__ else "" + documented_kwargs = parse_docstring(doc_class)[0] + for param_name, param_type_annotation in cls.__annotations__.items(): + param_type, optional = process_type_annotation(param_type_annotation, param_name) + + # Check for default value + param_default = "" + param_default = str(getattr(cls, param_name, "")) + param_default = f", defaults to `{param_default}`" if param_default != "" else "" + + param_type, optional_string, shape_string, additional_info, description, is_documented = ( + _get_parameter_info(param_name, documented_kwargs, source_args_dict, param_type, optional) + ) + + if is_documented: + # Check if type is missing + if param_type == "": + print( + f"[ERROR] {param_name} for {cls.__qualname__} in file {cls.__code__.co_filename} has no type" + ) + param_type = param_type if "`" in param_type else f"`{param_type}`" + # Format the parameter docstring + if additional_info: + docstring += set_min_indent( + f"{param_name} ({param_type}{additional_info}):{description}", + indent_level + 8, + ) + else: + docstring += set_min_indent( + f"{param_name} ({param_type}{shape_string}{optional_string}{param_default}):{description}", + indent_level + 8, + ) + # TODO (Yoni): Add support for Attributes section in docs + + else: + print( + f"You used `@auto_class_docstring` decorator on `{cls.__name__}` but this class is not part of the AutoMappings. Remove the decorator" + ) + # Assign the dynamically generated docstring to the wrapper class + cls.__doc__ = docstring + + return cls + + +def auto_docstring(obj=None, *, custom_intro=None, custom_args=None, checkpoint=None): + r""" + Automatically generates comprehensive docstrings for model classes and methods in the Transformers library. + + This decorator reduces boilerplate by automatically including standard argument descriptions while allowing + overrides to add new or custom arguments. It inspects function signatures, retrieves predefined docstrings + for common arguments (like `input_ids`, `attention_mask`, etc.), and generates complete documentation + including examples and return value descriptions. + + For complete documentation and examples, read this [guide](https://huggingface.co/docs/transformers/auto_docstring). + + Examples of usage: + + Basic usage (no parameters): + ```python + @auto_docstring + class MyAwesomeModel(PreTrainedModel): + def __init__(self, config, custom_parameter: int = 10): + r''' + custom_parameter (`int`, *optional*, defaults to 10): + Description of the custom parameter for MyAwesomeModel. + ''' + super().__init__(config) + self.custom_parameter = custom_parameter + ``` + + Using `custom_intro` with a class: + ```python + @auto_docstring( + custom_intro="This model implements a novel attention mechanism for improved performance." + ) + class MySpecialModel(PreTrainedModel): + def __init__(self, config, attention_type: str = "standard"): + r''' + attention_type (`str`, *optional*, defaults to "standard"): + Type of attention mechanism to use. + ''' + super().__init__(config) + ``` + + Using `custom_intro` with a method, and specify custom arguments and example directly in the docstring: + ```python + @auto_docstring( + custom_intro="Performs forward pass with enhanced attention computation." + ) + def forward( + self, + input_ids: Optional[torch.Tensor] = None, + attention_mask: Optional[torch.Tensor] = None, + ): + r''' + custom_parameter (`int`, *optional*, defaults to 10): + Description of the custom parameter for MyAwesomeModel. + + Example: + + ```python + >>> model = MyAwesomeModel(config) + >>> model.forward(input_ids=torch.tensor([1, 2, 3]), attention_mask=torch.tensor([1, 1, 1])) + ``` + ''' + ``` + + Using `custom_args` to define reusable arguments: + ```python + VISION_ARGS = r''' + pixel_values (`torch.FloatTensor`, *optional*): + Pixel values of the input images. + image_features (`torch.FloatTensor`, *optional*): + Pre-computed image features for efficient processing. + ''' + + @auto_docstring(custom_args=VISION_ARGS) + def encode_images(self, pixel_values=None, image_features=None): + # ... method implementation + ``` + + Combining `custom_intro` and `custom_args`: + ```python + MULTIMODAL_ARGS = r''' + vision_features (`torch.FloatTensor`, *optional*): + Pre-extracted vision features from the vision encoder. + fusion_strategy (`str`, *optional*, defaults to "concat"): + Strategy for fusing text and vision modalities. + ''' + + @auto_docstring( + custom_intro="Processes multimodal inputs combining text and vision.", + custom_args=MULTIMODAL_ARGS + ) + def forward( + self, + input_ids, + attention_mask=None, + vision_features=None, + fusion_strategy="concat" + ): + # ... multimodal processing + ``` + + Using with ModelOutput classes: + ```python + @dataclass + @auto_docstring( + custom_intro="Custom model outputs with additional fields." + ) + class MyModelOutput(ImageClassifierOutput): + r''' + loss (`torch.FloatTensor`, *optional*): + The loss of the model. + custom_field (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*): + A custom output field specific to this model. + ''' + + # Standard fields like hidden_states, logits, attentions etc. can be automatically documented + # However, given that the loss docstring is often different per model, you should document it above + loss: Optional[torch.FloatTensor] = None + logits: Optional[torch.FloatTensor] = None + hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None + attentions: Optional[tuple[torch.FloatTensor, ...]] = None + custom_field: Optional[torch.FloatTensor] = None + ``` + + Args: + custom_intro (`str`, *optional*): + Custom introduction text to add to the docstring. This replaces the default + introduction text generated by the decorator before the Args section. Use this to describe what + makes your model or method special. + custom_args (`str`, *optional*): + Custom argument documentation in docstring format. This allows you to define + argument descriptions once and reuse them across multiple methods. The format should follow the + standard docstring convention: `arg_name (`type`, *optional*, defaults to `value`): Description.` + checkpoint (`str`, *optional*): + Checkpoint name to use in examples within the docstring. This is typically + automatically inferred from the model configuration class, but can be overridden if needed for + custom examples. + + Note: + - Standard arguments (`input_ids`, `attention_mask`, `pixel_values`, etc.) are automatically documented + from predefined descriptions and should not be redefined unless their behavior differs in your model. + - New or custom arguments should be documented in the method's docstring using the `r''' '''` block + or passed via the `custom_args` parameter. + - For model classes, the decorator derives parameter descriptions from the `__init__` method's signature + and docstring. + - Return value documentation is automatically generated for methods that return ModelOutput subclasses. + """ + + def auto_docstring_decorator(obj): + if len(obj.__qualname__.split(".")) > 1: + return auto_method_docstring( + obj, custom_args=custom_args, custom_intro=custom_intro, checkpoint=checkpoint + ) + else: + return auto_class_docstring(obj, custom_args=custom_args, custom_intro=custom_intro, checkpoint=checkpoint) + + if obj: + return auto_docstring_decorator(obj) + + return auto_docstring_decorator diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/backbone_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/backbone_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2947b9a5a953228549e52e7b53af0588d3d4fb7b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/backbone_utils.py @@ -0,0 +1,19 @@ +import warnings + +from ..backbone_utils import BackboneConfigMixin, BackboneMixin + + +class BackboneConfigMixin(BackboneConfigMixin): + warnings.warn( + "Importing `BackboneConfigMixin` from `utils/backbone_utils.py` is deprecated and will be removed in " + "Transformers v5.10. Import as `from transformers.backbone_utils import BackboneConfigMixin` instead.", + FutureWarning, + ) + + +class BackboneMixin(BackboneMixin): + warnings.warn( + "Importing `BackboneMixin` from `utils/backbone_utils.py` is deprecated and will be removed in " + "Transformers v5.10. Import as `from transformers.backbone_utils import BackboneMixin` instead.", + FutureWarning, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/chat_parsing_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/chat_parsing_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44983cb33a25e613c1c40476b8b7f5251d0c947f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/chat_parsing_utils.py @@ -0,0 +1,305 @@ +# Copyright 2026 The HuggingFace Team. All rights reserved. +# +# 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. + +from __future__ import annotations + +import json +import re + +from transformers.utils import is_jmespath_available + + +if is_jmespath_available(): + import jmespath +else: + jmespath = None + + +def _gemma4_json_to_json(text: str) -> str: + """Convert Gemma4 tool call format (unquoted keys, ``<|"|>`` string delimiters) to valid JSON.""" + strings = [] + + def _capture(m): + strings.append(m.group(1)) + return f"\x00{len(strings) - 1}\x00" + + # Grab the inside of gemma-quotes and store them for later + text = re.sub(r'<\|"\|>(.*?)<\|"\|>', _capture, text, flags=re.DOTALL) + # Add quotes to the bare keys elsewhere + text = re.sub(r"(?<=[{,])(\w+):", r'"\1":', text) + + # Put the inside of the quotes back afterwards + for i, s in enumerate(strings): + text = text.replace(f"\x00{i}\x00", json.dumps(s)) + + return text + + +def _parse_re_match(node_match: re.Match) -> dict | str: + # If the regex has named groups, return a dict of those groups + if node_match.groupdict(): + return {key: val for key, val in node_match.groupdict().items() if val is not None} + # Otherwise the regex must have exactly one unnamed group, and we return that + else: + groups = list(node_match.groups()) + if len(groups) > 1: + raise ValueError(f"Regex has multiple unnamed groups!\nGroups: {groups}\n") + elif len(groups) == 0: + raise ValueError(f"Regex has no capture groups:\n\n{node_match.group(0)}") + return groups[0] + + +def recursive_parse( + node_content: str | list | dict, + node_schema: dict, +): + """ + This function takes content and a JSON schema which includes + regex extractors, and recursively parses the content. The output + should be a data structure matching the schema. + + Args: + node_content: The content corresponding to this node. Usually a string, but can be something else + if the parent node has multiple capture groups or named groups. In that case, + we generally pass the capture groups straight through to the children of this node + and don't do any parsing at this level. + node_schema: The schema node controlling the parsing. + + Returns: + The parsed data structure for the current node. + """ + + # If the schema has a const, we just return that value and do absolutely nothing else + if "const" in node_schema: + return node_schema["const"] + + # If the node content is None, we return None. EZ. + if node_content is None: + return None + + # If not, we have to do a little parsing. First, set some vars and do basic validation + node_type = node_schema.get("type") + has_regex = ( + "x-regex" in node_schema + or "x-regex-iterator" in node_schema + or "x-regex-key-value" in node_schema + or "x-regex-substitutions" in node_schema + ) + if has_regex and not isinstance(node_content, str): + raise TypeError( + "Schema node got a non-string input, but has a regex for parsing or substitution.\n" + f"Input: {node_content}\n" + f"Schema: {node_schema}" + ) + + node_subs = node_schema.get("x-regex-substitutions", []) + for node_sub in node_subs: + node_content = re.sub(node_sub[0], node_sub[1], node_content, flags=re.DOTALL) + node_regex = node_schema.get("x-regex") + node_regex_iterator = node_schema.get("x-regex-iterator") + node_regex_to_dict = node_schema.get("x-regex-key-value") + if node_regex is not None: + node_match = re.search(node_regex, node_content, flags=re.DOTALL) + if not node_match: + return None + node_content = _parse_re_match(node_match) + if node_regex_iterator is not None: + if node_type != "array": + raise TypeError(f"Schema node with type {node_type} cannot use x-regex-iterator.\nSchema: {node_schema}") + # Note that this can be applied after a standard node-regex search + node_content = [ + _parse_re_match(node_match) + for node_match in re.finditer(node_regex_iterator, node_content, flags=re.DOTALL) + ] + if not node_content: + return None + if node_regex_to_dict is not None: + if node_type != "object": + raise TypeError(f"Schema node with type {node_type} cannot use x-regex-key-value.\nSchema: {node_schema}") + # Note that this can be applied after a standard node-regex search + output_content = {} + for node_match in re.finditer(node_regex_to_dict, node_content, flags=re.DOTALL): + match_groups = _parse_re_match(node_match) + if not isinstance(match_groups, dict) or "key" not in match_groups or "value" not in match_groups: + raise ValueError( + f"Regex for x-regex-key-value must have named groups 'key' and 'value'.\n" + f"Match groups: {match_groups}\n" + f"Schema: {node_schema}" + ) + output_content[match_groups["key"]] = match_groups["value"] + node_content = output_content + if not node_content: + return None + + # Next, if the node has a parser, apply it. We do this after regexes so that the regex can extract + # a substring to parse, if needed. + if "x-parser" in node_schema: + parser = node_schema["x-parser"] + if parser == "gemma4-tool-call": + if not isinstance(node_content, str): + raise TypeError( + f"Node has Gemma4 tool call parser but got non-string input: {node_content}\nSchema: {node_schema}" + ) + node_content = _gemma4_json_to_json(node_content) + parser = "json" # fall through to the JSON parser below - don't add an elif! + if parser == "json": + if not isinstance(node_content, str): + raise TypeError( + f"Node has JSON parser but got non-string input: {node_content}\nSchema: {node_schema}" + ) + parser_args = node_schema.get("x-parser-args", {}) + transform = parser_args.get("transform") + allow_non_json = parser_args.get("allow_non_json", False) + try: + parsed_json = json.loads(node_content) + except json.JSONDecodeError as e: + if allow_non_json: + parsed_json = node_content + else: + raise ValueError( + f"Node has JSON parser but could not parse its contents as JSON. You can use the `allow_non_json` parser arg for nodes which may contain JSON or string content.\n\nContent: {node_content}\n\nError: {e}" + ) + if transform is not None: + if jmespath is None: + raise ImportError( + "Chat response schema includes a jmespath transformation, but jmespath is not installed. You can install it with `pip install jmespath`." + ) + parsed_json = jmespath.search(parser_args["transform"], parsed_json) + node_content = parsed_json + else: + raise ValueError(f"Unknown parser {parser} for schema node: {node_schema}") + + # Finally, handle parsed content based on schema type and recurse if required + if node_type == "object": + parsed_schema = {} + if isinstance(node_content, str): + # This means we don't have a regex at this level, so all of our child nodes need to parse the whole + # string themselves to extract their value. + if "properties" not in node_schema: + raise ValueError( + f"Object node received string content but has no regex or parser to handle it.\n" + f"Content: {node_content}\n" + f"Schema: {node_schema}" + ) + for key, child_node in node_schema["properties"].items(): + child_node_content = recursive_parse(node_content, node_schema["properties"][key]) + if child_node_content is not None: + parsed_schema[key] = child_node_content + elif isinstance(node_content, dict): + for key, child_node in node_schema.get("properties", {}).items(): + if "const" in child_node: + parsed_schema[key] = child_node["const"] + elif key in node_content: + parsed_schema[key] = recursive_parse(node_content[key], child_node) + elif "default" in child_node: + parsed_schema[key] = child_node["default"] + additional_schema = node_schema.get("additionalProperties", True) + # We want to check only for False values; {} is "falsy" but should pass through + if additional_schema is not False: + additional_schema = additional_schema if isinstance(additional_schema, dict) else {} + for key, value in node_content.items(): + if key not in node_schema.get("properties", {}): + parsed_schema[key] = recursive_parse(value, additional_schema) + else: + raise TypeError(f"Expected a dict or str for schema node with type object, got {node_content}") + required = node_schema.get("required", []) + missing = [key for key in required if key not in parsed_schema] + if missing: + input_preview = repr(node_content[:500]) if isinstance(node_content, str) else repr(node_content) + raise ValueError( + f"Required fields {missing} are missing from parsed output.\n" + f"Parsed: {parsed_schema}\n" + f"Input: {input_preview}" + ) + return parsed_schema + elif node_type == "array": + if not node_content: + return [] + parsed_schema = [] + if "items" in node_schema: + if not isinstance(node_content, list): + raise TypeError(f"Expected a list or regex for schema node with type array, got {node_content}") + for item in node_content: + parsed_schema.append(recursive_parse(item, node_schema["items"])) + return parsed_schema + elif "prefixItems" in node_schema: + if not isinstance(node_content, list): + if len(node_schema["prefixItems"]) == 1: + # If there's only one prefix item, this is a single item array, we can just wrap the string + node_content = [node_content] + else: + raise TypeError(f"Expected a list or regex for schema node with type array, got {node_content}") + if len(node_content) != len(node_schema["prefixItems"]): + raise ValueError( + f"Array node has {len(node_content)} items, but schema only has " + f"{len(node_schema['prefixItems'])} prefixItems defined.\n" + f"Content: {node_content}\n" + f"Schema: {node_schema}" + ) + for item, item_schema in zip(node_content, node_schema["prefixItems"]): + parsed_schema.append(recursive_parse(item, item_schema)) + return parsed_schema + else: + raise ValueError(f"Array node has no items or prefixItems schema defined.\nSchema: {node_schema}") + elif node_type in ("string", "integer", "number", "boolean"): + if node_type == "integer": + if isinstance(node_content, int): + return node_content + if not isinstance(node_content, str): + raise TypeError( + f"Expected a string or int for schema node with type integer, got {type(node_content).__name__}: {node_content}" + ) + try: + return int(node_content) + except ValueError: + raise ValueError( + f"Schema node has type 'integer', but the parsed string content is not a valid integer: {node_content!r}" + ) + elif node_type == "number": + if isinstance(node_content, (int, float)): + return float(node_content) + if not isinstance(node_content, str): + raise TypeError( + f"Expected a string or number for schema node with type number, got {type(node_content).__name__}: {node_content}" + ) + try: + return float(node_content) + except ValueError: + raise ValueError( + f"Schema node has type 'number', but the parsed string content is not a valid number: {node_content!r}" + ) + elif node_type == "boolean": + if isinstance(node_content, bool): + return node_content + if not isinstance(node_content, str): + raise TypeError( + f"Expected a string or bool for schema node with type boolean, got {type(node_content).__name__}: {node_content}" + ) + if node_content.lower() in ("true", "1"): + return True + elif node_content.lower() in ("false", "0"): + return False + else: + raise ValueError(f"Invalid boolean value: {node_content}") + else: + # String type + if not isinstance(node_content, str): + raise TypeError( + f"Expected a string for schema node with type string, got {type(node_content).__name__}: {node_content}" + ) + return node_content + elif node_type is None or node_type == "any": + return node_content # Don't touch it + else: + raise TypeError(f"Unsupported schema type {node_type} for node: {node_content}") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/chat_template_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/chat_template_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6b23e2fa881d302e60f12528788d50d8ad2d50a1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/chat_template_utils.py @@ -0,0 +1,622 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# 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. + +import inspect +import json +import re +import types +from collections.abc import Callable +from contextlib import contextmanager +from copy import deepcopy +from datetime import datetime +from functools import lru_cache +from inspect import isfunction +from typing import Any, Literal, Union, get_args, get_origin, get_type_hints, no_type_check + +from packaging import version + +from . import logging +from .import_utils import is_jinja_available, is_torch_available, is_vision_available + + +logger = logging.get_logger(__name__) + +if is_jinja_available(): + import jinja2 + import jinja2.exceptions + import jinja2.ext + import jinja2.meta + import jinja2.nodes + import jinja2.runtime + from jinja2.ext import Extension + from jinja2.sandbox import ImmutableSandboxedEnvironment +else: + jinja2 = None + +if is_vision_available(): + from PIL.Image import Image + +ChatType = list[dict[str, Any]] + + +BASIC_TYPES = (int, float, str, bool, Any, type(None), ...) +# Extracts the initial segment of the docstring, containing the function description +description_re = re.compile(r"^(.*?)[\n\s]*(Args:|Returns:|Raises:|\Z)", re.DOTALL) +# Extracts the Args: block from the docstring +args_re = re.compile(r"\n\s*Args:\n\s*(.*?)[\n\s]*(Returns:|Raises:|\Z)", re.DOTALL) +# Splits the Args: block into individual arguments +args_split_re = re.compile( + r""" +(?:^|\n) # Match the start of the args block, or a newline +\s*(\w+):\s* # Capture the argument name and strip spacing +(.*?)\s* # Capture the argument description, which can span multiple lines, and strip trailing spacing +(?=\n\s*\w+:|\Z) # Stop when you hit the next argument or the end of the block +""", + re.DOTALL | re.VERBOSE, +) +# Extracts the Returns: block from the docstring, if present. Note that most chat templates ignore the return type/doc! +returns_re = re.compile(r"\n\s*Returns:\n\s*(.*?)[\n\s]*(Raises:|\Z)", re.DOTALL) + + +class TypeHintParsingException(Exception): + """Exception raised for errors in parsing type hints to generate JSON schemas""" + + +class DocstringParsingException(Exception): + """Exception raised for errors in parsing docstrings to generate JSON schemas""" + + +def _get_json_schema_type(param_type: type) -> dict[str, str]: + type_mapping = { + int: {"type": "integer"}, + float: {"type": "number"}, + str: {"type": "string"}, + bool: {"type": "boolean"}, + type(None): {"type": "null"}, + Any: {}, + } + if is_vision_available(): + type_mapping[Image] = {"type": "image"} + if is_torch_available(): + import torch + + type_mapping[torch.Tensor] = {"type": "audio"} + return type_mapping.get(param_type, {"type": "object"}) + + +def _parse_type_hint(hint: str) -> dict: + origin = get_origin(hint) + args = get_args(hint) + + if origin is None: + try: + return _get_json_schema_type(hint) + except KeyError: + raise TypeHintParsingException( + "Couldn't parse this type hint, likely due to a custom class or object: ", hint + ) + + elif origin is Union or (hasattr(types, "UnionType") and origin is types.UnionType): + # Recurse into each of the subtypes in the Union, except None, which is handled separately at the end + subtypes = [_parse_type_hint(t) for t in args if t is not type(None)] + if len(subtypes) == 1: + # A single non-null type can be expressed directly + return_dict = subtypes[0] + elif all("type" in subtype and isinstance(subtype["type"], str) for subtype in subtypes): + # A union of basic types can be expressed as a list in the schema + return_dict = {"type": sorted([subtype["type"] for subtype in subtypes])} + else: + # A union of more complex types requires "anyOf" + return_dict = {"anyOf": subtypes} + if type(None) in args: + return_dict["nullable"] = True + return return_dict + + elif origin is Literal and len(args) > 0: + LITERAL_TYPES = (int, float, str, bool, type(None)) + args_types = [] + for arg in args: + if type(arg) not in LITERAL_TYPES: + raise TypeHintParsingException("Only the valid python literals can be listed in typing.Literal.") + arg_type = _get_json_schema_type(type(arg)).get("type") + if arg_type is not None and arg_type not in args_types: + args_types.append(arg_type) + return { + "type": args_types.pop() if len(args_types) == 1 else list(args_types), + "enum": list(args), + } + + elif origin is list: + if not args: + return {"type": "array"} + else: + # Lists can only have a single type argument, so recurse into it + return {"type": "array", "items": _parse_type_hint(args[0])} + + elif origin is tuple: + if not args: + return {"type": "array"} + if len(args) == 1: + raise TypeHintParsingException( + f"The type hint {str(hint).replace('typing.', '')} is a Tuple with a single element, which " + "we do not automatically convert to JSON schema as it is rarely necessary. If this input can contain " + "more than one element, we recommend " + "using a list[] type instead, or if it really is a single element, remove the tuple[] wrapper and just " + "pass the element directly." + ) + if ... in args: + raise TypeHintParsingException( + "Conversion of '...' is not supported in Tuple type hints. " + "Use list[] types for variable-length" + " inputs instead." + ) + return {"type": "array", "prefixItems": [_parse_type_hint(t) for t in args]} + + elif origin is dict: + # The JSON equivalent to a dict is 'object', which mandates that all keys are strings + # However, we can specify the type of the dict values with "additionalProperties" + out = {"type": "object"} + if len(args) == 2: + out["additionalProperties"] = _parse_type_hint(args[1]) + return out + + raise TypeHintParsingException("Couldn't parse this type hint, likely due to a custom class or object: ", hint) + + +def _convert_type_hints_to_json_schema(func: Callable) -> dict: + type_hints = get_type_hints(func) + signature = inspect.signature(func) + func_name = getattr(func, "__name__", "operation") + # For methods, we need to ignore the first "self" or "cls" parameter. Here we assume that if the first parameter + # is named "self" or "cls" and has no type hint, it is an implicit receiver argument. + first_param_name = next(iter(signature.parameters), None) + if ( + first_param_name in {"self", "cls"} + and signature.parameters[first_param_name].annotation == inspect.Parameter.empty + ): + implicit_arg_name = first_param_name + else: + implicit_arg_name = None + required = [] + for param_name, param in signature.parameters.items(): + if param_name == implicit_arg_name: + continue + if param.annotation == inspect.Parameter.empty: + raise TypeHintParsingException(f"Argument {param.name} is missing a type hint in function {func_name}") + if param.default == inspect.Parameter.empty: + required.append(param_name) + + properties = {} + for param_name, param_type in type_hints.items(): + if param_name == implicit_arg_name: + continue + properties[param_name] = _parse_type_hint(param_type) + + schema = {"type": "object", "properties": properties} + if required: + schema["required"] = required + + return schema + + +def parse_google_format_docstring(docstring: str) -> tuple[str | None, dict | None, str | None]: + """ + Parses a Google-style docstring to extract the function description, + argument descriptions, and return description. + + Args: + docstring (str): The docstring to parse. + + Returns: + The function description, arguments, and return description. + """ + + # Extract the sections + description_match = description_re.search(docstring) + args_match = args_re.search(docstring) + returns_match = returns_re.search(docstring) + + # Clean and store the sections + description = description_match.group(1).strip() if description_match else None + docstring_args = args_match.group(1).strip() if args_match else None + returns = returns_match.group(1).strip() if returns_match else None + + # Parsing the arguments into a dictionary + if docstring_args is not None: + docstring_args = "\n".join([line for line in docstring_args.split("\n") if line.strip()]) # Remove blank lines + matches = args_split_re.findall(docstring_args) + args_dict = {match[0]: re.sub(r"\s*\n+\s*", " ", match[1].strip()) for match in matches} + else: + args_dict = {} + + return description, args_dict, returns + + +def get_json_schema(func: Callable) -> dict: + """ + This function generates a JSON schema for a given function, based on its docstring and type hints. This is + mostly used for passing lists of tools to a chat template. The JSON schema contains the name and description of + the function, as well as the names, types and descriptions for each of its arguments. `get_json_schema()` requires + that the function has a docstring, and that each argument has a description in the docstring, in the standard + Google docstring format shown below. It also requires that all user-facing arguments have valid Python type hints. + When passing methods, implicit receiver arguments (`self` or `cls`) are ignored. + + Although it is not required, a `Returns` block can also be added, which will be included in the schema. This is + optional because most chat templates ignore the return value of the function. + + Args: + func: The function to generate a JSON schema for. + + Returns: + A dictionary containing the JSON schema for the function. + + Examples: + ```python + >>> def multiply(x: float, y: float): + >>> ''' + >>> A function that multiplies two numbers + >>> + >>> Args: + >>> x: The first number to multiply + >>> y: The second number to multiply + >>> ''' + >>> return x * y + >>> + >>> print(get_json_schema(multiply)) + { + "name": "multiply", + "description": "A function that multiplies two numbers", + "parameters": { + "type": "object", + "properties": { + "x": {"type": "number", "description": "The first number to multiply"}, + "y": {"type": "number", "description": "The second number to multiply"} + }, + "required": ["x", "y"] + } + } + ``` + + The general use for these schemas is that they are used to generate tool descriptions for chat templates that + support them, like so: + + ```python + >>> from transformers import AutoTokenizer + >>> from transformers.utils import get_json_schema + >>> + >>> def multiply(x: float, y: float): + >>> ''' + >>> A function that multiplies two numbers + >>> + >>> Args: + >>> x: The first number to multiply + >>> y: The second number to multiply + >>> return x * y + >>> ''' + >>> + >>> multiply_schema = get_json_schema(multiply) + >>> tokenizer = AutoTokenizer.from_pretrained("CohereForAI/c4ai-command-r-v01") + >>> messages = [{"role": "user", "content": "What is 179 x 4571?"}] + >>> formatted_chat = tokenizer.apply_chat_template( + >>> messages, + >>> tools=[multiply_schema], + >>> chat_template="tool_use", + >>> return_dict=True, + >>> return_tensors="pt", + >>> add_generation_prompt=True + >>> ) + >>> # The formatted chat can now be passed to model.generate() + ``` + + Each argument description can also have an optional `(choices: ...)` block at the end, such as + `(choices: ["tea", "coffee"])`, which will be parsed into an `enum` field in the schema. Note that this will + only be parsed correctly if it is at the end of the line: + + ```python + >>> def drink_beverage(beverage: str): + >>> ''' + >>> A function that drinks a beverage + >>> + >>> Args: + >>> beverage: The beverage to drink (choices: ["tea", "coffee"]) + >>> ''' + >>> pass + >>> + >>> print(get_json_schema(drink_beverage)) + ``` + { + 'name': 'drink_beverage', + 'description': 'A function that drinks a beverage', + 'parameters': { + 'type': 'object', + 'properties': { + 'beverage': { + 'type': 'string', + 'enum': ['tea', 'coffee'], + 'description': 'The beverage to drink' + } + }, + 'required': ['beverage'] + } + } + """ + doc = inspect.getdoc(func) + func_name = getattr(func, "__name__", "operation") + + if not doc: + raise DocstringParsingException(f"Cannot generate JSON schema for {func_name} because it has no docstring!") + doc = doc.strip() + main_doc, param_descriptions, return_doc = parse_google_format_docstring(doc) + + json_schema = _convert_type_hints_to_json_schema(func) + if (return_dict := json_schema["properties"].pop("return", None)) is not None: + if return_doc is not None: # We allow a missing return docstring since most templates ignore it + return_dict["description"] = return_doc + for arg, schema in json_schema["properties"].items(): + if arg not in param_descriptions: + raise DocstringParsingException( + f"Cannot generate JSON schema for {func_name} because the docstring has no description for the argument '{arg}'" + ) + desc = param_descriptions[arg] + enum_choices = re.search(r"\(choices:\s*(.*?)\)\s*$", desc, flags=re.IGNORECASE) + if enum_choices: + schema["enum"] = [c.strip() for c in json.loads(enum_choices.group(1))] + desc = enum_choices.string[: enum_choices.start()].strip() + schema["description"] = desc + + output = {"name": func_name, "description": main_doc, "parameters": json_schema} + if return_dict is not None: + output["return"] = return_dict + return {"type": "function", "function": output} + + +@lru_cache +@no_type_check +def _get_template_variables(chat_template: str | None) -> frozenset[str]: + """Return the set of undeclared variables referenced by a chat template. + + Uses ``jinja2.meta.find_undeclared_variables`` so that callers can + automatically distinguish template-level kwargs from processor kwargs + without maintaining a manual allowlist. Needed only to support BC as we + allowed all `kwargs` to be merged into one in the past + """ + if chat_template is None: + return frozenset() + compiled = _compile_jinja_template(chat_template) + ast = compiled.environment.parse(chat_template) + return frozenset(jinja2.meta.find_undeclared_variables(ast)) + + +def _render_with_assistant_indices( + compiled_template, messages, tools, documents, add_generation_prompt, **template_kwargs +): + rendered_blocks = [] + generation_indices = [] + with compiled_template.environment.activate_tracker(rendered_blocks, generation_indices): + for block in compiled_template.generate( + messages=messages, + tools=tools, + documents=documents, + add_generation_prompt=add_generation_prompt, + **template_kwargs, + ): + rendered_blocks.append(block) + rendered_chat = "".join(rendered_blocks) + return rendered_chat, generation_indices + + +@lru_cache +def _compile_jinja_template(chat_template): + return _cached_compile_jinja_template(chat_template) + + +@no_type_check +def _cached_compile_jinja_template(chat_template): + if not is_jinja_available(): + raise ImportError( + "apply_chat_template requires jinja2 to be installed. Please install it using `pip install jinja2`." + ) + + class AssistantTracker(Extension): + # This extension is used to track the indices of assistant-generated tokens in the rendered chat + tags = {"generation"} + + def __init__(self, environment: ImmutableSandboxedEnvironment): + # The class is only initiated by jinja. + super().__init__(environment) + environment.extend(activate_tracker=self.activate_tracker) + self._rendered_blocks = None + self._generation_indices = None + + def parse(self, parser: jinja2.parser.Parser) -> jinja2.nodes.CallBlock: + lineno = next(parser.stream).lineno + body = parser.parse_statements(["name:endgeneration"], drop_needle=True) + return jinja2.nodes.CallBlock(self.call_method("_generation_support"), [], [], body).set_lineno(lineno) + + @jinja2.pass_eval_context + def _generation_support(self, context: jinja2.nodes.EvalContext, caller: jinja2.runtime.Macro) -> str: + rv = caller() + if self.is_active(): + # Only track generation indices if the tracker is active + start_index = len("".join(self._rendered_blocks)) + end_index = start_index + len(rv) + self._generation_indices.append((start_index, end_index)) + return rv + + def is_active(self) -> bool: + return self._rendered_blocks is not None or self._generation_indices is not None + + @contextmanager + def activate_tracker(self, rendered_blocks: list[int], generation_indices: list[int]): + try: + if self.is_active(): + raise ValueError("AssistantTracker should not be reused before closed") + self._rendered_blocks = rendered_blocks + self._generation_indices = generation_indices + + yield + finally: + self._rendered_blocks = None + self._generation_indices = None + + if version.parse(jinja2.__version__) < version.parse("3.1.0"): + raise ImportError( + f"apply_chat_template requires jinja2>=3.1.0 to be installed. Your version is {jinja2.__version__}." + ) + + def raise_exception(message): + raise jinja2.exceptions.TemplateError(message) + + def tojson(x, ensure_ascii=False, indent=None, separators=None, sort_keys=False): + # We override the built-in tojson filter because Jinja's default filter escapes HTML characters + # We also expose some options like custom indents and separators + return json.dumps(x, ensure_ascii=ensure_ascii, indent=indent, separators=separators, sort_keys=sort_keys) + + def strftime_now(format): + return datetime.now().strftime(format) + + jinja_env = ImmutableSandboxedEnvironment( + trim_blocks=True, lstrip_blocks=True, extensions=[AssistantTracker, jinja2.ext.loopcontrols] + ) + jinja_env.filters["tojson"] = tojson + jinja_env.globals["raise_exception"] = raise_exception + jinja_env.globals["strftime_now"] = strftime_now + return jinja_env.from_string(chat_template) + + +def render_jinja_template( + conversations: list[ChatType], + tools: list[dict | Callable] | None = None, + documents: ChatType | None = None, + chat_template: str | None = None, + return_assistant_tokens_mask: bool = False, + continue_final_message: bool = False, + add_generation_prompt: bool = False, + **kwargs, +) -> str: + if return_assistant_tokens_mask and not re.search(r"\{\%-?\s*generation\s*-?\%\}", chat_template): + logger.warning_once( + "return_assistant_tokens_mask==True but chat template does not contain `{% generation %}` keyword." + ) + + # Compilation function uses a cache to avoid recompiling the same template + compiled_template = _compile_jinja_template(chat_template) + + # We accept either JSON schemas or functions for tools. If we get functions, we convert them to schemas + if tools is not None: + tool_schemas = [] + for tool in tools: + if isinstance(tool, dict): + tool_schemas.append(tool) + elif isfunction(tool) or inspect.ismethod(tool): + tool_schemas.append(get_json_schema(tool)) + else: + raise ValueError( + "Tools should either be a JSON schema, or a callable function with type hints " + "and a docstring suitable for auto-conversion to a schema." + ) + else: + tool_schemas = None + + if documents is not None: + for document in documents: + if not isinstance(document, dict): + raise TypeError("Documents should be a list of dicts with 'title' and 'text' keys!") + + rendered = [] + all_generation_indices = [] + continue_final_message_tag = "CONTINUE_FINAL_MESSAGE_TAG " + for chat in conversations: + if hasattr(chat, "messages"): + # Indicates it's a Conversation object + chat = chat.messages + if continue_final_message: + chat = deepcopy(chat) + final_message = chat[-1].get("content") + if final_message is None: + raise ValueError("continue_final_message is set but the final message has no content to continue!") + elif isinstance(final_message, (list, tuple)): + for content_block in reversed(final_message): + if "text" in content_block: + # Pick the last text block in the message (the first one we hit while iterating in reverse) + final_message = content_block["text"] + content_block["text"] = content_block["text"] + continue_final_message_tag + break + else: + raise ValueError( + "continue_final_message is set but we could not find any text to continue in the final message!" + ) + else: + chat[-1]["content"] = chat[-1]["content"] + continue_final_message_tag + if return_assistant_tokens_mask: + rendered_chat, generation_indices = _render_with_assistant_indices( + compiled_template=compiled_template, + messages=chat, + tools=tool_schemas, + documents=documents, + add_generation_prompt=add_generation_prompt, + **kwargs, + ) + all_generation_indices.append(generation_indices) + else: + rendered_chat = compiled_template.render( + messages=chat, + tools=tool_schemas, + documents=documents, + add_generation_prompt=add_generation_prompt, + **kwargs, + ) + if continue_final_message: + if (final_message.strip() not in rendered_chat) or ( + continue_final_message_tag.strip() not in rendered_chat + ): + raise ValueError( + "continue_final_message is set but the final message does not appear in the chat after " + "applying the chat template! This can happen if the chat template deletes portions of " + "the final message. Please verify the chat template and final message in your chat to " + "ensure they are compatible." + ) + tag_loc = rendered_chat.rindex(continue_final_message_tag.strip()) + if rendered_chat[tag_loc : tag_loc + len(continue_final_message_tag)] == continue_final_message_tag: + # The template preserves spacing, so things are simple + rendered_chat = rendered_chat[:tag_loc] + else: + # The message has trailing spacing that was trimmed, so we must be more cautious + rendered_chat = rendered_chat[:tag_loc].rstrip() + rendered.append(rendered_chat) + + return rendered, all_generation_indices + + +def is_valid_message(message): + """ + Check that input is a valid message in a chat, namely a dict with "role" and "content" keys. + """ + if not isinstance(message, dict): + return False + if not ("role" in message and "content" in message): + return False + return True + + +class Chat: + """This class is intended to just be used internally for pipelines and not exposed to users. We convert chats + to this format because the rest of the pipeline code tends to assume that lists of messages are + actually a batch of samples rather than messages in the same conversation.""" + + def __init__(self, messages: dict): + for message in messages: + if not is_valid_message(message): + raise ValueError("When passing chat dicts as input, each dict must have a 'role' and 'content' key.") + self.messages = messages diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/constants.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..fefd1b4601da04e073ff2880099ccaf87d0b1666 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/constants.py @@ -0,0 +1,6 @@ +IMAGENET_DEFAULT_MEAN = [0.485, 0.456, 0.406] +IMAGENET_DEFAULT_STD = [0.229, 0.224, 0.225] +IMAGENET_STANDARD_MEAN = [0.5, 0.5, 0.5] +IMAGENET_STANDARD_STD = [0.5, 0.5, 0.5] +OPENAI_CLIP_MEAN = [0.48145466, 0.4578275, 0.40821073] +OPENAI_CLIP_STD = [0.26862954, 0.26130258, 0.27577711] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/deprecation.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/deprecation.py new file mode 100644 index 0000000000000000000000000000000000000000..db0e67325d7811d41d1ca90f49813ed0fb803f0f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/deprecation.py @@ -0,0 +1,175 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# 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. +import inspect +import warnings +from functools import wraps + +import packaging.version + +from .. import __version__ +from . import ExplicitEnum, is_torch_available, is_torchdynamo_compiling + + +# This is needed in case we deprecate a kwarg of a function/method being compiled +if is_torch_available(): + import torch # noqa: F401 + + +class Action(ExplicitEnum): + NONE = "none" + NOTIFY = "notify" + NOTIFY_ALWAYS = "notify_always" + RAISE = "raise" + + +def deprecate_kwarg( + old_name: str, + version: str, + new_name: str | None = None, + warn_if_greater_or_equal_version: bool = False, + raise_if_greater_or_equal_version: bool = False, + raise_if_both_names: bool = False, + additional_message: str | None = None, +): + """ + Function or method decorator to notify users about deprecated keyword arguments, replacing them with a new name if specified. + Note that is decorator is `torch.compile`-safe, i.e. it will not cause graph breaks (but no warning will be displayed if compiling). + + This decorator allows you to: + - Notify users when a keyword argument is deprecated. + - Automatically replace deprecated keyword arguments with new ones. + - Raise an error if deprecated arguments are used, depending on the specified conditions. + + By default, the decorator notifies the user about the deprecated argument while the `transformers.__version__` < specified `version` + in the decorator. To keep notifications with any version `warn_if_greater_or_equal_version=True` can be set. + + Parameters: + old_name (`str`): + Name of the deprecated keyword argument. + version (`str`): + The version in which the keyword argument was (or will be) deprecated. + new_name (`Optional[str]`, *optional*): + The new name for the deprecated keyword argument. If specified, the deprecated keyword argument will be replaced with this new name. + warn_if_greater_or_equal_version (`bool`, *optional*, defaults to `False`): + Whether to show warning if current `transformers` version is greater or equal to the deprecated version. + raise_if_greater_or_equal_version (`bool`, *optional*, defaults to `False`): + Whether to raise `ValueError` if current `transformers` version is greater or equal to the deprecated version. + raise_if_both_names (`bool`, *optional*, defaults to `False`): + Whether to raise `ValueError` if both deprecated and new keyword arguments are set. + additional_message (`Optional[str]`, *optional*): + An additional message to append to the default deprecation message. + + Raises: + ValueError: + If raise_if_greater_or_equal_version is True and the current version is greater than or equal to the deprecated version, or if raise_if_both_names is True and both old and new keyword arguments are provided. + + Returns: + Callable: + A wrapped function that handles the deprecated keyword arguments according to the specified parameters. + + Example usage with renaming argument: + + ```python + @deprecate_kwarg("reduce_labels", new_name="do_reduce_labels", version="6.0.0") + def my_function(do_reduce_labels): + print(do_reduce_labels) + + my_function(reduce_labels=True) # Will show a deprecation warning and use do_reduce_labels=True + ``` + + Example usage without renaming argument: + + ```python + @deprecate_kwarg("max_size", version="6.0.0") + def my_function(max_size): + print(max_size) + + my_function(max_size=1333) # Will show a deprecation warning + ``` + + """ + + deprecated_version = packaging.version.parse(version) + current_version = packaging.version.parse(__version__) + is_greater_or_equal_version = current_version >= deprecated_version + + if is_greater_or_equal_version: + version_message = f"and removed starting from version {version}" + else: + version_message = f"and will be removed in version {version}" + + def wrapper(func): + # Required for better warning message + sig = inspect.signature(func) + function_named_args = set(sig.parameters.keys()) + is_instance_method = "self" in function_named_args + is_class_method = "cls" in function_named_args + + @wraps(func) + def wrapped_func(*args, **kwargs): + # Get class + function name (just for better warning message) + func_name = func.__name__ + if is_instance_method: + func_name = f"{args[0].__class__.__name__}.{func_name}" + elif is_class_method: + func_name = f"{args[0].__name__}.{func_name}" + + minimum_action = Action.NONE + message = None + + # deprecated kwarg and its new version are set for function call -> replace it with new name + if old_name in kwargs and new_name in kwargs: + minimum_action = Action.RAISE if raise_if_both_names else Action.NOTIFY_ALWAYS + message = f"Both `{old_name}` and `{new_name}` are set for `{func_name}`. Using `{new_name}={kwargs[new_name]}` and ignoring deprecated `{old_name}={kwargs[old_name]}`." + kwargs.pop(old_name) + + # only deprecated kwarg is set for function call -> replace it with new name + elif old_name in kwargs and new_name is not None and new_name not in kwargs: + minimum_action = Action.NOTIFY + message = f"`{old_name}` is deprecated {version_message} for `{func_name}`. Use `{new_name}` instead." + kwargs[new_name] = kwargs.pop(old_name) + + # deprecated kwarg is not set for function call and new name is not specified -> just notify + elif old_name in kwargs: + minimum_action = Action.NOTIFY + message = f"`{old_name}` is deprecated {version_message} for `{func_name}`." + + if message is not None and additional_message is not None: + message = f"{message} {additional_message}" + + # update minimum_action if argument is ALREADY deprecated (current version >= deprecated version) + if is_greater_or_equal_version: + # change to (NOTIFY, NOTIFY_ALWAYS) -> RAISE if specified + # in case we want to raise error for already deprecated arguments + if raise_if_greater_or_equal_version and minimum_action != Action.NONE: + minimum_action = Action.RAISE + + # change to NOTIFY -> NONE if specified (NOTIFY_ALWAYS can't be changed to NONE) + # in case we want to ignore notifications for already deprecated arguments + elif not warn_if_greater_or_equal_version and minimum_action == Action.NOTIFY: + minimum_action = Action.NONE + + # raise error or notify user + if minimum_action == Action.RAISE: + raise ValueError(message) + # If we are compiling, we do not raise the warning as it would break compilation + elif minimum_action in (Action.NOTIFY, Action.NOTIFY_ALWAYS) and not is_torchdynamo_compiling(): + # DeprecationWarning is ignored by default, so we use FutureWarning instead + warnings.warn(message, FutureWarning, stacklevel=2) + + return func(*args, **kwargs) + + return wrapped_func + + return wrapper diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/doc.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/doc.py new file mode 100644 index 0000000000000000000000000000000000000000..ae111f11d19cc020544aab7dcb2fed875d6c04ab --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/doc.py @@ -0,0 +1,1091 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# 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. +""" +Doc utilities: Utilities related to documentation +""" + +import functools +import inspect +import re +import textwrap +import types +from collections import OrderedDict +from typing import cast + + +def get_docstring_indentation_level(func): + """Return the indentation level of the start of the docstring of a class or function (or method).""" + # We assume classes are always defined in the global scope + if inspect.isclass(func): + return 4 + source = inspect.getsource(func) + first_line = source.splitlines()[0] + function_def_level = len(first_line) - len(first_line.lstrip()) + return 4 + function_def_level + + +def add_start_docstrings(*docstr): + def docstring_decorator(fn): + fn.__doc__ = "".join(docstr) + (fn.__doc__ if fn.__doc__ is not None else "") + return fn + + return docstring_decorator + + +def add_start_docstrings_to_model_forward(*docstr): + def docstring_decorator(fn): + class_name = f"[`{fn.__qualname__.split('.')[0]}`]" + intro = rf""" The {class_name} forward method, overrides the `__call__` special method. + + + + Although the recipe for forward pass needs to be defined within this function, one should call the [`Module`] + instance afterwards instead of this since the former takes care of running the pre and post processing steps while + the latter silently ignores them. + + +""" + + correct_indentation = get_docstring_indentation_level(fn) + current_doc = fn.__doc__ if fn.__doc__ is not None else "" + try: + first_non_empty = next(line for line in current_doc.splitlines() if line.strip() != "") + doc_indentation = len(first_non_empty) - len(first_non_empty.lstrip()) + except StopIteration: + doc_indentation = correct_indentation + + docs = docstr + # In this case, the correct indentation level (class method, 2 Python levels) was respected, and we should + # correctly reindent everything. Otherwise, the doc uses a single indentation level + if doc_indentation == 4 + correct_indentation: + docs = [textwrap.indent(textwrap.dedent(doc), " " * correct_indentation) for doc in docstr] + intro = textwrap.indent(textwrap.dedent(intro), " " * correct_indentation) + + docstring = "".join(docs) + current_doc + fn.__doc__ = intro + docstring + return fn + + return docstring_decorator + + +def add_end_docstrings(*docstr): + def docstring_decorator(fn): + fn.__doc__ = (fn.__doc__ if fn.__doc__ is not None else "") + "".join(docstr) + return fn + + return docstring_decorator + + +PT_RETURN_INTRODUCTION = r""" + Returns: + [`{full_output_type}`] or `tuple(torch.FloatTensor)`: A [`{full_output_type}`] or a tuple of + `torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various + elements depending on the configuration ([`{config_class}`]) and inputs. + +""" + + +def _get_indent(t): + """Returns the indentation in the first line of t""" + search = re.search(r"^(\s*)\S", t) + return "" if search is None else search.groups()[0] + + +def _convert_output_args_doc(output_args_doc): + """Convert output_args_doc to display properly.""" + # Split output_arg_doc in blocks argument/description + indent = _get_indent(output_args_doc) + blocks = [] + current_block = "" + for line in output_args_doc.split("\n"): + # If the indent is the same as the beginning, the line is the name of new arg. + if _get_indent(line) == indent: + if len(current_block) > 0: + blocks.append(current_block[:-1]) + current_block = f"{line}\n" + else: + # Otherwise it's part of the description of the current arg. + # We need to remove 2 spaces to the indentation. + current_block += f"{line[2:]}\n" + blocks.append(current_block[:-1]) + + # Format each block for proper rendering + for i in range(len(blocks)): + blocks[i] = re.sub(r"^(\s+)(\S+)(\s+)", r"\1- **\2**\3", blocks[i]) + blocks[i] = re.sub(r":\s*\n\s*(\S)", r" -- \1", blocks[i]) + + return "\n".join(blocks) + + +def _prepare_output_docstrings(output_type, config_class, min_indent=None, add_intro=True): + """ + Prepares the return part of the docstring using `output_type`. + """ + output_docstring = output_type.__doc__ + params_docstring = None + if output_docstring is not None: + # Remove the head of the docstring to keep the list of args only + lines = output_docstring.split("\n") + i = 0 + while i < len(lines) and re.search(r"^\s*(Args|Parameters):\s*$", lines[i]) is None: + i += 1 + if i < len(lines): + params_docstring = "\n".join(lines[(i + 1) :]) + params_docstring = _convert_output_args_doc(params_docstring) + elif add_intro: + raise ValueError( + f"No `Args` or `Parameters` section is found in the docstring of `{output_type.__name__}`. Make sure it has " + "docstring and contain either `Args` or `Parameters`." + ) + + # Add the return introduction + if add_intro: + full_output_type = f"{output_type.__module__}.{output_type.__name__}" + intro = PT_RETURN_INTRODUCTION.format(full_output_type=full_output_type, config_class=config_class) + else: + full_output_type = str(output_type) + intro = f"\nReturns:\n `{full_output_type}`" + if params_docstring is not None: + intro += ":\n" + + result = intro + if params_docstring is not None: + result += params_docstring + + # Apply minimum indent if necessary + if min_indent is not None: + lines = result.split("\n") + # Find the indent of the first nonempty line + i = 0 + while len(lines[i]) == 0: + i += 1 + indent = len(_get_indent(lines[i])) + # If too small, add indentation to all nonempty lines + if indent < min_indent: + to_add = " " * (min_indent - indent) + lines = [(f"{to_add}{line}" if len(line) > 0 else line) for line in lines] + result = "\n".join(lines) + + return result + + +FAKE_MODEL_DISCLAIMER = """ + + + This example uses a random model as the real ones are all very big. To get proper results, you should use + {real_checkpoint} instead of {fake_checkpoint}. If you get out-of-memory when loading that checkpoint, you can try + adding `device_map="auto"` in the `from_pretrained` call. + + +""" + + +PT_TOKEN_CLASSIFICATION_SAMPLE = r""" + Example: + + ```python + >>> from transformers import AutoTokenizer, {model_class} + >>> import torch + + >>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}") + >>> model = {model_class}.from_pretrained("{checkpoint}") + + >>> inputs = tokenizer( + ... "HuggingFace is a company based in Paris and New York", add_special_tokens=False, return_tensors="pt" + ... ) + + >>> with torch.no_grad(): + ... logits = model(**inputs).logits + + >>> predicted_token_class_ids = logits.argmax(-1) + + >>> # Note that tokens are classified rather then input words which means that + >>> # there might be more predicted token classes than words. + >>> # Multiple token classes might account for the same word + >>> predicted_tokens_classes = [model.config.id2label[t.item()] for t in predicted_token_class_ids[0]] + >>> predicted_tokens_classes + {expected_output} + + >>> labels = predicted_token_class_ids + >>> loss = model(**inputs, labels=labels).loss + >>> round(loss.item(), 2) + {expected_loss} + ``` +""" + +PT_QUESTION_ANSWERING_SAMPLE = r""" + Example: + + ```python + >>> from transformers import AutoTokenizer, {model_class} + >>> import torch + + >>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}") + >>> model = {model_class}.from_pretrained("{checkpoint}") + + >>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet" + + >>> inputs = tokenizer(question, text, return_tensors="pt") + >>> with torch.no_grad(): + ... outputs = model(**inputs) + + >>> answer_start_index = outputs.start_logits.argmax() + >>> answer_end_index = outputs.end_logits.argmax() + + >>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1] + >>> tokenizer.decode(predict_answer_tokens, skip_special_tokens=True) + {expected_output} + + >>> # target is "nice puppet" + >>> target_start_index = torch.tensor([{qa_target_start_index}]) + >>> target_end_index = torch.tensor([{qa_target_end_index}]) + + >>> outputs = model(**inputs, start_positions=target_start_index, end_positions=target_end_index) + >>> loss = outputs.loss + >>> round(loss.item(), 2) + {expected_loss} + ``` +""" + +PT_SEQUENCE_CLASSIFICATION_SAMPLE = r""" + Example of single-label classification: + + ```python + >>> import torch + >>> from transformers import AutoTokenizer, {model_class} + + >>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}") + >>> model = {model_class}.from_pretrained("{checkpoint}") + + >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") + + >>> with torch.no_grad(): + ... logits = model(**inputs).logits + + >>> predicted_class_id = logits.argmax().item() + >>> model.config.id2label[predicted_class_id] + {expected_output} + + >>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)` + >>> num_labels = len(model.config.id2label) + >>> model = {model_class}.from_pretrained("{checkpoint}", num_labels=num_labels) + + >>> labels = torch.tensor([1]) + >>> loss = model(**inputs, labels=labels).loss + >>> round(loss.item(), 2) + {expected_loss} + ``` + + Example of multi-label classification: + + ```python + >>> import torch + >>> from transformers import AutoTokenizer, {model_class} + + >>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}") + >>> model = {model_class}.from_pretrained("{checkpoint}", problem_type="multi_label_classification") + + >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") + + >>> with torch.no_grad(): + ... logits = model(**inputs).logits + + >>> predicted_class_ids = torch.arange(0, logits.shape[-1])[torch.sigmoid(logits).squeeze(dim=0) > 0.5] + + >>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)` + >>> num_labels = len(model.config.id2label) + >>> model = {model_class}.from_pretrained( + ... "{checkpoint}", num_labels=num_labels, problem_type="multi_label_classification" + ... ) + + >>> labels = torch.sum( + ... torch.nn.functional.one_hot(predicted_class_ids[None, :].clone(), num_classes=num_labels), dim=1 + ... ).to(torch.float) + >>> loss = model(**inputs, labels=labels).loss + ``` +""" + +PT_MASKED_LM_SAMPLE = r""" + Example: + + ```python + >>> from transformers import AutoTokenizer, {model_class} + >>> import torch + + >>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}") + >>> model = {model_class}.from_pretrained("{checkpoint}") + + >>> inputs = tokenizer("The capital of France is {mask}.", return_tensors="pt") + + >>> with torch.no_grad(): + ... logits = model(**inputs).logits + + >>> # retrieve index of {mask} + >>> mask_token_index = (inputs.input_ids == tokenizer.mask_token_id)[0].nonzero(as_tuple=True)[0] + + >>> predicted_token_id = logits[0, mask_token_index].argmax(axis=-1) + >>> tokenizer.decode(predicted_token_id) + {expected_output} + + >>> labels = tokenizer("The capital of France is Paris.", return_tensors="pt")["input_ids"] + >>> # mask labels of non-{mask} tokens + >>> labels = torch.where(inputs.input_ids == tokenizer.mask_token_id, labels, -100) + + >>> outputs = model(**inputs, labels=labels) + >>> round(outputs.loss.item(), 2) + {expected_loss} + ``` +""" + +PT_BASE_MODEL_SAMPLE = r""" + Example: + + ```python + >>> from transformers import AutoTokenizer, {model_class} + >>> import torch + + >>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}") + >>> model = {model_class}.from_pretrained("{checkpoint}") + + >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") + >>> outputs = model(**inputs) + + >>> last_hidden_states = outputs.last_hidden_state + ``` +""" + +PT_MULTIPLE_CHOICE_SAMPLE = r""" + Example: + + ```python + >>> from transformers import AutoTokenizer, {model_class} + >>> import torch + + >>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}") + >>> model = {model_class}.from_pretrained("{checkpoint}") + + >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced." + >>> choice0 = "It is eaten with a fork and a knife." + >>> choice1 = "It is eaten while held in the hand." + >>> labels = torch.tensor(0).unsqueeze(0) # choice0 is correct (according to Wikipedia ;)), batch size 1 + + >>> encoding = tokenizer([prompt, prompt], [choice0, choice1], return_tensors="pt", padding=True) + >>> outputs = model(**{{k: v.unsqueeze(0) for k, v in encoding.items()}}, labels=labels) # batch size is 1 + + >>> # the linear classifier still needs to be trained + >>> loss = outputs.loss + >>> logits = outputs.logits + ``` +""" + +PT_CAUSAL_LM_SAMPLE = r""" + Example: + + ```python + >>> import torch + >>> from transformers import AutoTokenizer, {model_class} + + >>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}") + >>> model = {model_class}.from_pretrained("{checkpoint}") + + >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") + >>> outputs = model(**inputs, labels=inputs["input_ids"]) + >>> loss = outputs.loss + >>> logits = outputs.logits + ``` +""" + +PT_SPEECH_BASE_MODEL_SAMPLE = r""" + Example: + + ```python + >>> from transformers import AutoProcessor, {model_class} + >>> import torch + >>> from datasets import load_dataset + + >>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation") + >>> dataset = dataset.sort("id") + >>> sampling_rate = dataset.features["audio"].sampling_rate + + >>> processor = AutoProcessor.from_pretrained("{checkpoint}") + >>> model = {model_class}.from_pretrained("{checkpoint}") + + >>> # audio file is decoded on the fly + >>> inputs = processor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt") + >>> with torch.no_grad(): + ... outputs = model(**inputs) + + >>> last_hidden_states = outputs.last_hidden_state + >>> list(last_hidden_states.shape) + {expected_output} + ``` +""" + +PT_SPEECH_CTC_SAMPLE = r""" + Example: + + ```python + >>> from transformers import AutoProcessor, {model_class} + >>> from datasets import load_dataset + >>> import torch + + >>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation") + >>> dataset = dataset.sort("id") + >>> sampling_rate = dataset.features["audio"].sampling_rate + + >>> processor = AutoProcessor.from_pretrained("{checkpoint}") + >>> model = {model_class}.from_pretrained("{checkpoint}") + + >>> # audio file is decoded on the fly + >>> inputs = processor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt") + >>> with torch.no_grad(): + ... logits = model(**inputs).logits + >>> predicted_ids = torch.argmax(logits, dim=-1) + + >>> # transcribe speech + >>> transcription = processor.batch_decode(predicted_ids) + >>> transcription[0] + {expected_output} + + >>> inputs["labels"] = processor(text=dataset[0]["text"], return_tensors="pt").input_ids + + >>> # compute loss + >>> loss = model(**inputs).loss + >>> round(loss.item(), 2) + {expected_loss} + ``` +""" + +PT_SPEECH_SEQ_CLASS_SAMPLE = r""" + Example: + + ```python + >>> from transformers import AutoFeatureExtractor, {model_class} + >>> from datasets import load_dataset + >>> import torch + + >>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation") + >>> dataset = dataset.sort("id") + >>> sampling_rate = dataset.features["audio"].sampling_rate + + >>> feature_extractor = AutoFeatureExtractor.from_pretrained("{checkpoint}") + >>> model = {model_class}.from_pretrained("{checkpoint}") + + >>> # audio file is decoded on the fly + >>> inputs = feature_extractor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt") + + >>> with torch.no_grad(): + ... logits = model(**inputs).logits + + >>> predicted_class_ids = torch.argmax(logits, dim=-1).item() + >>> predicted_label = model.config.id2label[predicted_class_ids] + >>> predicted_label + {expected_output} + + >>> # compute loss - target_label is e.g. "down" + >>> target_label = model.config.id2label[0] + >>> inputs["labels"] = torch.tensor([model.config.label2id[target_label]]) + >>> loss = model(**inputs).loss + >>> round(loss.item(), 2) + {expected_loss} + ``` +""" + + +PT_SPEECH_FRAME_CLASS_SAMPLE = r""" + Example: + + ```python + >>> from transformers import AutoFeatureExtractor, {model_class} + >>> from datasets import load_dataset + >>> import torch + + >>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation") + >>> dataset = dataset.sort("id") + >>> sampling_rate = dataset.features["audio"].sampling_rate + + >>> feature_extractor = AutoFeatureExtractor.from_pretrained("{checkpoint}") + >>> model = {model_class}.from_pretrained("{checkpoint}") + + >>> # audio file is decoded on the fly + >>> inputs = feature_extractor(dataset[0]["audio"]["array"], return_tensors="pt", sampling_rate=sampling_rate) + >>> with torch.no_grad(): + ... logits = model(**inputs).logits + + >>> probabilities = torch.sigmoid(logits[0]) + >>> # labels is a one-hot array of shape (num_frames, num_speakers) + >>> labels = (probabilities > 0.5).long() + >>> labels[0].tolist() + {expected_output} + ``` +""" + + +PT_SPEECH_XVECTOR_SAMPLE = r""" + Example: + + ```python + >>> from transformers import AutoFeatureExtractor, {model_class} + >>> from datasets import load_dataset + >>> import torch + + >>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation") + >>> dataset = dataset.sort("id") + >>> sampling_rate = dataset.features["audio"].sampling_rate + + >>> feature_extractor = AutoFeatureExtractor.from_pretrained("{checkpoint}") + >>> model = {model_class}.from_pretrained("{checkpoint}") + + >>> # audio file is decoded on the fly + >>> inputs = feature_extractor( + ... [d["array"] for d in dataset[:2]["audio"]], sampling_rate=sampling_rate, return_tensors="pt", padding=True + ... ) + >>> with torch.no_grad(): + ... embeddings = model(**inputs).embeddings + + >>> embeddings = torch.nn.functional.normalize(embeddings, dim=-1).cpu() + + >>> # the resulting embeddings can be used for cosine similarity-based retrieval + >>> cosine_sim = torch.nn.CosineSimilarity(dim=-1) + >>> similarity = cosine_sim(embeddings[0], embeddings[1]) + >>> threshold = 0.7 # the optimal threshold is dataset-dependent + >>> if similarity < threshold: + ... print("Speakers are not the same!") + >>> round(similarity.item(), 2) + {expected_output} + ``` +""" + +PT_VISION_BASE_MODEL_SAMPLE = r""" + Example: + + ```python + >>> from transformers import AutoImageProcessor, {model_class} + >>> import torch + >>> from datasets import load_dataset + + >>> dataset = load_dataset("huggingface/cats-image") + >>> image = dataset["test"]["image"][0] + + >>> image_processor = AutoImageProcessor.from_pretrained("{checkpoint}") + >>> model = {model_class}.from_pretrained("{checkpoint}") + + >>> inputs = image_processor(image, return_tensors="pt") + + >>> with torch.no_grad(): + ... outputs = model(**inputs) + + >>> last_hidden_states = outputs.last_hidden_state + >>> list(last_hidden_states.shape) + {expected_output} + ``` +""" + +PT_VISION_SEQ_CLASS_SAMPLE = r""" + Example: + + ```python + >>> from transformers import AutoImageProcessor, {model_class} + >>> import torch + >>> from datasets import load_dataset + + >>> dataset = load_dataset("huggingface/cats-image") + >>> image = dataset["test"]["image"][0] + + >>> image_processor = AutoImageProcessor.from_pretrained("{checkpoint}") + >>> model = {model_class}.from_pretrained("{checkpoint}") + + >>> inputs = image_processor(image, return_tensors="pt") + + >>> with torch.no_grad(): + ... logits = model(**inputs).logits + + >>> # model predicts one of the 1000 ImageNet classes + >>> predicted_label = logits.argmax(-1).item() + >>> print(model.config.id2label[predicted_label]) + {expected_output} + ``` +""" + + +PT_SAMPLE_DOCSTRINGS = { + "SequenceClassification": PT_SEQUENCE_CLASSIFICATION_SAMPLE, + "QuestionAnswering": PT_QUESTION_ANSWERING_SAMPLE, + "TokenClassification": PT_TOKEN_CLASSIFICATION_SAMPLE, + "MultipleChoice": PT_MULTIPLE_CHOICE_SAMPLE, + "MaskedLM": PT_MASKED_LM_SAMPLE, + "LMHead": PT_CAUSAL_LM_SAMPLE, + "BaseModel": PT_BASE_MODEL_SAMPLE, + "SpeechBaseModel": PT_SPEECH_BASE_MODEL_SAMPLE, + "CTC": PT_SPEECH_CTC_SAMPLE, + "AudioClassification": PT_SPEECH_SEQ_CLASS_SAMPLE, + "AudioFrameClassification": PT_SPEECH_FRAME_CLASS_SAMPLE, + "AudioXVector": PT_SPEECH_XVECTOR_SAMPLE, + "VisionBaseModel": PT_VISION_BASE_MODEL_SAMPLE, + "ImageClassification": PT_VISION_SEQ_CLASS_SAMPLE, +} + + +TEXT_TO_AUDIO_SPECTROGRAM_SAMPLE = r""" + Example: + + ```python + >>> from transformers import AutoProcessor, {model_class}, SpeechT5HifiGan + + >>> model = {model_class}.from_pretrained("{checkpoint}") + + >>> processor = AutoProcessor.from_pretrained("{checkpoint}") + >>> vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan") + >>> inputs = processor(text="Hello, my dog is cute", return_tensors="pt") + + >>> # generate speech + >>> speech = model.generate(inputs["input_ids"], speaker_embeddings=speaker_embeddings, vocoder=vocoder) + ``` +""" + + +TEXT_TO_AUDIO_WAVEFORM_SAMPLE = r""" + Example: + + ```python + >>> from transformers import AutoProcessor, {model_class} + + >>> model = {model_class}.from_pretrained("{checkpoint}") + + >>> processor = AutoProcessor.from_pretrained("{checkpoint}") + >>> inputs = processor(text="Hello, my dog is cute", return_tensors="pt") + + >>> # generate speech + >>> speech = model(inputs["input_ids"]) + ``` +""" + + +AUDIO_FRAME_CLASSIFICATION_SAMPLE = PT_SPEECH_FRAME_CLASS_SAMPLE + + +AUDIO_XVECTOR_SAMPLE = PT_SPEECH_XVECTOR_SAMPLE + + +DEPTH_ESTIMATION_SAMPLE = r""" + Example: + + ```python + >>> from transformers import AutoImageProcessor, {model_class} + >>> import torch + >>> from PIL import Image + >>> import httpx + >>> from io import BytesIO + + >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" + >>> with httpx.stream("GET", url) as response: + ... image = Image.open(BytesIO(response.read())).convert("RGB") + + >>> processor = AutoImageProcessor.from_pretrained("{checkpoint}") + >>> model = {model_class}.from_pretrained("{checkpoint}") + + >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + >>> model.to(device) + + >>> # prepare image for the model + >>> inputs = processor(images=image, return_tensors="pt").to(device) + + >>> with torch.no_grad(): + ... outputs = model(**inputs) + + >>> # interpolate to original size + >>> post_processed_output = processor.post_process_depth_estimation( + ... outputs, [(image.height, image.width)], + ... ) + >>> predicted_depth = post_processed_output[0]["predicted_depth"] + ``` +""" + + +VIDEO_CLASSIFICATION_SAMPLE = r""" + Example: + + ```python + ``` +""" + + +ZERO_SHOT_OBJECT_DETECTION_SAMPLE = r""" + Example: + + ```python + ``` +""" + + +IMAGE_TO_IMAGE_SAMPLE = r""" + Example: + + ```python + ``` +""" + + +IMAGE_FEATURE_EXTRACTION_SAMPLE = r""" + Example: + + ```python + ``` +""" + + +DOCUMENT_QUESTION_ANSWERING_SAMPLE = r""" + Example: + + ```python + ``` +""" + + +NEXT_SENTENCE_PREDICTION_SAMPLE = r""" + Example: + + ```python + ``` +""" + + +MULTIPLE_CHOICE_SAMPLE = PT_MULTIPLE_CHOICE_SAMPLE + + +PRETRAINING_SAMPLE = r""" + Example: + + ```python + ``` +""" +MASK_GENERATION_SAMPLE = r""" + Example: + + ```python + ``` +""" + + +VISUAL_QUESTION_ANSWERING_SAMPLE = r""" + Example: + + ```python + ``` +""" + + +TEXT_GENERATION_SAMPLE = r""" + Example: + + ```python + ``` +""" + + +IMAGE_CLASSIFICATION_SAMPLE = PT_VISION_SEQ_CLASS_SAMPLE + + +IMAGE_SEGMENTATION_SAMPLE = r""" + Example: + + ```python + ``` +""" + + +FILL_MASK_SAMPLE = r""" + Example: + + ```python + ``` +""" + + +OBJECT_DETECTION_SAMPLE = r""" + Example: + + ```python + ``` +""" + + +QUESTION_ANSWERING_SAMPLE = PT_QUESTION_ANSWERING_SAMPLE + + +TEXT_CLASSIFICATION_SAMPLE = PT_SEQUENCE_CLASSIFICATION_SAMPLE + + +TABLE_QUESTION_ANSWERING_SAMPLE = r""" + Example: + + ```python + ``` +""" + + +TOKEN_CLASSIFICATION_SAMPLE = PT_TOKEN_CLASSIFICATION_SAMPLE + + +AUDIO_CLASSIFICATION_SAMPLE = PT_SPEECH_SEQ_CLASS_SAMPLE + + +AUTOMATIC_SPEECH_RECOGNITION_SAMPLE = PT_SPEECH_CTC_SAMPLE + + +ZERO_SHOT_IMAGE_CLASSIFICATION_SAMPLE = r""" + Example: + + ```python + ``` +""" + + +IMAGE_TEXT_TO_TEXT_GENERATION_SAMPLE = r""" + Example: + + ```python + >>> from PIL import Image + >>> from transformers import AutoProcessor, {model_class} + + >>> model = {model_class}.from_pretrained("{checkpoint}") + >>> processor = AutoProcessor.from_pretrained("{checkpoint}") + + >>> messages = [ + ... {{ + ... "role": "user", "content": [ + ... {{"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"}}, + ... {{"type": "text", "text": "Where is the cat standing?"}}, + ... ] + ... }}, + ... ] + + >>> inputs = processor.apply_chat_template( + ... messages, + ... tokenize=True, + ... return_dict=True, + ... return_tensors="pt", + ... add_generation_prompt=True + ... ) + >>> # Generate + >>> generate_ids = model.generate(**inputs) + >>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0] + ``` +""" + + +PIPELINE_TASKS_TO_SAMPLE_DOCSTRINGS = OrderedDict( + [ + ("text-to-audio-spectrogram", TEXT_TO_AUDIO_SPECTROGRAM_SAMPLE), + ("text-to-audio-waveform", TEXT_TO_AUDIO_WAVEFORM_SAMPLE), + ("automatic-speech-recognition", AUTOMATIC_SPEECH_RECOGNITION_SAMPLE), + ("audio-frame-classification", AUDIO_FRAME_CLASSIFICATION_SAMPLE), + ("audio-classification", AUDIO_CLASSIFICATION_SAMPLE), + ("audio-xvector", AUDIO_XVECTOR_SAMPLE), + ("image-text-to-text", IMAGE_TEXT_TO_TEXT_GENERATION_SAMPLE), + ("depth-estimation", DEPTH_ESTIMATION_SAMPLE), + ("video-classification", VIDEO_CLASSIFICATION_SAMPLE), + ("zero-shot-image-classification", ZERO_SHOT_IMAGE_CLASSIFICATION_SAMPLE), + ("image-classification", IMAGE_CLASSIFICATION_SAMPLE), + ("zero-shot-object-detection", ZERO_SHOT_OBJECT_DETECTION_SAMPLE), + ("object-detection", OBJECT_DETECTION_SAMPLE), + ("image-segmentation", IMAGE_SEGMENTATION_SAMPLE), + ("image-feature-extraction", IMAGE_FEATURE_EXTRACTION_SAMPLE), + ("text-generation", TEXT_GENERATION_SAMPLE), + ("table-question-answering", TABLE_QUESTION_ANSWERING_SAMPLE), + ("document-question-answering", DOCUMENT_QUESTION_ANSWERING_SAMPLE), + ("next-sentence-prediction", NEXT_SENTENCE_PREDICTION_SAMPLE), + ("multiple-choice", MULTIPLE_CHOICE_SAMPLE), + ("text-classification", TEXT_CLASSIFICATION_SAMPLE), + ("token-classification", TOKEN_CLASSIFICATION_SAMPLE), + ("fill-mask", FILL_MASK_SAMPLE), + ("mask-generation", MASK_GENERATION_SAMPLE), + ("pretraining", PRETRAINING_SAMPLE), + ] +) + +# Ordered dict to look for more specialized model mappings first +# before falling back to the more generic ones. +MODELS_TO_PIPELINE = OrderedDict( + [ + # Audio + ("MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES", "text-to-audio-spectrogram"), + ("MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES", "text-to-audio-waveform"), + ("MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES", "automatic-speech-recognition"), + ("MODEL_FOR_CTC_MAPPING_NAMES", "automatic-speech-recognition"), + ("MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES", "audio-frame-classification"), + ("MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES", "audio-classification"), + ("MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES", "audio-xvector"), + # Vision + ("MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES", "image-text-to-text"), + ("MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES", "depth-estimation"), + ("MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES", "video-classification"), + ("MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES", "zero-shot-image-classification"), + ("MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES", "image-classification"), + ("MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES", "zero-shot-object-detection"), + ("MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES", "object-detection"), + ("MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES", "image-segmentation"), + ("MODEL_FOR_IMAGE_MAPPING_NAMES", "image-feature-extraction"), + # Text/tokens + ("MODEL_FOR_CAUSAL_LM_MAPPING_NAMES", "text-generation"), + ("MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES", "table-question-answering"), + ("MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES", "document-question-answering"), + ("MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES", "next-sentence-prediction"), + ("MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES", "multiple-choice"), + ("MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES", "text-classification"), + ("MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES", "token-classification"), + ("MODEL_FOR_MASKED_LM_MAPPING_NAMES", "fill-mask"), + ("MODEL_FOR_MASK_GENERATION_MAPPING_NAMES", "mask-generation"), + ("MODEL_FOR_PRETRAINING_MAPPING_NAMES", "pretraining"), + ] +) + + +def filter_outputs_from_example(docstring, **kwargs): + """ + Removes the lines testing an output with the doctest syntax in a code sample when it's set to `None`. + """ + for key, value in kwargs.items(): + if value is not None: + continue + + doc_key = "{" + key + "}" + docstring = re.sub(rf"\n([^\n]+)\n\s+{doc_key}\n", "\n", docstring) + + return docstring + + +def add_code_sample_docstrings( + *docstr, + processor_class=None, + checkpoint=None, + output_type=None, + config_class=None, + mask="[MASK]", + qa_target_start_index=14, + qa_target_end_index=15, + model_cls=None, + modality=None, + expected_output=None, + expected_loss=None, + real_checkpoint=None, + revision=None, +): + def docstring_decorator(fn): + # model_class defaults to function's class if not specified otherwise + model_class = fn.__qualname__.split(".")[0] if model_cls is None else model_cls + + sample_docstrings = PT_SAMPLE_DOCSTRINGS + + # putting all kwargs for docstrings in a dict to be used + # with the `.format(**doc_kwargs)`. Note that string might + # be formatted with non-existing keys, which is fine. + doc_kwargs = { + "model_class": model_class, + "processor_class": processor_class, + "checkpoint": checkpoint, + "mask": mask, + "qa_target_start_index": qa_target_start_index, + "qa_target_end_index": qa_target_end_index, + "expected_output": expected_output, + "expected_loss": expected_loss, + "real_checkpoint": real_checkpoint, + "fake_checkpoint": checkpoint, + "true": "{true}", # For syntax that conflicts with formatting. + } + + if ("SequenceClassification" in model_class or "AudioClassification" in model_class) and modality == "audio": + code_sample = sample_docstrings["AudioClassification"] + elif "SequenceClassification" in model_class: + code_sample = sample_docstrings["SequenceClassification"] + elif "QuestionAnswering" in model_class: + code_sample = sample_docstrings["QuestionAnswering"] + elif "TokenClassification" in model_class: + code_sample = sample_docstrings["TokenClassification"] + elif "MultipleChoice" in model_class: + code_sample = sample_docstrings["MultipleChoice"] + elif "MaskedLM" in model_class or model_class in ["FlaubertWithLMHeadModel", "XLMWithLMHeadModel"]: + code_sample = sample_docstrings["MaskedLM"] + elif "LMHead" in model_class or "CausalLM" in model_class: + code_sample = sample_docstrings["LMHead"] + elif "CTC" in model_class: + code_sample = sample_docstrings["CTC"] + elif "AudioFrameClassification" in model_class: + code_sample = sample_docstrings["AudioFrameClassification"] + elif "XVector" in model_class and modality == "audio": + code_sample = sample_docstrings["AudioXVector"] + elif "Model" in model_class and modality == "audio": + code_sample = sample_docstrings["SpeechBaseModel"] + elif "Model" in model_class and modality == "vision": + code_sample = sample_docstrings["VisionBaseModel"] + elif "Model" in model_class or "Encoder" in model_class: + code_sample = sample_docstrings["BaseModel"] + elif "ImageClassification" in model_class: + code_sample = sample_docstrings["ImageClassification"] + else: + raise ValueError(f"Docstring can't be built for model {model_class}") + + code_sample = filter_outputs_from_example( + code_sample, expected_output=expected_output, expected_loss=expected_loss + ) + if real_checkpoint is not None: + code_sample = FAKE_MODEL_DISCLAIMER + code_sample + func_doc = (fn.__doc__ or "") + "".join(docstr) + output_doc = "" if output_type is None else _prepare_output_docstrings(output_type, config_class) + built_doc = code_sample.format(**doc_kwargs) + if revision is not None: + if re.match(r"^refs/pr/\\d+", revision): + raise ValueError( + f"The provided revision '{revision}' is incorrect. It should point to" + " a pull request reference on the hub like 'refs/pr/6'" + ) + built_doc = built_doc.replace( + f'from_pretrained("{checkpoint}")', f'from_pretrained("{checkpoint}", revision="{revision}")' + ) + + fn.__doc__ = func_doc + output_doc + built_doc + return fn + + return docstring_decorator + + +def replace_return_docstrings(output_type=None, config_class=None): + def docstring_decorator(fn): + func_doc = fn.__doc__ + lines = func_doc.split("\n") + i = 0 + while i < len(lines) and re.search(r"^\s*Returns?:\s*$", lines[i]) is None: + i += 1 + if i < len(lines): + indent = len(_get_indent(lines[i])) + lines[i] = _prepare_output_docstrings(output_type, config_class, min_indent=indent) + func_doc = "\n".join(lines) + else: + raise ValueError( + f"The function {fn} should have an empty 'Return:' or 'Returns:' in its docstring as placeholder, " + f"current docstring is:\n{func_doc}" + ) + fn.__doc__ = func_doc + return fn + + return docstring_decorator + + +def copy_func(f): + """Returns a copy of a function f.""" + # Based on http://stackoverflow.com/a/6528148/190597 (Glenn Maynard) + g = types.FunctionType(f.__code__, f.__globals__, name=f.__name__, argdefs=f.__defaults__, closure=f.__closure__) + g = cast(types.FunctionType, functools.update_wrapper(g, f)) + g.__kwdefaults__ = f.__kwdefaults__ + return g diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_detectron2_objects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_detectron2_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..22ec32fe30a1b9abbc5d810510d97d5c81082561 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_detectron2_objects.py @@ -0,0 +1,11 @@ +# This file is autogenerated by the command `make fix-copies`, do not edit. +from ..utils import requires_backends + + +class LayoutLMv2Model: + def __init__(self, *args, **kwargs): + requires_backends(self, ["detectron2"]) + + @classmethod + def from_pretrained(cls, *args, **kwargs): + requires_backends(cls, ["detectron2"]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..e6d75a6ec22e90427c972a753a24afd1a780758f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects.py @@ -0,0 +1,23 @@ +# This file is autogenerated by the command `make fix-copies`, do not edit. +from ..utils import DummyObject, requires_backends + + +class Pop2PianoFeatureExtractor(metaclass=DummyObject): + _backends = ["essentia", "librosa", "pretty_midi", "scipy", "torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["essentia", "librosa", "pretty_midi", "scipy", "torch"]) + + +class Pop2PianoTokenizer(metaclass=DummyObject): + _backends = ["essentia", "librosa", "pretty_midi", "scipy", "torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["essentia", "librosa", "pretty_midi", "scipy", "torch"]) + + +class Pop2PianoProcessor(metaclass=DummyObject): + _backends = ["essentia", "librosa", "pretty_midi", "scipy", "torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["essentia", "librosa", "pretty_midi", "scipy", "torch"]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_mistral_common_objects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_mistral_common_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..36cdb01cea4534203b879b8c7f30778cc34fe5ad --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_mistral_common_objects.py @@ -0,0 +1,9 @@ +# This file is autogenerated by the command `make fix-copies`, do not edit. +from ..utils import DummyObject, requires_backends + + +class MistralCommonBackend(metaclass=DummyObject): + _backends = ["mistral-common"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["mistral-common"]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_music_objects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_music_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..89052be47c1d32bac5cbd6fceab183fc1d75d3bf --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_music_objects.py @@ -0,0 +1,16 @@ +# This file is autogenerated by the command `make fix-copies`, do not edit. +from ..utils import DummyObject, requires_backends + + +class Pop2PianoFeatureExtractor(metaclass=DummyObject): + _backends = ["music"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["music"]) + + +class Pop2PianoTokenizer(metaclass=DummyObject): + _backends = ["music"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["music"]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_pt_objects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_pt_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..191783b25df3cc8e9d9bed4a8101bf025c6df2a3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_pt_objects.py @@ -0,0 +1,488 @@ +# This file is autogenerated by the command `make fix-copies`, do not edit. +from ..utils import DummyObject, requires_backends + + +class Cache(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DynamicCache(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EncoderDecoderCache(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class QuantizedCache(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class StaticCache(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GlueDataset(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GlueDataTrainingArguments(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SquadDataset(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SquadDataTrainingArguments(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class AlternatingCodebooksLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BayesianDetectorConfig(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class BayesianDetectorModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ClassifierFreeGuidanceLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EncoderNoRepeatNGramLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EncoderRepetitionPenaltyLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EosTokenCriteria(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EpsilonLogitsWarper(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class EtaLogitsWarper(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ExponentialDecayLengthPenalty(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ForcedBOSTokenLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class ForcedEOSTokenLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class GenerationMixin(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class InfNanRemoveLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LogitNormalization(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class LogitsProcessorList(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MaxLengthCriteria(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MaxTimeCriteria(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MinLengthLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MinNewTokensLengthLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class MinPLogitsWarper(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NoBadWordsLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class NoRepeatNGramLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PrefixConstrainedLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class RepetitionPenaltyLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SequenceBiasLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class StoppingCriteria(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class StoppingCriteriaList(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class StopStringCriteria(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SuppressTokensAtBeginLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SuppressTokensLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SynthIDTextWatermarkDetector(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SynthIDTextWatermarkingConfig(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class SynthIDTextWatermarkLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TemperatureLogitsWarper(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TopKLogitsWarper(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TopPLogitsWarper(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TypicalLogitsWarper(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class UnbatchedClassifierFreeGuidanceLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class WatermarkDetector(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class WatermarkLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class WhisperTimeStampLogitsProcessor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class TorchExportableModuleWithStaticCache(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def convert_and_export_with_cache(*args, **kwargs): + requires_backends(convert_and_export_with_cache, ["torch"]) + + +class AttentionMaskInterface(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def model_addition_debugger_context(*args, **kwargs): + requires_backends(model_addition_debugger_context, ["torch"]) + + +class GradientCheckpointingLayer(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +ROPE_INIT_FUNCTIONS = None + + +def dynamic_rope_update(*args, **kwargs): + requires_backends(dynamic_rope_update, ["torch"]) + + +class AttentionInterface(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class PreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class Adafactor(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def get_constant_schedule(*args, **kwargs): + requires_backends(get_constant_schedule, ["torch"]) + + +def get_constant_schedule_with_warmup(*args, **kwargs): + requires_backends(get_constant_schedule_with_warmup, ["torch"]) + + +def get_cosine_schedule_with_warmup(*args, **kwargs): + requires_backends(get_cosine_schedule_with_warmup, ["torch"]) + + +def get_cosine_with_hard_restarts_schedule_with_warmup(*args, **kwargs): + requires_backends(get_cosine_with_hard_restarts_schedule_with_warmup, ["torch"]) + + +def get_inverse_sqrt_schedule(*args, **kwargs): + requires_backends(get_inverse_sqrt_schedule, ["torch"]) + + +def get_linear_schedule_with_warmup(*args, **kwargs): + requires_backends(get_linear_schedule_with_warmup, ["torch"]) + + +def get_polynomial_decay_schedule_with_warmup(*args, **kwargs): + requires_backends(get_polynomial_decay_schedule_with_warmup, ["torch"]) + + +def get_scheduler(*args, **kwargs): + requires_backends(get_scheduler, ["torch"]) + + +def get_wsd_schedule(*args, **kwargs): + requires_backends(get_wsd_schedule, ["torch"]) + + +class Conv1D(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def apply_chunking_to_forward(*args, **kwargs): + requires_backends(apply_chunking_to_forward, ["torch"]) + + +class Trainer(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +def torch_distributed_zero_first(*args, **kwargs): + requires_backends(torch_distributed_zero_first, ["torch"]) + + +class Seq2SeqTrainer(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_sentencepiece_and_tokenizers_objects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_sentencepiece_and_tokenizers_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..38775330a81d91030f000e58c0e6035bba1c0f31 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_sentencepiece_and_tokenizers_objects.py @@ -0,0 +1,9 @@ +# This file is autogenerated by the command `make fix-copies`, do not edit. +from ..utils import DummyObject, requires_backends + + +SLOW_TO_FAST_CONVERTERS = None + + +def convert_slow_tokenizer(*args, **kwargs): + requires_backends(convert_slow_tokenizer, ["sentencepiece", "tokenizers"]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_speech_objects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_speech_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..0bf08ebea42b4595ae1f8bbc2afcddf0630dcf4b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_speech_objects.py @@ -0,0 +1,16 @@ +# This file is autogenerated by the command `make fix-copies`, do not edit. +from ..utils import DummyObject, requires_backends + + +class ASTFeatureExtractor(metaclass=DummyObject): + _backends = ["speech"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["speech"]) + + +class Speech2TextFeatureExtractor(metaclass=DummyObject): + _backends = ["speech"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["speech"]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_timm_and_torchvision_objects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_timm_and_torchvision_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..8b67b5dac58db13278706e0838aebbe495a9d2fc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_timm_and_torchvision_objects.py @@ -0,0 +1,9 @@ +# This file is autogenerated by the command `make fix-copies`, do not edit. +from ..utils import DummyObject, requires_backends + + +class TimmWrapperImageProcessor(metaclass=DummyObject): + _backends = ["timm", "torchvision"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["timm", "torchvision"]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_tokenizers_objects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_tokenizers_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..2e592f28570fedf4870d185e92d504fa82f6b545 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_tokenizers_objects.py @@ -0,0 +1,9 @@ +# This file is autogenerated by the command `make fix-copies`, do not edit. +from ..utils import DummyObject, requires_backends + + +class PreTrainedTokenizerFast(metaclass=DummyObject): + _backends = ["tokenizers"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["tokenizers"]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_torchaudio_objects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_torchaudio_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..f7aea4a70207a2ce26385868b4437ea478c9efc5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_torchaudio_objects.py @@ -0,0 +1,30 @@ +# This file is autogenerated by the command `make fix-copies`, do not edit. +from ..utils import DummyObject, requires_backends + + +class GraniteSpeechFeatureExtractor(metaclass=DummyObject): + _backends = ["torchaudio"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torchaudio"]) + + +class GraniteSpeechProcessor(metaclass=DummyObject): + _backends = ["torchaudio"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torchaudio"]) + + +class MusicgenMelodyFeatureExtractor(metaclass=DummyObject): + _backends = ["torchaudio"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torchaudio"]) + + +class MusicgenMelodyProcessor(metaclass=DummyObject): + _backends = ["torchaudio"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torchaudio"]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_torchvision_objects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_torchvision_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..8d19003699b01ffc4027c1b2039894760729fb5b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_torchvision_objects.py @@ -0,0 +1,16 @@ +# This file is autogenerated by the command `make fix-copies`, do not edit. +from ..utils import DummyObject, requires_backends + + +class TorchvisionBackend(metaclass=DummyObject): + _backends = ["torchvision"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torchvision"]) + + +class BaseVideoProcessor(metaclass=DummyObject): + _backends = ["torchvision"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torchvision"]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_vision_objects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_vision_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..89aa3ad35872491b96bc102250d82425a4fc7766 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_vision_objects.py @@ -0,0 +1,23 @@ +# This file is autogenerated by the command `make fix-copies`, do not edit. +from ..utils import DummyObject, requires_backends + + +class ImageProcessingMixin(metaclass=DummyObject): + _backends = ["vision"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["vision"]) + + +class BaseImageProcessor(metaclass=DummyObject): + _backends = ["vision"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["vision"]) + + +class ImageFeatureExtractionMixin(metaclass=DummyObject): + _backends = ["vision"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["vision"]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/generic.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/generic.py new file mode 100644 index 0000000000000000000000000000000000000000..c6b5960f08493080cd568951edbbcac3635959e8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/generic.py @@ -0,0 +1,1087 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# 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. +""" +Generic utilities +""" + +from __future__ import annotations + +import inspect +import json +import os +import random +import re +import time +import warnings +from collections import OrderedDict, UserDict +from collections.abc import Callable, Iterable, MutableMapping +from contextlib import AbstractContextManager, ExitStack, nullcontext +from dataclasses import fields, is_dataclass +from enum import Enum +from functools import partial, wraps +from typing import TYPE_CHECKING, Any, TypedDict + +import numpy as np + +from ..utils import logging +from .import_utils import is_mlx_available, is_torch_available, is_torch_fx_proxy + + +if TYPE_CHECKING: + import torch + from torch import nn + + +logger = logging.get_logger(__name__) + + +_is_torch_available = False +if is_torch_available(): + _is_torch_available = True + +_registered_model_output_types: set[type[Any]] = set() + + +def _register_model_output_pytree_node(output_type: type[ModelOutput]) -> None: + if not _is_torch_available: + return + import torch + + # AMD CI runs PyTorch 2.8.0+rocm which does not support tracing `set.__contains__` + # through TorchDynamo. Skip registration during compilation since the pytree node + # is already registered from the preceding eager run. + if torch.compiler.is_compiling(): + return + if output_type in _registered_model_output_types: + return + + import torch.utils._pytree as torch_pytree + + torch_pytree.register_pytree_node( + output_type, + _model_output_flatten, + partial(_model_output_unflatten, output_type=output_type), + serialized_type_name=f"{output_type.__module__}.{output_type.__name__}", + ) + _registered_model_output_types.add(output_type) + + +# required for @can_return_tuple decorator to work with torchdynamo +_is_mlx_available = False +if is_mlx_available(): + _is_mlx_available = True + + +# vendored from distutils.util +def strtobool(val) -> int: + """Convert a string representation of truth to true (1) or false (0). + + True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. + Raises ValueError if 'val' is anything else. + """ + val = val.lower() + if val in {"y", "yes", "t", "true", "on", "1"}: + return 1 + if val in {"n", "no", "f", "false", "off", "0"}: + return 0 + raise ValueError(f"invalid truth value {val!r}") + + +def infer_framework_from_repr(x) -> str | None: + """ + Tries to guess the framework of an object `x` from its repr (brittle but will help in `is_tensor` to try the + frameworks in a smart order, without the need to import the frameworks). + """ + representation = str(type(x)) + if representation.startswith(" bool: + """ + Tests if `x` is a `torch.Tensor`, `np.ndarray` or `mlx.array` in the order defined by `infer_framework_from_repr` + """ + # This gives us a smart order to test the frameworks with the corresponding tests. + framework_to_test_func = _get_frameworks_and_test_func(x) + for test_func in framework_to_test_func.values(): + if test_func(x): + return True + + # Tracers + if is_torch_fx_proxy(x): + return True + + return False + + +def is_numpy_array(x) -> bool: + """ + Tests if `x` is a numpy array or not. + """ + return isinstance(x, np.ndarray) + + +def is_torch_tensor(x) -> bool: + """ + Tests if `x` is a torch tensor or not. Safe to call even if torch is not installed. + """ + if not _is_torch_available: + return False + + import torch + + return isinstance(x, torch.Tensor) + + +def is_torch_device(x) -> bool: + """ + Tests if `x` is a torch device or not. Safe to call even if torch is not installed. + """ + if not _is_torch_available: + return False + + import torch + + return isinstance(x, torch.device) + + +def is_torch_dtype(x) -> bool: + """ + Tests if `x` is a torch dtype or not. Safe to call even if torch is not installed. + """ + if not _is_torch_available: + return False + + import torch + + if isinstance(x, str): + if hasattr(torch, x): + x = getattr(torch, x) + else: + return False + return isinstance(x, torch.dtype) + + +def _is_tensor_or_array_like(value): + """ + Check if a value is array-like (includes ragged arrays) + """ + if is_numpy_array(value): + return True + if is_torch_tensor(value): + return True + if isinstance(value, (int, float, bool, np.number)): + return True + + if isinstance(value, (list, tuple)): + if len(value) == 0: + # consider empty list or nested list as array-like + return True + return _is_tensor_or_array_like(value[0]) + + return False + + +def maybe_autocast( + device_type: str, + dtype: torch.dtype | None = None, + enabled: bool = True, + cache_enabled: bool | None = None, +): + """ + Context manager that only autocasts if: + + - `autocast` is already enabled in this context + - Or this call to `maybe_autocast` has `enabled=True` + + This prevents `autocast` being added to the graph when it is effectively a no-op. + Which makes graph splitting in `torch.compile` more flexible as it removes the + requirement that partition IDs be monotonically increasing. + """ + if not _is_torch_available: + raise ImportError("`maybe_autocast` requires PyTorch to be installed.") + + import torch + + if device_type == "meta": + return nullcontext() + if torch.is_autocast_enabled(device_type) or enabled: + return torch.autocast(device_type, dtype=dtype, enabled=enabled, cache_enabled=cache_enabled) + else: + return nullcontext() + + +def _is_mlx(x): + import mlx.core as mx + + return isinstance(x, mx.array) + + +def is_mlx_array(x) -> bool: + """ + Tests if `x` is a mlx array or not. Safe to call even when mlx is not installed. + """ + return False if not _is_mlx_available else _is_mlx(x) + + +def is_flash_attention_requested( + config=None, requested_attention_implementation: str | None = None, version: int | None = None +) -> bool: + """ + Checks whether some flavor of flash attention is requested or not. Optionally, checks for a specific version of + flash attention. + + This is checked against one of the two arguments, i.e. either the `config` or the directly passed value + `requested_attention_implementation`. Otherwise, an error will be raised (ambiguity). + + The different versions of flash attention are usually + - Implementations based on the original flash attention repo: https://github.com/Dao-AILab/flash-attention + - Kernels implementations such as: https://huggingface.co/kernels-community/vllm-flash-attn3 + """ + if config is not None and requested_attention_implementation is not None: + raise ValueError( + "Requested attention implementation is ambiguous: " + "Please pass either the config or the name of the attention implementation, not both." + ) + + if config is not None: + checked_attention_implementation = config._attn_implementation + else: + checked_attention_implementation = requested_attention_implementation + + # theoretically can happen, equivalent to default implementation (sdpa/eager) + if checked_attention_implementation is None: + return False + + # If a specific version is requested, look for a pattern of type "flash...{version}" + if version is not None: + return re.match(r".*flash.*" + str(version), checked_attention_implementation) is not None + # Otherwise, just check "flash" is in the attention implementation + return "flash" in checked_attention_implementation + + +def split_attention_implementation(implementation: str | None) -> tuple[bool, str | None]: + """ + Split the optional `paged|` prefix from an attention implementation string. + + Note that `None` means using the default attention implementation, which is either torch's native `sdpa` or `eager` (if `sdpa` is not implemented for that model). + """ + if implementation is None: + return False, None + + is_paged = implementation.startswith("paged|") + return is_paged, implementation.removeprefix("paged|") + + +def to_py_obj(obj): + """ + Convert a PyTorch tensor, Numpy array or python list to a python list. + """ + if isinstance(obj, (int, float)): + return obj + elif isinstance(obj, (dict, UserDict)): + return {k: to_py_obj(v) for k, v in obj.items()} + elif isinstance(obj, (list, tuple)): + # Only convert directly if all elements are numeric scalars + if all(isinstance(x, (int, float, np.number)) for x in obj): + return list(obj) + + # Otherwise recurse element-wise + return [to_py_obj(o) for o in obj] + + framework_to_py_obj = { + "pt": lambda obj: obj.tolist(), + "np": lambda obj: obj.tolist(), + } + + # This gives us a smart order to test the frameworks with the corresponding tests. + framework_to_test_func = _get_frameworks_and_test_func(obj) + for framework, test_func in framework_to_test_func.items(): + if test_func(obj): + return framework_to_py_obj[framework](obj) + + # tolist also works on 0d np arrays + if isinstance(obj, np.number): + return obj.tolist() + else: + return obj + + +def to_numpy(obj): + """ + Convert a PyTorch tensor, Numpy array or python list to a Numpy array. + """ + + framework_to_numpy = { + "pt": lambda obj: obj.detach().cpu().numpy(), + "np": lambda obj: obj, + } + + if isinstance(obj, (dict, UserDict)): + return {k: to_numpy(v) for k, v in obj.items()} + elif isinstance(obj, (list, tuple)): + return np.array(obj) + + # This gives us a smart order to test the frameworks with the corresponding tests. + framework_to_test_func = _get_frameworks_and_test_func(obj) + for framework, test_func in framework_to_test_func.items(): + if test_func(obj): + return framework_to_numpy[framework](obj) + + return obj + + +def safe_load_json_file(json_file: str): + "A helper to load safe config files and raise a proper error message if it wasn't serialized correctly" + try: + with open(json_file, encoding="utf-8") as reader: + text = reader.read() + config_dict = json.loads(text) + except json.JSONDecodeError: + raise OSError(f"It looks like the config file at '{json_file}' is not a valid JSON file.") + return config_dict + + +class ModelOutput(OrderedDict): + """ + Base class for all model outputs as dataclass. Has a `__getitem__` that allows indexing by integer or slice (like a + tuple) or strings (like a dictionary) that will ignore the `None` attributes. Otherwise behaves like a regular + python dictionary. + + + + You can't unpack a `ModelOutput` directly. Use the [`~utils.ModelOutput.to_tuple`] method to convert it to a tuple + before. + + + """ + + def __init_subclass__(cls) -> None: + """Register subclasses as pytree nodes. + + This is necessary to synchronize gradients when using `torch.nn.parallel.DistributedDataParallel` with + `static_graph=True` with modules that output `ModelOutput` subclasses. + """ + _register_model_output_pytree_node(cls) + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + _register_model_output_pytree_node(type(self)) + + # Subclasses of ModelOutput must use the @dataclass decorator + # This check is done in __init__ because the @dataclass decorator operates after __init_subclass__ + # issubclass() would return True for issubclass(ModelOutput, ModelOutput) when False is needed + # Just need to check that the current class is not ModelOutput + is_modeloutput_subclass = self.__class__ != ModelOutput + + if is_modeloutput_subclass and not is_dataclass(self): + raise TypeError( + f"{self.__module__}.{self.__class__.__name__} is not a dataclass." + " This is a subclass of ModelOutput and so must use the @dataclass decorator." + ) + + def __post_init__(self): + """Check the ModelOutput dataclass. + + Only occurs if @dataclass decorator has been used. + """ + _register_model_output_pytree_node(type(self)) + class_fields = fields(self) + + # Safety and consistency checks + if not len(class_fields): + raise ValueError(f"{self.__class__.__name__} has no fields.") + if not all(field.default is None for field in class_fields[1:]): + raise ValueError(f"{self.__class__.__name__} should not have more than one required field.") + + first_field = getattr(self, class_fields[0].name) + other_fields_are_none = all(getattr(self, field.name) is None for field in class_fields[1:]) + + if other_fields_are_none and not is_tensor(first_field): + if isinstance(first_field, dict): + iterator = first_field.items() + first_field_iterator = True + else: + try: + iterator = iter(first_field) + first_field_iterator = True + except TypeError: + first_field_iterator = False + + # if we provided an iterator as first field and the iterator is a (key, value) iterator + # set the associated fields + if first_field_iterator: + # reset first field to None and remove it from the internal dictionary + setattr(self, class_fields[0].name, None) + super().__delitem__(class_fields[0].name) + for idx, element in enumerate(iterator): + if not isinstance(element, (list, tuple)) or len(element) != 2 or not isinstance(element[0], str): + if idx == 0: + # If we do not have an iterator of key/values, set it as attribute + self[class_fields[0].name] = first_field + else: + # If we have a mixed iterator, raise an error + raise ValueError( + f"Cannot set key/value for {element}. It needs to be a tuple (key, value)." + ) + break + setattr(self, element[0], element[1]) + if element[1] is not None: + self[element[0]] = element[1] + elif first_field is not None: + self[class_fields[0].name] = first_field + else: + for field in class_fields: + v = getattr(self, field.name) + if v is not None: + self[field.name] = v + + def __delitem__(self, *args, **kwargs): + raise Exception(f"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.") + + def setdefault(self, *args, **kwargs): + raise Exception(f"You cannot use ``setdefault`` on a {self.__class__.__name__} instance.") + + def pop(self, *args, **kwargs): + raise Exception(f"You cannot use ``pop`` on a {self.__class__.__name__} instance.") + + def update(self, *args, **kwargs): + raise Exception(f"You cannot use ``update`` on a {self.__class__.__name__} instance.") + + def __getitem__(self, k): + if isinstance(k, str): + inner_dict = dict(self.items()) + return inner_dict[k] + else: + return self.to_tuple()[k] + + def __setattr__(self, name, value): + field_names = {field.name for field in fields(self)} + if name in field_names and value is not None: + # Don't call self.__setitem__ to avoid recursion errors + super().__setitem__(name, value) + super().__setattr__(name, value) + + def __setitem__(self, key, value): + # Will raise a KeyException if needed + super().__setitem__(key, value) + # Don't call self.__setattr__ to avoid recursion errors + super().__setattr__(key, value) + + def __reduce__(self): + if not is_dataclass(self): + return super().__reduce__() + callable, _args, *remaining = super().__reduce__() + args = tuple(getattr(self, field.name) for field in fields(self)) + return callable, args, *remaining + + def to_tuple(self) -> tuple: + """ + Convert self to a tuple containing all the attributes/keys that are not `None`. + """ + return tuple(self[k] for k in self.keys()) + + +def _model_output_flatten(output: ModelOutput) -> tuple[list[Any], list[str]]: + return list(output.values()), list(output.keys()) + + +def _model_output_unflatten( + values: Iterable[Any], + context: list[str], + output_type: type[ModelOutput] | None = None, +) -> ModelOutput: + return output_type(**dict(zip(context, values))) + + +class ExplicitEnum(str, Enum): + """ + Enum with more explicit error message for missing values. + """ + + @classmethod + def _missing_(cls, value): + raise ValueError( + f"{value} is not a valid {cls.__name__}, please select one of {list(cls._value2member_map_.keys())}" + ) + + +class PaddingStrategy(ExplicitEnum): + """ + Possible values for the `padding` argument in [`PreTrainedTokenizerBase.__call__`]. Useful for tab-completion in an + IDE. + """ + + LONGEST = "longest" + MAX_LENGTH = "max_length" + DO_NOT_PAD = "do_not_pad" + + +class TensorType(ExplicitEnum): + """ + Possible values for the `return_tensors` argument in [`PreTrainedTokenizerBase.__call__`]. Useful for + tab-completion in an IDE. + """ + + PYTORCH = "pt" + NUMPY = "np" + MLX = "mlx" + + +class ContextManagers: + """ + Wrapper for `contextlib.ExitStack` which enters a collection of context managers. Adaptation of `ContextManagers` + in the `fastcore` library. + """ + + def __init__(self, context_managers: list[AbstractContextManager]): + self.context_managers = context_managers + self.stack = ExitStack() + + def __enter__(self): + for context_manager in self.context_managers: + self.stack.enter_context(context_manager) + + def __exit__(self, *args, **kwargs): + self.stack.__exit__(*args, **kwargs) + + +def can_return_loss(model_class): + """ + Check if a given model can return loss. + + Args: + model_class (`type`): The class of the model. + """ + signature = inspect.signature(model_class.forward) + + for p in signature.parameters: + if p == "return_loss" and signature.parameters[p].default is True: + return True + + return False + + +def find_labels(model_class): + """ + Find the labels used by a given model. + + Args: + model_class (`type`): The class of the model. + """ + model_name = model_class.__name__ + signature = inspect.signature(model_class.forward) + + if "QuestionAnswering" in model_name: + return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")] + else: + return [p for p in signature.parameters if "label" in p] + + +def flatten_dict(d: MutableMapping, parent_key: str = "", delimiter: str = "."): + """Flatten a nested dict into a single level dict.""" + + def _flatten_dict(d, parent_key="", delimiter="."): + for k, v in d.items(): + key = str(parent_key) + delimiter + str(k) if parent_key else k + if v and isinstance(v, MutableMapping): + yield from flatten_dict(v, key, delimiter=delimiter).items() + else: + yield key, v + + return dict(_flatten_dict(d, parent_key, delimiter)) + + +def transpose(array, axes=None): + """ + Framework-agnostic version of transpose operation. + """ + if is_numpy_array(array): + return np.transpose(array, axes=axes) + elif is_torch_tensor(array): + return array.T if axes is None else array.permute(*axes) + else: + raise ValueError(f"Type not supported for transpose: {type(array)}.") + + +def reshape(array, newshape): + """ + Framework-agnostic version of reshape operation. + """ + if is_numpy_array(array): + return np.reshape(array, newshape) + elif is_torch_tensor(array): + return array.reshape(*newshape) + else: + raise ValueError(f"Type not supported for reshape: {type(array)}.") + + +def squeeze(array, axis=None): + """ + Framework-agnostic version of squeeze operation. + """ + if is_numpy_array(array): + return np.squeeze(array, axis=axis) + elif is_torch_tensor(array): + return array.squeeze() if axis is None else array.squeeze(dim=axis) + else: + raise ValueError(f"Type not supported for squeeze: {type(array)}.") + + +def expand_dims(array, axis): + """ + Framework-agnostic version of expand_dims operation. + """ + if is_numpy_array(array): + return np.expand_dims(array, axis) + elif is_torch_tensor(array): + return array.unsqueeze(dim=axis) + else: + raise ValueError(f"Type not supported for expand_dims: {type(array)}.") + + +def tensor_size(array): + """ + Framework-agnostic version of size operation. + """ + if is_numpy_array(array): + return np.size(array) + elif is_torch_tensor(array): + return array.numel() + else: + raise ValueError(f"Type not supported for tensor_size: {type(array)}.") + + +def torch_int(x): + """ + Casts an input to a torch int64 tensor if we are in a tracing context, otherwise to a Python int. + """ + if not _is_torch_available: + return int(x) + + import torch + + return x.to(torch.int64) if torch.jit.is_tracing() and isinstance(x, torch.Tensor) else int(x) + + +def torch_float(x): + """ + Casts an input to a torch float32 tensor if we are in a tracing context, otherwise to a Python float. + """ + if not _is_torch_available: + return int(x) + + import torch + + return x.to(torch.float32) if torch.jit.is_tracing() and isinstance(x, torch.Tensor) else int(x) + + +def filter_out_non_signature_kwargs(extra: list | None = None): + """ + Decorator to filter out named arguments that are not in the function signature. + + This decorator ensures that only the keyword arguments that match the function's signature, or are specified in the + `extra` list, are passed to the function. Any additional keyword arguments are filtered out and a warning is issued. + + Parameters: + extra (`Optional[list]`, *optional*): + A list of extra keyword argument names that are allowed even if they are not in the function's signature. + + Returns: + Callable: + A decorator that wraps the function and filters out invalid keyword arguments. + + Example usage: + + ```python + @filter_out_non_signature_kwargs(extra=["allowed_extra_arg"]) + def my_function(arg1, arg2, **kwargs): + print(arg1, arg2, kwargs) + + my_function(arg1=1, arg2=2, allowed_extra_arg=3, invalid_arg=4) + # This will print: 1 2 {"allowed_extra_arg": 3} + # And issue a warning: "The following named arguments are not valid for `my_function` and were ignored: 'invalid_arg'" + ``` + """ + extra = extra or [] + extra_params_to_pass = set(extra) + + def decorator(func): + sig = inspect.signature(func) + function_named_args = set(sig.parameters.keys()) + valid_kwargs_to_pass = function_named_args.union(extra_params_to_pass) + + # Required for better warning message + is_instance_method = "self" in function_named_args + is_class_method = "cls" in function_named_args + + # Mark function as decorated + func._filter_out_non_signature_kwargs = True + + @wraps(func) + def wrapper(*args, **kwargs): + valid_kwargs = {} + invalid_kwargs = {} + + for k, v in kwargs.items(): + if k in valid_kwargs_to_pass: + valid_kwargs[k] = v + else: + invalid_kwargs[k] = v + + if invalid_kwargs: + invalid_kwargs_names = [f"'{k}'" for k in invalid_kwargs] + invalid_kwargs_names = ", ".join(invalid_kwargs_names) + + # Get the class name for better warning message + if is_instance_method: + cls_prefix = args[0].__class__.__name__ + "." + elif is_class_method: + cls_prefix = args[0].__name__ + "." + else: + cls_prefix = "" + + warnings.warn( + f"The following named arguments are not valid for `{cls_prefix}{func.__name__}`" + f" and were ignored: {invalid_kwargs_names}", + UserWarning, + stacklevel=2, + ) + + return func(*args, **valid_kwargs) + + return wrapper + + return decorator + + +class TransformersKwargs(TypedDict, total=False): + """ + Keyword arguments to be passed to the forward pass of a `PreTrainedModel`. + + Attributes: + num_items_in_batch (`Optional[torch.Tensor]`, *optional*): + Number of items in the batch. It is recommended to pass it when you are doing gradient accumulation. + output_hidden_states (`Optional[bool]`, *optional*): + Most of the models support outputting all hidden states computed during the forward pass. + output_attentions (`Optional[bool]`, *optional*): + Turn this on to return the intermediary attention scores. + output_router_logits (`Optional[bool]`, *optional*): + For MoE models, this allows returning the router logits to compute the loss. + cu_seq_lens_q (`torch.LongTensor`, *optional*) + Gets cumulative sequence length for query state. + cu_seq_lens_k (`torch.LongTensor`, *optional*) + Gets cumulative sequence length for key state. + max_length_q (`int`, *optional*): + Maximum sequence length for query state. + max_length_k (`int`, *optional*): + Maximum sequence length for key state. + position_ids (`torch.LongTensor`, *optional*) + Indices of positions of each input sequence tokens. + is_causal (`bool`, *optional*) + Can be set to False to enable bi-directional attention, i.e. use decoder Attention modules as encoders. + """ + + num_items_in_batch: torch.Tensor | None + output_hidden_states: bool | None + output_attentions: bool | None + output_router_logits: bool | None + cu_seq_lens_q: torch.LongTensor | None + cu_seq_lens_k: torch.LongTensor | None + max_length_q: int | None + max_length_k: int | None + position_ids: torch.LongTensor | None + is_causal: bool | None + + +def is_timm_config_dict(config_dict: dict[str, Any]) -> bool: + """Checks whether a config dict is a timm config dict.""" + return "pretrained_cfg" in config_dict + + +def is_timm_local_checkpoint(pretrained_model_path: str) -> bool: + """ + Checks whether a checkpoint is a timm model checkpoint. + """ + if pretrained_model_path is None: + return False + + # in case it's Path, not str + pretrained_model_path = str(pretrained_model_path) + + is_file = os.path.isfile(pretrained_model_path) + is_dir = os.path.isdir(pretrained_model_path) + + # pretrained_model_path is a file + if is_file and pretrained_model_path.endswith(".json"): + with open(pretrained_model_path) as f: + config_dict = json.load(f) + return is_timm_config_dict(config_dict) + + # pretrained_model_path is a directory with a config.json + if is_dir and os.path.exists(os.path.join(pretrained_model_path, "config.json")): + with open(os.path.join(pretrained_model_path, "config.json")) as f: + config_dict = json.load(f) + return is_timm_config_dict(config_dict) + + return False + + +def set_attribute_for_modules(module: nn.Module, key: str, value: Any): + """ + Set a value to a module and all submodules. + """ + setattr(module, key, value) + for submodule in module.children(): + set_attribute_for_modules(submodule, key, value) + + +def del_attribute_from_modules(module: nn.Module, key: str): + """ + Delete a value from a module and all submodules. + """ + # because we might remove it previously in case it's a shared module, e.g. activation function + if hasattr(module, key): + delattr(module, key) + + for submodule in module.children(): + del_attribute_from_modules(submodule, key) + + +def can_return_tuple(func): + """ + Decorator to wrap model method, to call output.to_tuple() if return_dict=False passed as a kwarg or + return_dict=False is set in the config. + + Note: + output.to_tuple() convert output to tuple skipping all `None` values. + """ + + @wraps(func) + def wrapper(self, *args, **kwargs): + return_dict = self.config.return_dict if hasattr(self, "config") else True + return_dict_passed = kwargs.pop("return_dict", return_dict) + if return_dict_passed is not None: + return_dict = return_dict_passed + output = func(self, *args, **kwargs) + if not return_dict and not isinstance(output, tuple): + output = output.to_tuple() + return output + + return wrapper + + +def merge_with_config_defaults(func): + """ + Decorator using config field (if they exist) as default value for some args and kwargs. Precedence is always + given to the args/kwargs that are explicitly passed. + """ + + @wraps(func) + def wrapper(self, *args, **kwargs): + args_with_config_defaults = [ + "use_cache", + "vision_feature_layer", + "vision_feature_select_strategy", + "vision_aspect_ratio", + ] + for arg_name in args_with_config_defaults: + arg_index = None + if arg_name in func.__code__.co_varnames: + arg_index = func.__code__.co_varnames.index(arg_name) - 1 # -1 for self + + if arg_index is not None and len(args) > arg_index and args[arg_index] is not None: + arg_value = args[arg_index] + elif kwargs.get(arg_name) is not None: + arg_value = kwargs[arg_name] + else: + arg_value = getattr(self.config, arg_name, None) + + if arg_value is not None: + # Arg-specific handling + if arg_name == "use_cache": + if getattr(self, "gradient_checkpointing", False) and self.training and arg_value: + logger.warning_once( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`." + ) + arg_value = False + elif arg_name == "vision_feature_select_strategy": + valid_strategies = ["default", "full"] + if arg_value not in valid_strategies: + raise ValueError( + f"`Unexpected select feature strategy: {arg_value}. Please select from {valid_strategies}." + ) + + if arg_index is not None and len(args) > arg_index: + args = list(args) + args[arg_index] = arg_value + args = tuple(args) + else: + kwargs[arg_name] = arg_value + + # Maybe temporarily overwrite config value to create the correct mask - kwarg takes precedence + is_causal = kwargs.get("is_causal", getattr(self.config, "is_causal", None)) + if is_causal is not None: + is_causal_in_config = hasattr(self.config, "is_causal") + if is_causal_in_config: + is_causal_original_value = self.config.is_causal + # Set it to both config and kwargs (it's needed in both, and can come from only 1 of the sources) + self.config.is_causal = is_causal + kwargs["is_causal"] = is_causal + + # Call the original forward with the updated kwargs/config + try: + if kwargs.get("debug_io", False): + from ..model_debugging_utils import model_addition_debugger_context + + with model_addition_debugger_context( + self, kwargs.get("debug_io_dir", "model_debug"), kwargs.get("prune_layers") + ): + output = func(self, *args, **kwargs) + else: + output = func(self, *args, **kwargs) + # Restore original config value + finally: + if is_causal is not None: + if is_causal_in_config: + self.config.is_causal = is_causal_original_value + else: + del self.config.is_causal + + return output + + return wrapper + + +# bc for check_model_inputs: + + +def check_model_inputs(func): + logger.warning_once("The `check_model_inputs` decorator is deprecated in favor of `merge_with_config_defaults`.") + return merge_with_config_defaults(func) + + +class GeneralInterface(MutableMapping): + """ + Dict-like object keeping track of a class-wide mapping, as well as a local one. Allows to have library-wide + modifications through the class mapping, as well as local modifications in a single file with the local mapping. + """ + + # Class instance object, so that a call to `register` can be reflected into all other files correctly, even if + # a new instance is created (in order to locally override a given function) + _global_mapping = {} + + def __init__(self): + self._local_mapping = {} + + def __getitem__(self, key): + # First check if instance has a local override + if key in self._local_mapping: + return self._local_mapping[key] + return self._global_mapping[key] + + def __setitem__(self, key, value): + # Allow local update of the default functions without impacting other instances + self._local_mapping.update({key: value}) + + def __delitem__(self, key): + del self._local_mapping[key] + + def __iter__(self): + # Ensure we use all keys, with the overwritten ones on top + return iter({**self._global_mapping, **self._local_mapping}) + + def __len__(self): + return len(self._global_mapping.keys() | self._local_mapping.keys()) + + @classmethod + def register(cls, key: str, value: Callable): + cls._global_mapping.update({key: value}) + + def valid_keys(self) -> list[str]: + return list(self.keys()) + + +def retry( + max_retries=5, + initial_delay=1.0, + max_delay=30.0, + jitter=True, + exceptions=(Exception,), +): + """ + Decorator that retries a function call with exponential backoff. + + Args: + max_retries (`int`, *optional*, defaults to 5): + Maximum number of retry attempts. + initial_delay (`float`, *optional*, defaults to 1.0): + Initial delay in seconds before the first retry. + max_delay (`float`, *optional*, defaults to 30.0): + Maximum delay in seconds between retries. + jitter (`bool`, *optional*, defaults to `True`): + Whether to add random jitter to the delay. + exceptions (`tuple`, *optional*, defaults to `(Exception,)`): + Tuple of exception types to catch and retry on. + """ + + def decorator(func): + @wraps(func) + def wrapper(*args, **kwargs): + delay = initial_delay + + for attempt in range(1, max_retries + 1): + try: + return func(*args, **kwargs) + except exceptions as exc: + if attempt == max_retries: + raise + + sleep_for = min(delay, max_delay) + if jitter: + sleep_for *= random.uniform(0.8, 1.2) + + logger.info( + f"[{func.__name__}] attempt {attempt}/{max_retries} failed: {exc}\n" + f"Retrying in {sleep_for:.1f}s..." + ) + time.sleep(sleep_for) + delay = min(delay * 2, max_delay) + + return wrapper + + return decorator diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/hp_naming.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/hp_naming.py new file mode 100644 index 0000000000000000000000000000000000000000..f7c5cb5259f8452b09cc910aee1fec7f1ba438c8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/hp_naming.py @@ -0,0 +1,162 @@ +# Copyright 2020 The HuggingFace Team. All rights reserved. +# +# 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. + +import copy +import re + + +class TrialShortNamer: + PREFIX = "hp" + DEFAULTS = {} + NAMING_INFO = None + + @classmethod + def set_defaults(cls, prefix, defaults): + cls.PREFIX = prefix + cls.DEFAULTS = defaults + cls.build_naming_info() + + @staticmethod + def shortname_for_word(info, word): + if len(word) == 0: + return "" + short_word = None + if any(char.isdigit() for char in word): + raise Exception(f"Parameters should not contain numbers: '{word}' contains a number") + if word in info["short_word"]: + return info["short_word"][word] + for prefix_len in range(1, len(word) + 1): + prefix = word[:prefix_len] + if prefix in info["reverse_short_word"]: + continue + else: + short_word = prefix + break + + if short_word is None: + # Paranoid fallback + def int_to_alphabetic(integer): + s = "" + while integer != 0: + s = chr(ord("A") + integer % 10) + s + integer //= 10 + return s + + i = 0 + while True: + sword = word + "#" + int_to_alphabetic(i) + if sword in info["reverse_short_word"]: + continue + else: + short_word = sword + break + + info["short_word"][word] = short_word + info["reverse_short_word"][short_word] = word + return short_word + + @staticmethod + def shortname_for_key(info, param_name): + words = param_name.split("_") + + shortname_parts = [TrialShortNamer.shortname_for_word(info, word) for word in words] + + # We try to create a separatorless short name, but if there is a collision we have to fallback + # to a separated short name + separators = ["", "_"] + + for separator in separators: + shortname = separator.join(shortname_parts) + if shortname not in info["reverse_short_param"]: + info["short_param"][param_name] = shortname + info["reverse_short_param"][shortname] = param_name + return shortname + + return param_name + + @staticmethod + def add_new_param_name(info, param_name): + short_name = TrialShortNamer.shortname_for_key(info, param_name) + info["short_param"][param_name] = short_name + info["reverse_short_param"][short_name] = param_name + + @classmethod + def build_naming_info(cls): + if cls.NAMING_INFO is not None: + return + + info = { + "short_word": {}, + "reverse_short_word": {}, + "short_param": {}, + "reverse_short_param": {}, + } + + field_keys = list(cls.DEFAULTS.keys()) + + for k in field_keys: + cls.add_new_param_name(info, k) + + cls.NAMING_INFO = info + + @classmethod + def shortname(cls, params): + cls.build_naming_info() + assert cls.PREFIX is not None + name = [copy.copy(cls.PREFIX)] + + for k, v in params.items(): + if k not in cls.DEFAULTS: + raise Exception(f"You should provide a default value for the param name {k} with value {v}") + if v == cls.DEFAULTS[k]: + # The default value is not added to the name + continue + + key = cls.NAMING_INFO["short_param"][k] + + if isinstance(v, bool): + v = 1 if v else 0 + + sep = "" if isinstance(v, (int, float)) else "-" + e = f"{key}{sep}{v}" + name.append(e) + + return "_".join(name) + + @classmethod + def parse_repr(cls, repr): + repr = repr[len(cls.PREFIX) + 1 :] + if repr == "": + values = [] + else: + values = repr.split("_") + + parameters = {} + + for value in values: + if "-" in value: + p_k, p_v = value.split("-") + else: + p_k = re.sub("[0-9.]", "", value) + p_v = float(re.sub("[^0-9.]", "", value)) + + key = cls.NAMING_INFO["reverse_short_param"][p_k] + + parameters[key] = p_v + + for k in cls.DEFAULTS: + if k not in parameters: + parameters[k] = cls.DEFAULTS[k] + + return parameters diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/hub.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/hub.py new file mode 100644 index 0000000000000000000000000000000000000000..616796e4fe22d056db7f6dc3de2c58d140775305 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/hub.py @@ -0,0 +1,949 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# 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. +""" +Hub utilities: utilities related to download and cache models +""" + +import json +import os +import re +import sys +import tempfile +from concurrent import futures +from pathlib import Path +from typing import TypedDict +from uuid import uuid4 + +import httpx +from huggingface_hub import ( + _CACHED_NO_EXIST, + CommitOperationAdd, + ModelCard, + ModelCardData, + constants, + create_branch, + create_commit, + create_repo, + hf_hub_download, + hf_hub_url, + is_offline_mode, + list_repo_tree, + snapshot_download, + try_to_load_from_cache, +) +from huggingface_hub.file_download import REGEX_COMMIT_HASH +from huggingface_hub.utils import ( + EntryNotFoundError, + GatedRepoError, + HfHubHTTPError, + LocalEntryNotFoundError, + OfflineModeIsEnabled, + RepositoryNotFoundError, + RevisionNotFoundError, + build_hf_headers, + get_session, + hf_raise_for_status, +) + +from . import __version__, logging +from .import_utils import ( + ENV_VARS_TRUE_VALUES, + get_torch_version, + is_torch_available, + is_training_run_on_sagemaker, +) + + +LEGACY_PROCESSOR_CHAT_TEMPLATE_FILE = "chat_template.json" +CHAT_TEMPLATE_FILE = "chat_template.jinja" +CHAT_TEMPLATE_DIR = "additional_chat_templates" + + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + + +class DownloadKwargs(TypedDict, total=False): + cache_dir: str | os.PathLike | None + force_download: bool + proxies: dict[str, str] | None + local_files_only: bool + token: str | bool | None + revision: str | None + subfolder: str + commit_hash: str | None + tqdm_class: type | None + + +# Determine default cache directory. +# The best way to set the cache path is with the environment variable HF_HOME. For more details, check out this +# documentation page: https://huggingface.co/docs/huggingface_hub/package_reference/environment_variables. + +HF_MODULES_CACHE = os.getenv("HF_MODULES_CACHE", os.path.join(constants.HF_HOME, "modules")) +TRANSFORMERS_DYNAMIC_MODULE_NAME = "transformers_modules" +SESSION_ID = uuid4().hex + +S3_BUCKET_PREFIX = "https://s3.amazonaws.com/models.huggingface.co/bert" +CLOUDFRONT_DISTRIB_PREFIX = "https://cdn.huggingface.co" + + +def _get_cache_file_to_return( + path_or_repo_id: str, + full_filename: str, + cache_dir: str | Path | None = None, + revision: str | None = None, + repo_type: str | None = None, +): + # We try to see if we have a cached version (not up to date): + resolved_file = try_to_load_from_cache( + path_or_repo_id, full_filename, cache_dir=cache_dir, revision=revision, repo_type=repo_type + ) + if resolved_file is not None and resolved_file != _CACHED_NO_EXIST: + return resolved_file + return None + + +def list_repo_templates( + repo_id: str, + *, + local_files_only: bool, + revision: str | None = None, + cache_dir: str | None = None, + token: str | bool | None = None, +) -> list[str]: + """List template files from a repo. + + A template is a jinja file located under the `additional_chat_templates/` folder. + If working in offline mode or if internet is down, the method will list jinja template from the local cache - if any. + """ + + if not local_files_only: + try: + return [ + entry.path.removeprefix(f"{CHAT_TEMPLATE_DIR}/") + for entry in list_repo_tree( + repo_id=repo_id, + revision=revision, + path_in_repo=CHAT_TEMPLATE_DIR, + recursive=False, + token=token, + ) + if entry.path.endswith(".jinja") + ] + except (GatedRepoError, RepositoryNotFoundError, RevisionNotFoundError): + raise # valid errors => do not catch + except (HfHubHTTPError, OfflineModeIsEnabled, httpx.NetworkError): + pass # offline mode, internet down, etc. => try local files + + # check local files + try: + snapshot_dir = snapshot_download( + repo_id=repo_id, revision=revision, cache_dir=cache_dir, local_files_only=True + ) + except LocalEntryNotFoundError: # No local repo means no local files + return [] + templates_dir = Path(snapshot_dir, CHAT_TEMPLATE_DIR) + if not templates_dir.is_dir(): + return [] + return [entry.stem for entry in templates_dir.iterdir() if entry.is_file() and entry.name.endswith(".jinja")] + + +def define_sagemaker_information(): + try: + instance_data = httpx.get(os.environ["ECS_CONTAINER_METADATA_URI"]).json() + dlc_container_used = instance_data["Image"] + dlc_tag = instance_data["Image"].split(":")[1] + except Exception: + dlc_container_used = None + dlc_tag = None + + sagemaker_params = json.loads(os.getenv("SM_FRAMEWORK_PARAMS", "{}")) + runs_distributed_training = "sagemaker_distributed_dataparallel_enabled" in sagemaker_params + training_job_arn = os.getenv("TRAINING_JOB_ARN") + account_id = training_job_arn.split(":")[4] if training_job_arn is not None else None + + sagemaker_object = { + "sm_framework": os.getenv("SM_FRAMEWORK_MODULE", None), + "sm_region": os.getenv("AWS_REGION", None), + "sm_number_gpu": os.getenv("SM_NUM_GPUS", "0"), + "sm_number_cpu": os.getenv("SM_NUM_CPUS", "0"), + "sm_distributed_training": runs_distributed_training, + "sm_deep_learning_container": dlc_container_used, + "sm_deep_learning_container_tag": dlc_tag, + "sm_account_id": account_id, + } + return sagemaker_object + + +def http_user_agent(user_agent: dict | str | None = None) -> str: + """ + Formats a user-agent string with basic info about a request. + """ + ua = f"transformers/{__version__}; python/{sys.version.split()[0]}; session_id/{SESSION_ID}" + if is_torch_available(): + ua += f"; torch/{get_torch_version()}" + if constants.HF_HUB_DISABLE_TELEMETRY: + return ua + "; telemetry/off" + if is_training_run_on_sagemaker(): + ua += "; " + "; ".join(f"{k}/{v}" for k, v in define_sagemaker_information().items()) + # CI will set this value to True + if os.environ.get("TRANSFORMERS_IS_CI", "").upper() in ENV_VARS_TRUE_VALUES: + ua += "; is_ci/true" + if isinstance(user_agent, dict): + ua += "; " + "; ".join(f"{k}/{v}" for k, v in user_agent.items()) + elif isinstance(user_agent, str): + ua += "; " + user_agent + return ua + + +def extract_commit_hash(resolved_file: str | None, commit_hash: str | None) -> str | None: + """ + Extracts the commit hash from a resolved filename toward a cache file. + """ + if resolved_file is None or commit_hash is not None: + return commit_hash + resolved_file = str(Path(resolved_file).as_posix()) + search = re.search(r"snapshots/([^/]+)/", resolved_file) + if search is None: + return None + commit_hash = search.groups()[0] + return commit_hash if REGEX_COMMIT_HASH.match(commit_hash) else None + + +def cached_file( + path_or_repo_id: str | os.PathLike, + filename: str, + **kwargs, +) -> str | None: + """ + Tries to locate a file in a local folder and repo, downloads and cache it if necessary. + + Args: + path_or_repo_id (`str` or `os.PathLike`): + This can be either: + - a string, the *model id* of a model repo on huggingface.co. + - a path to a *directory* potentially containing the file. + filename (`str`): + The name of the file to locate in `path_or_repo`. + cache_dir (`str` or `os.PathLike`, *optional*): + Path to a directory in which a downloaded pretrained model configuration should be cached if the standard + cache should not be used. + force_download (`bool`, *optional*, defaults to `False`): + Whether or not to force to (re-)download the configuration files and override the cached versions if they + exist. + proxies (`dict[str, str]`, *optional*): + A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', + 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request. + token (`str` or *bool*, *optional*): + The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated + when running `hf auth login` (stored in `~/.huggingface`). + revision (`str`, *optional*, defaults to `"main"`): + The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a + git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any + identifier allowed by git. + local_files_only (`bool`, *optional*, defaults to `False`): + If `True`, will only try to load the tokenizer configuration from local files. + subfolder (`str`, *optional*, defaults to `""`): + In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can + specify the folder name here. + repo_type (`str`, *optional*): + Specify the repo type (useful when downloading from a space for instance). + + + + Passing `token=True` is required when you want to use a private model. + + + + Returns: + `Optional[str]`: Returns the resolved file (to the cache folder if downloaded from a repo). + + Examples: + + ```python + # Download a model weight from the Hub and cache it. + model_weights_file = cached_file("google-bert/bert-base-uncased", "pytorch_model.bin") + ``` + """ + file = cached_files(path_or_repo_id=path_or_repo_id, filenames=[filename], **kwargs) + file = file[0] if file is not None else file + return file + + +def cached_files( + path_or_repo_id: str | os.PathLike, + filenames: list[str], + cache_dir: str | os.PathLike | None = None, + force_download: bool = False, + proxies: dict[str, str] | None = None, + token: bool | str | None = None, + revision: str | None = None, + local_files_only: bool = False, + subfolder: str = "", + repo_type: str | None = None, + user_agent: str | dict[str, str] | None = None, + _raise_exceptions_for_gated_repo: bool = True, + _raise_exceptions_for_missing_entries: bool = True, + _raise_exceptions_for_connection_errors: bool = True, + _commit_hash: str | None = None, + tqdm_class: type | None = None, + **deprecated_kwargs, +) -> list[str] | None: + """ + Tries to locate several files in a local folder and repo, downloads and cache them if necessary. + + Args: + path_or_repo_id (`str` or `os.PathLike`): + This can be either: + - a string, the *model id* of a model repo on huggingface.co. + - a path to a *directory* potentially containing the file. + filenames (`list[str]`): + The name of all the files to locate in `path_or_repo`. + cache_dir (`str` or `os.PathLike`, *optional*): + Path to a directory in which a downloaded pretrained model configuration should be cached if the standard + cache should not be used. + force_download (`bool`, *optional*, defaults to `False`): + Whether or not to force to (re-)download the configuration files and override the cached versions if they + exist. + proxies (`dict[str, str]`, *optional*): + A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', + 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request. + token (`str` or *bool*, *optional*): + The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated + when running `hf auth login` (stored in `~/.huggingface`). + revision (`str`, *optional*, defaults to `"main"`): + The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a + git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any + identifier allowed by git. + local_files_only (`bool`, *optional*, defaults to `False`): + If `True`, will only try to load the tokenizer configuration from local files. + subfolder (`str`, *optional*, defaults to `""`): + In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can + specify the folder name here. + repo_type (`str`, *optional*): + Specify the repo type (useful when downloading from a space for instance). + + Private args: + _raise_exceptions_for_gated_repo (`bool`): + if False, do not raise an exception for gated repo error but return None. + _raise_exceptions_for_missing_entries (`bool`): + if False, do not raise an exception for missing entries but return None. + _raise_exceptions_for_connection_errors (`bool`): + if False, do not raise an exception for connection errors but return None. + _commit_hash (`str`, *optional*): + passed when we are chaining several calls to various files (e.g. when loading a tokenizer or + a pipeline). If files are cached for this commit hash, avoid calls to head and get from the cache. + + + + Passing `token=True` is required when you want to use a private model. + + + + Returns: + `Optional[str]`: Returns the resolved file (to the cache folder if downloaded from a repo). + + Examples: + + ```python + # Download a model weight from the Hub and cache it. + model_weights_file = cached_file("google-bert/bert-base-uncased", "pytorch_model.bin") + ``` + """ + if is_offline_mode() and not local_files_only: + logger.info("Offline mode: forcing local_files_only=True") + local_files_only = True + if subfolder is None: + subfolder = "" + + # Add folder to filenames + full_filenames = [os.path.join(subfolder, file) for file in filenames] + + path_or_repo_id = str(path_or_repo_id) + existing_files = [] + for filename in full_filenames: + if os.path.isdir(path_or_repo_id): + resolved_file = os.path.join(path_or_repo_id, filename) + if not os.path.isfile(resolved_file): + if _raise_exceptions_for_missing_entries and filename != os.path.join(subfolder, "config.json"): + revision_ = "main" if revision is None else revision + raise OSError( + f"{path_or_repo_id} does not appear to have a file named {filename}. Checkout " + f"'https://huggingface.co/{path_or_repo_id}/tree/{revision_}' for available files." + ) + else: + continue + existing_files.append(resolved_file) + + if os.path.isdir(path_or_repo_id): + return existing_files if existing_files else None + + if cache_dir is None: + cache_dir = constants.HF_HUB_CACHE + if isinstance(cache_dir, Path): + cache_dir = str(cache_dir) + + existing_files = [] + file_counter = 0 + if _commit_hash is not None and not force_download: + for filename in full_filenames: + # If the file is cached under that commit hash, we return it directly. + resolved_file = try_to_load_from_cache( + path_or_repo_id, filename, cache_dir=cache_dir, revision=_commit_hash, repo_type=repo_type + ) + if resolved_file is not None: + if resolved_file is not _CACHED_NO_EXIST: + file_counter += 1 + existing_files.append(resolved_file) + elif not _raise_exceptions_for_missing_entries: + file_counter += 1 + else: + raise OSError(f"Could not locate {filename} inside {path_or_repo_id}.") + + # Either all the files were found, or some were _CACHED_NO_EXIST but we do not raise for missing entries + if file_counter == len(full_filenames): + return existing_files if len(existing_files) > 0 else None + + user_agent = http_user_agent(user_agent) + # download the files if needed + try: + if len(full_filenames) == 1: + # This is slightly better for only 1 file + hf_hub_download( + path_or_repo_id, + filenames[0], + subfolder=None if len(subfolder) == 0 else subfolder, + repo_type=repo_type, + revision=revision, + cache_dir=cache_dir, + user_agent=user_agent, + force_download=force_download, + proxies=proxies, + token=token, + local_files_only=local_files_only, + tqdm_class=tqdm_class, + ) + else: + snapshot_download( + path_or_repo_id, + allow_patterns=full_filenames, + repo_type=repo_type, + revision=revision, + cache_dir=cache_dir, + user_agent=user_agent, + force_download=force_download, + proxies=proxies, + token=token, + local_files_only=local_files_only, + tqdm_class=tqdm_class, + ) + + except Exception as e: + # We cannot recover from them + if isinstance(e, RepositoryNotFoundError) and not isinstance(e, GatedRepoError): + raise OSError( + f"{path_or_repo_id} is not a local folder and is not a valid model identifier " + "listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a token " + "having permission to this repo either by logging in with `hf auth login` or by passing " + "`token=`" + ) from e + elif isinstance(e, RevisionNotFoundError): + raise OSError( + f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists " + "for this model name. Check the model page at " + f"'https://huggingface.co/{path_or_repo_id}' for available revisions." + ) from e + elif isinstance(e, PermissionError): + raise OSError( + f"PermissionError at {e.filename} when downloading {path_or_repo_id}. " + "Check cache directory permissions. Common causes: 1) another user is downloading the same model (please wait); " + "2) a previous download was canceled and the lock file needs manual removal." + ) from e + elif isinstance(e, ValueError): + raise OSError(f"{e}") from e + + # Now we try to recover if we can find all files correctly in the cache + resolved_files = [ + _get_cache_file_to_return(path_or_repo_id, filename, cache_dir, revision, repo_type) + for filename in full_filenames + ] + if all(file is not None for file in resolved_files): + return resolved_files + + # Raise based on the flags. Note that we will raise for missing entries at the very end, even when + # not entering this Except block, as it may also happen when `snapshot_download` does not raise + if isinstance(e, GatedRepoError): + if not _raise_exceptions_for_gated_repo: + return None + raise OSError( + "You are trying to access a gated repo.\nMake sure to have access to it at " + f"https://huggingface.co/{path_or_repo_id}.\n{str(e)}" + ) from e + elif isinstance(e, LocalEntryNotFoundError): + if not _raise_exceptions_for_connection_errors: + return None + # Here we only raise if both flags for missing entry and connection errors are True (because it can be raised + # even when `local_files_only` is True, in which case raising for connections errors only would not make sense) + elif _raise_exceptions_for_missing_entries: + raise OSError( + f"We couldn't connect to '{constants.ENDPOINT}' to load the files, and couldn't find them in the" + f" cached files.\nCheck your internet connection or see how to run the library in offline mode at" + " 'https://huggingface.co/docs/transformers/installation#offline-mode'." + ) from e + # snapshot_download will not raise EntryNotFoundError, but hf_hub_download can. If this is the case, it will be treated + # later on anyway and re-raised if needed + elif isinstance(e, HfHubHTTPError) and not isinstance(e, EntryNotFoundError): + if not _raise_exceptions_for_connection_errors: + return None + raise OSError(f"There was a specific connection error when trying to load {path_or_repo_id}:\n{e}") from e + # Any other Exception type should now be re-raised, in order to provide helpful error messages and break the execution flow + # (EntryNotFoundError will be treated outside this block and correctly re-raised if needed) + elif not isinstance(e, EntryNotFoundError): + raise e + + resolved_files = [ + _get_cache_file_to_return(path_or_repo_id, filename, cache_dir, revision) for filename in full_filenames + ] + # If there are any missing file and the flag is active, raise + if any(file is None for file in resolved_files) and _raise_exceptions_for_missing_entries: + missing_entries = [original for original, resolved in zip(full_filenames, resolved_files) if resolved is None] + # Last escape + if len(resolved_files) == 1 and missing_entries[0] == os.path.join(subfolder, "config.json"): + return None + # Now we raise for missing entries + revision_ = "main" if revision is None else revision + msg = ( + f"a file named {missing_entries[0]}" if len(missing_entries) == 1 else f"files named {(*missing_entries,)}" + ) + raise OSError( + f"{path_or_repo_id} does not appear to have {msg}. Checkout 'https://huggingface.co/{path_or_repo_id}/tree/{revision_}'" + " for available files." + ) + + # Remove potential missing entries (we can silently remove them at this point based on the flags) + resolved_files = [file for file in resolved_files if file is not None] + # Return `None` if the list is empty, coherent with other Exception when the flag is not active + resolved_files = None if len(resolved_files) == 0 else resolved_files + + return resolved_files + + +def has_file( + path_or_repo: str | os.PathLike, + filename: str, + revision: str | None = None, + proxies: dict[str, str] | None = None, + token: bool | str | None = None, + *, + local_files_only: bool = False, + cache_dir: str | Path | None = None, + repo_type: str | None = None, + **deprecated_kwargs, +): + """ + Checks if a repo contains a given file without downloading it. Works for remote repos and local folders. + + If offline mode is enabled, checks if the file exists in the cache. + + + + This function will raise an error if the repository `path_or_repo` is not valid or if `revision` does not exist for + this repo, but will return False for regular connection errors. + + + """ + # If path to local directory, check if the file exists + if os.path.isdir(path_or_repo): + return os.path.isfile(os.path.join(path_or_repo, filename)) + + # Else it's a repo => let's check if the file exists in local cache or on the Hub + + # Check if file exists in cache + # This information might be outdated so it's best to also make a HEAD call (if allowed). + cached_path = try_to_load_from_cache( + repo_id=path_or_repo, + filename=filename, + revision=revision, + repo_type=repo_type, + cache_dir=cache_dir, + ) + has_file_in_cache = isinstance(cached_path, str) + + # If local_files_only, don't try the HEAD call + if local_files_only: + return has_file_in_cache + + # Check if the file exists + try: + response = get_session().head( + hf_hub_url(path_or_repo, filename=filename, revision=revision, repo_type=repo_type), + headers=build_hf_headers(token=token, user_agent=http_user_agent()), + follow_redirects=False, + timeout=10, + ) + except httpx.ProxyError: + # Actually raise for those subclasses of ConnectionError + raise + except (httpx.ConnectError, httpx.TimeoutException, OfflineModeIsEnabled): + return has_file_in_cache + + try: + hf_raise_for_status(response) + return True + except GatedRepoError as e: + logger.error(e) + raise OSError( + f"{path_or_repo} is a gated repository. Make sure to request access at " + f"https://huggingface.co/{path_or_repo} and pass a token having permission to this repo either by " + "logging in with `hf auth login` or by passing `token=`." + ) from e + except RepositoryNotFoundError as e: + logger.error(e) + raise OSError(f"{path_or_repo} is not a local folder or a valid repository name on 'https://hf.co'.") from e + except RevisionNotFoundError as e: + logger.error(e) + raise OSError( + f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for this " + f"model name. Check the model page at 'https://huggingface.co/{path_or_repo}' for available revisions." + ) from e + except EntryNotFoundError: + return False # File does not exist + except HfHubHTTPError: + # Any authentication/authorization error will be caught here => default to cache + return has_file_in_cache + + +class PushToHubMixin: + """ + A Mixin containing the functionality to push a model or tokenizer to the hub. + """ + + def _get_files_timestamps(self, working_dir: str | os.PathLike): + """ + Returns the list of files with their last modification timestamp. + """ + return {f: os.path.getmtime(os.path.join(working_dir, f)) for f in os.listdir(working_dir)} + + def _upload_modified_files( + self, + working_dir: str | os.PathLike, + repo_id: str, + files_timestamps: dict[str, float], + commit_message: str | None = None, + token: bool | str | None = None, + create_pr: bool = False, + revision: str | None = None, + commit_description: str | None = None, + ): + """ + Uploads all modified files in `working_dir` to `repo_id`, based on `files_timestamps`. + """ + if commit_message is None: + if "Model" in self.__class__.__name__: + commit_message = "Upload model" + elif "Config" in self.__class__.__name__: + commit_message = "Upload config" + elif "Tokenizer" in self.__class__.__name__: + commit_message = "Upload tokenizer" + elif "FeatureExtractor" in self.__class__.__name__: + commit_message = "Upload feature extractor" + elif "Processor" in self.__class__.__name__: + commit_message = "Upload processor" + else: + commit_message = f"Upload {self.__class__.__name__}" + modified_files = [ + f + for f in os.listdir(working_dir) + if f not in files_timestamps or os.path.getmtime(os.path.join(working_dir, f)) > files_timestamps[f] + ] + + # filter for actual files + folders at the root level + modified_files = [ + f + for f in modified_files + if os.path.isfile(os.path.join(working_dir, f)) or os.path.isdir(os.path.join(working_dir, f)) + ] + + operations = [] + # upload standalone files + for file in modified_files: + if os.path.isdir(os.path.join(working_dir, file)): + # go over individual files of folder + for f in os.listdir(os.path.join(working_dir, file)): + operations.append( + CommitOperationAdd( + path_or_fileobj=os.path.join(working_dir, file, f), path_in_repo=os.path.join(file, f) + ) + ) + else: + operations.append( + CommitOperationAdd(path_or_fileobj=os.path.join(working_dir, file), path_in_repo=file) + ) + + if revision is not None and not revision.startswith("refs/pr"): + try: + create_branch(repo_id=repo_id, branch=revision, token=token, exist_ok=True) + except HfHubHTTPError as e: + if e.response.status_code == 403 and create_pr: + # If we are creating a PR on a repo we don't have access to, we can't create the branch. + # so let's assume the branch already exists. If it's not the case, an error will be raised when + # calling `create_commit` below. + pass + else: + raise + + logger.info(f"Uploading the following files to {repo_id}: {','.join(modified_files)}") + return create_commit( + repo_id=repo_id, + operations=operations, + commit_message=commit_message, + commit_description=commit_description, + token=token, + create_pr=create_pr, + revision=revision, + ) + + def save_pretrained(self, *args, **kwargs): + # explicit contract + raise NotImplementedError(f"{self.__class__.__name__} must implement `save_pretrained` to use `push_to_hub`.") + + def push_to_hub( + self, + repo_id: str, + *, + # Commit details + commit_message: str | None = None, + commit_description: str | None = None, + # Repo / upload details + private: bool | None = None, + token: bool | str | None = None, + revision: str | None = None, + create_pr: bool = False, + # Serialization details + max_shard_size: int | str | None = "50GB", + tags: list[str] | None = None, + ) -> str: + """ + Upload the {object_files} to the 🤗 Model Hub. + + Parameters: + repo_id (`str`): + The name of the repository you want to push your {object} to. It should contain your organization name + when pushing to a given organization. + commit_message (`str`, *optional*): + Message to commit while pushing. Will default to `"Upload {object}"`. + commit_description (`str`, *optional*): + The description of the commit that will be created + private (`bool`, *optional*): + Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists. + token (`bool` or `str`, *optional*): + The token to use as HTTP bearer authorization for remote files. If `True` (default), will use the token generated + when running `hf auth login` (stored in `~/.huggingface`). + revision (`str`, *optional*): + Branch to push the uploaded files to. + create_pr (`bool`, *optional*, defaults to `False`): + Whether or not to create a PR with the uploaded files or directly commit. + max_shard_size (`int` or `str`, *optional*, defaults to `"50GB"`): + Only applicable for models. The maximum size for a checkpoint before being sharded. Checkpoints shard + will then be each of size lower than this size. If expressed as a string, needs to be digits followed + by a unit (like `"5MB"`). + tags (`list[str]`, *optional*): + List of tags to push on the Hub. + + Examples: + + ```python + from transformers import {object_class} + + {object} = {object_class}.from_pretrained("google-bert/bert-base-cased") + + # Push the {object} to your namespace with the name "my-finetuned-bert". + {object}.push_to_hub("my-finetuned-bert") + + # Push the {object} to an organization with the name "my-finetuned-bert". + {object}.push_to_hub("huggingface/my-finetuned-bert") + ``` + """ + # Create repo if it doesn't exist yet + repo_id = create_repo(repo_id, private=private, token=token, exist_ok=True).repo_id + + # Load model card or create a new one + eventually tag it + model_card = create_and_tag_model_card(repo_id, tags, token=token) + + with tempfile.TemporaryDirectory() as tmp_dir: + # Save all files. + self.save_pretrained(tmp_dir, max_shard_size=max_shard_size) + + # Update model card + model_card.save(os.path.join(tmp_dir, "README.md")) + + # Upload + return self._upload_modified_files( + tmp_dir, + repo_id, + files_timestamps={}, + commit_message=commit_message, + token=token, + create_pr=create_pr, + revision=revision, + commit_description=commit_description, + ) + + +def convert_file_size_to_int(size: int | str): + """ + Converts a size expressed as a string with digits an unit (like `"5MB"`) to an integer (in bytes). + + Args: + size (`int` or `str`): The size to convert. Will be directly returned if an `int`. + + Example: + ```py + >>> convert_file_size_to_int("1MiB") + 1048576 + ``` + """ + if isinstance(size, int): + return size + if size.upper().endswith("GIB"): + return int(size[:-3]) * (2**30) + if size.upper().endswith("MIB"): + return int(size[:-3]) * (2**20) + if size.upper().endswith("KIB"): + return int(size[:-3]) * (2**10) + if size.upper().endswith("GB"): + int_size = int(size[:-2]) * (10**9) + return int_size // 8 if size.endswith("b") else int_size + if size.upper().endswith("MB"): + int_size = int(size[:-2]) * (10**6) + return int_size // 8 if size.endswith("b") else int_size + if size.upper().endswith("KB"): + int_size = int(size[:-2]) * (10**3) + return int_size // 8 if size.endswith("b") else int_size + raise ValueError("`size` is not in a valid format. Use an integer followed by the unit, e.g., '5GB'.") + + +def get_checkpoint_shard_files( + pretrained_model_name_or_path, + index_filename, + cache_dir=None, + force_download=False, + proxies=None, + local_files_only=False, + token=None, + user_agent=None, + revision=None, + subfolder="", + _commit_hash=None, + tqdm_class=None, + **deprecated_kwargs, +): + """ + For a given model: + + - download and cache all the shards of a sharded checkpoint if `pretrained_model_name_or_path` is a model ID on the + Hub + - returns the list of paths to all the shards, as well as some metadata. + + For the description of each arg, see [`PreTrainedModel.from_pretrained`]. `index_filename` is the full path to the + index (downloaded and cached if `pretrained_model_name_or_path` is a model ID on the Hub). + """ + if not os.path.isfile(index_filename): + raise ValueError(f"Can't find a checkpoint index ({index_filename}) in {pretrained_model_name_or_path}.") + + with open(index_filename) as f: + index = json.loads(f.read()) + + shard_filenames = sorted(set(index["weight_map"].values())) + sharded_metadata = index["metadata"] + sharded_metadata["all_checkpoint_keys"] = list(index["weight_map"].keys()) + sharded_metadata["weight_map"] = index["weight_map"].copy() + + # First, let's deal with local folder. + if os.path.isdir(pretrained_model_name_or_path): + shard_filenames = [os.path.join(pretrained_model_name_or_path, subfolder, f) for f in shard_filenames] + return shard_filenames, sharded_metadata + + # At this stage pretrained_model_name_or_path is a model identifier on the Hub. Try to get everything from cache, + # or download the files + cached_filenames = cached_files( + pretrained_model_name_or_path, + shard_filenames, + cache_dir=cache_dir, + force_download=force_download, + proxies=proxies, + local_files_only=local_files_only, + token=token, + user_agent=user_agent, + revision=revision, + subfolder=subfolder, + _commit_hash=_commit_hash, + tqdm_class=tqdm_class, + ) + + return cached_filenames, sharded_metadata + + +def create_and_tag_model_card(repo_id: str, tags: list[str] | None = None, token: str | None = None) -> ModelCard: + """ + Creates or loads an existing model card and tags it. + + Args: + repo_id (`str`): + The repo_id where to look for the model card. + tags (`list[str]`, *optional*): + The list of tags to add in the model card + token (`str`, *optional*): + Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to the stored token. + """ + try: + # Check if the model card is present on the remote repo + model_card = ModelCard.load(repo_id, token=token) + except EntryNotFoundError: + # Otherwise create a simple model card from template + model_description = "This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated." + card_data = ModelCardData(tags=[] if tags is None else tags, library_name="transformers") + model_card = ModelCard.from_template(card_data, model_description=model_description) + + if tags is not None: + # Ensure model_card.data.tags is a list and not None + if model_card.data.tags is None: + model_card.data.tags = [] + for model_tag in tags: + if model_tag not in model_card.data.tags: + model_card.data.tags.append(model_tag) + + return model_card + + +class PushInProgress: + """ + Internal class to keep track of a push in progress (which might contain multiple `Future` jobs). + """ + + def __init__(self, jobs: futures.Future | None = None) -> None: + self.jobs = [] if jobs is None else jobs + + def is_done(self): + return all(job.done() for job in self.jobs) + + def wait_until_done(self): + futures.wait(self.jobs) + + def cancel(self) -> None: + self.jobs = [ + job + for job in self.jobs + # Cancel the job if it wasn't started yet and remove cancelled/done jobs from the list + if not (job.cancel() or job.done()) + ] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/import_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/import_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8654bd083ba2cd5aade7283b415b72960e5dab59 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/import_utils.py @@ -0,0 +1,3031 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# 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. +""" +Import utilities: Utilities related to imports and our lazy inits. +""" + +import functools +import importlib.machinery +import importlib.metadata +import importlib.util +import json +import operator +import os +import re +import shutil +import subprocess +import sys +import warnings +from collections import OrderedDict +from collections.abc import Callable +from enum import Enum +from functools import lru_cache +from itertools import chain +from types import ModuleType +from typing import Any + +import packaging.version +from packaging import version + +from . import logging + + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + + +PACKAGE_DISTRIBUTION_MAPPING = importlib.metadata.packages_distributions() + + +def _is_package_available(pkg_name: str, return_version: bool = False) -> tuple[bool, str]: + """Check if `pkg_name` exist, and optionally try to get its version""" + spec = importlib.util.find_spec(pkg_name) + package_exists = spec is not None + package_version = "N/A" + if package_exists and return_version: + try: + # importlib.metadata works with the distribution package, which may be different from the import + # name (e.g. `PIL` is the import name, but `pillow` is the distribution name) + distributions = PACKAGE_DISTRIBUTION_MAPPING[pkg_name] + # Per PEP 503, underscores and hyphens are equivalent in package names. + # Prefer the distribution that matches the (normalized) package name. + normalized_pkg_name = pkg_name.replace("_", "-") + if normalized_pkg_name in distributions: + distribution_name = normalized_pkg_name + elif pkg_name in distributions: + distribution_name = pkg_name + else: + distribution_name = distributions[0] + package_version = importlib.metadata.version(distribution_name) + except (importlib.metadata.PackageNotFoundError, KeyError): + # If we cannot find the metadata (because of editable install for example), try to import directly. + # Note that this branch will almost never be run, so we do not import packages for nothing here + package = importlib.import_module(pkg_name) + package_version = getattr(package, "__version__", "N/A") + logger.debug(f"Detected {pkg_name} version: {package_version}") + + if return_version: + return package_exists, package_version + else: + return package_exists, None + + +def resolve_internal_import(module: ModuleType | None, chained_path: str) -> Callable | ModuleType | None: + """ + Check if a given `module` has an internal import path as defined by the `chained_path`. + This can either be the full path (not exposed in `__init__`) OR the last part of the chain (exposed in `__init__`). + + This is an important helper function for kernels based modules to apply the import from the module + itself, i.e. stay compatible with original libraries in certain cases. + + Example: + Module: `mamba_ssm` + Chained Path: `ops.triton.selective_state_update.selective_state_update` + Resulting import attempt at: + - `mamba_ssm.selective_state_update` + - `mamba_ssm.ops.triton.selective_state_update.selective_state_update` + """ + if not module: + return None + + if final_module := getattr(module, chained_path.split(".")[-1], None): + return final_module + + final_module = module + for path in chained_path.split("."): + final_module = getattr(final_module, path, None) + if not final_module: + return None + + return final_module + + +def is_env_variable_true(env_variable: str) -> bool: + """Detect whether `env_variable` has been set to a true value in the environment""" + return os.getenv(env_variable, "false").lower() in ("true", "1", "y", "yes", "on") + + +def is_env_variable_false(env_variable: str) -> bool: + """Detect whether `env_variable` has been set to a false value in the environment""" + return os.getenv(env_variable, "true").lower() in ("false", "0", "n", "no", "off") + + +ENV_VARS_TRUE_VALUES = {"1", "ON", "YES", "TRUE"} +ENV_VARS_TRUE_AND_AUTO_VALUES = ENV_VARS_TRUE_VALUES.union({"AUTO"}) + +# Try to run a native pytorch job in an environment with TorchXLA installed by setting this value to 0. +USE_TORCH_XLA = os.environ.get("USE_TORCH_XLA", "1").upper() + +ACCELERATE_MIN_VERSION = "1.1.0" +BITSANDBYTES_MIN_VERSION = "0.46.1" +SCHEDULEFREE_MIN_VERSION = "1.2.6" +FSDP_MIN_VERSION = "1.12.0" +GGUF_MIN_VERSION = "0.10.0" +XLA_FSDPV2_MIN_VERSION = "2.2.0" +HQQ_MIN_VERSION = "0.2.1" +VPTQ_MIN_VERSION = "0.0.4" +TORCHAO_MIN_VERSION = "0.15.0" +AUTOROUND_MIN_VERSION = "0.5.0" +TRITON_MIN_VERSION = "1.0.0" +KERNELS_MIN_VERSION = "0.10.2" + + +@lru_cache +def is_torch_available() -> bool: + try: + is_available, torch_version = _is_package_available("torch", return_version=True) + parsed_version = version.parse(torch_version) + if is_available and parsed_version < version.parse("2.4.0"): + logger.warning_once(f"Disabling PyTorch because PyTorch >= 2.4 is required but found {torch_version}") + return is_available and version.parse(torch_version) >= version.parse("2.4.0") + except packaging.version.InvalidVersion: + return False + + +@lru_cache +def get_torch_version() -> str: + _, torch_version = _is_package_available("torch", return_version=True) + return torch_version + + +@lru_cache +def is_torch_greater_or_equal(library_version: str, accept_dev: bool = False) -> bool: + """ + Accepts a library version and returns True if the current version of the library is greater than or equal to the + given version. If `accept_dev` is True, it will also accept development versions (e.g. 2.7.0.dev20250320 matches + 2.7.0). + """ + if not is_torch_available(): + return False + + if accept_dev: + return version.parse(version.parse(get_torch_version()).base_version) >= version.parse(library_version) + else: + return version.parse(get_torch_version()) >= version.parse(library_version) + + +@lru_cache +def is_torch_less_or_equal(library_version: str, accept_dev: bool = False) -> bool: + """ + Accepts a library version and returns True if the current version of the library is less than or equal to the + given version. If `accept_dev` is True, it will also accept development versions (e.g. 2.7.0.dev20250320 matches + 2.7.0). + """ + if not is_torch_available(): + return False + + if accept_dev: + return version.parse(version.parse(get_torch_version()).base_version) <= version.parse(library_version) + else: + return version.parse(get_torch_version()) <= version.parse(library_version) + + +@lru_cache +def is_torch_accelerator_available() -> bool: + if is_torch_available(): + import torch + + return hasattr(torch, "accelerator") + + return False + + +@lru_cache +def is_torch_cuda_available() -> bool: + if is_torch_available(): + import torch + + return torch.cuda.is_available() + return False + + +@lru_cache +def is_cuda_platform() -> bool: + if is_torch_available(): + import torch + + return getattr(torch, "version").cuda is not None + return False + + +@lru_cache +def get_cuda_runtime_version() -> tuple[int, int]: + """Return the CUDA runtime version as (major, minor). + + Prefers a direct query of ``cudaRuntimeGetVersion`` via ``libcudart.so``. If that's + not on the system loader path (common with pip-installed torch that bundles its own + CUDA runtime), falls back to ``torch.version.cuda`` — which equals the bundled + runtime's version for pip wheels. Returns ``(0, 0)`` for CPU-only torch. + """ + import ctypes + + try: + cudart = ctypes.CDLL("libcudart.so") + except OSError: + if not is_torch_available(): + return 0, 0 + import torch + + cuda_version = getattr(torch.version, "cuda", None) + if cuda_version is None: + return 0, 0 + + major, minor, *_ = cuda_version.split(".") + return int(major), int(minor) + + version = ctypes.c_int() + cudart.cudaRuntimeGetVersion(ctypes.byref(version)) + return version.value // 1000, (version.value % 1000) // 10 + + +@lru_cache +def is_rocm_platform() -> bool: + if is_torch_available(): + import torch + + return getattr(torch, "version").hip is not None + return False + + +@lru_cache +def is_habana_gaudi1() -> bool: + if not is_torch_hpu_available(): + return False + + import habana_frameworks.torch.utils.experimental as htexp + + # Check if the device is Gaudi1 (vs Gaudi2, Gaudi3) + return htexp._get_device_type() == htexp.synDeviceType.synDeviceGaudi + + +@lru_cache +def is_torch_mps_available(min_version: str | None = None) -> bool: + if is_torch_available(): + import torch + + backend_available = torch.backends.mps.is_available() and torch.backends.mps.is_built() + if min_version is not None: + flag = version.parse(get_torch_version()) >= version.parse(min_version) + backend_available = backend_available and flag + return backend_available + return False + + +@lru_cache +def is_torch_npu_available(check_device=False) -> bool: + "Checks if `torch_npu` is installed and potentially if a NPU is in the environment" + if not is_torch_available() or not _is_package_available("torch_npu")[0]: + return False + + import torch + import torch_npu # noqa: F401 + + if check_device: + try: + # Will raise a RuntimeError if no NPU is found + if hasattr(torch, "npu"): + _ = torch.npu.device_count() + return torch.npu.is_available() + return False + except RuntimeError: + return False + return hasattr(torch, "npu") and torch.npu.is_available() + + +@lru_cache +def is_torch_xpu_available(check_device: bool = False) -> bool: + """ + Checks if XPU acceleration is available via stock PyTorch (>=2.6) and + potentially if a XPU is in the environment. + """ + if not is_torch_available(): + return False + + torch_version = version.parse(get_torch_version()) + if torch_version.major == 2 and torch_version.minor < 6: + return False + + import torch + + if check_device: + try: + # Will raise a RuntimeError if no XPU is found + _ = torch.xpu.device_count() + return torch.xpu.is_available() + except RuntimeError: + return False + return hasattr(torch, "xpu") and torch.xpu.is_available() + + +@lru_cache +def is_torch_mlu_available() -> bool: + """ + Checks if `mlu` is available via an `cndev-based` check which won't trigger the drivers and leave mlu + uninitialized. + """ + if not is_torch_available() or not _is_package_available("torch_mlu")[0]: + return False + + import torch + import torch_mlu # noqa: F401 + + pytorch_cndev_based_mlu_check_previous_value = os.environ.get("PYTORCH_CNDEV_BASED_MLU_CHECK") + try: + os.environ["PYTORCH_CNDEV_BASED_MLU_CHECK"] = str(1) + available = torch.mlu.is_available() if hasattr(torch, "mlu") else False + finally: + if pytorch_cndev_based_mlu_check_previous_value: + os.environ["PYTORCH_CNDEV_BASED_MLU_CHECK"] = pytorch_cndev_based_mlu_check_previous_value + else: + os.environ.pop("PYTORCH_CNDEV_BASED_MLU_CHECK", None) + + return available + + +@lru_cache +def is_torch_musa_available(check_device=False) -> bool: + "Checks if `torch_musa` is installed and potentially if a MUSA is in the environment" + if not is_torch_available() or not _is_package_available("torch_musa")[0]: + return False + + import torch + import torch_musa # noqa: F401 + + torch_musa_min_version = "0.33.0" + accelerate_available, accelerate_version = _is_package_available("accelerate", return_version=True) + if accelerate_available and version.parse(accelerate_version) < version.parse(torch_musa_min_version): + return False + + if check_device: + try: + # Will raise a RuntimeError if no MUSA is found + if hasattr(torch, "musa"): + _ = torch.musa.device_count() + return torch.musa.is_available() + return False + except RuntimeError: + return False + return hasattr(torch, "musa") and torch.musa.is_available() + + +@lru_cache +def is_torch_xla_available(check_is_tpu=False, check_is_gpu=False) -> bool: + """ + Check if `torch_xla` is available. To train a native pytorch job in an environment with torch xla installed, set + the USE_TORCH_XLA to false. + """ + assert not (check_is_tpu and check_is_gpu), "The check_is_tpu and check_is_gpu cannot both be true." + + torch_xla_available = USE_TORCH_XLA in ENV_VARS_TRUE_VALUES and _is_package_available("torch_xla")[0] + if not torch_xla_available: + return False + + import torch_xla + + if check_is_gpu: + return torch_xla.runtime.device_type() in ["GPU", "CUDA"] + elif check_is_tpu: + return torch_xla.runtime.device_type() == "TPU" + + return True + + +@lru_cache +def is_torch_hpu_available() -> bool: + "Checks if `torch.hpu` is available and potentially if a HPU is in the environment" + if ( + not is_torch_available() + or not _is_package_available("habana_frameworks")[0] + or not _is_package_available("habana_frameworks.torch")[0] + ): + return False + + torch_hpu_min_accelerate_version = "1.5.0" + accelerate_available, accelerate_version = _is_package_available("accelerate", return_version=True) + if accelerate_available and version.parse(accelerate_version) < version.parse(torch_hpu_min_accelerate_version): + return False + + import torch + + if os.environ.get("PT_HPU_LAZY_MODE", "1") == "1": + # import habana_frameworks.torch in case of lazy mode to patch torch with torch.hpu + import habana_frameworks.torch # noqa: F401 + + if not hasattr(torch, "hpu") or not torch.hpu.is_available(): + return False + + # We patch torch.gather for int64 tensors to avoid a bug on Gaudi + # Graph compile failed with synStatus 26 [Generic failure] + # This can be removed once bug is fixed but for now we need it. + original_gather = torch.gather + + def patched_gather(input: torch.Tensor, dim: int, index: torch.LongTensor) -> torch.Tensor: + if input.dtype == torch.int64 and input.device.type == "hpu": + return original_gather(input.to(torch.int32), dim, index).to(torch.int64) + else: + return original_gather(input, dim, index) + + torch.gather = patched_gather + torch.Tensor.gather = patched_gather + + original_take_along_dim = torch.take_along_dim + + def patched_take_along_dim(input: torch.Tensor, indices: torch.LongTensor, dim: int | None = None) -> torch.Tensor: + if input.dtype == torch.int64 and input.device.type == "hpu": + return original_take_along_dim(input.to(torch.int32), indices, dim).to(torch.int64) + else: + return original_take_along_dim(input, indices, dim) + + torch.take_along_dim = patched_take_along_dim + + original_cholesky = torch.linalg.cholesky + + def safe_cholesky(A, *args, **kwargs): + output = original_cholesky(A, *args, **kwargs) + + if torch.isnan(output).any(): + jitter_value = 1e-9 + diag_jitter = torch.eye(A.size(-1), dtype=A.dtype, device=A.device) * jitter_value + output = original_cholesky(A + diag_jitter, *args, **kwargs) + + return output + + torch.linalg.cholesky = safe_cholesky + + original_scatter = torch.scatter + + def patched_scatter( + input: torch.Tensor, dim: int, index: torch.Tensor, src: torch.Tensor, *args, **kwargs + ) -> torch.Tensor: + if input.device.type == "hpu" and input is src: + return original_scatter(input, dim, index, src.clone(), *args, **kwargs) + else: + return original_scatter(input, dim, index, src, *args, **kwargs) + + torch.scatter = patched_scatter + torch.Tensor.scatter = patched_scatter + + # IlyasMoutawwakil: we patch torch.compile to use the HPU backend by default + # https://github.com/huggingface/transformers/pull/38790#discussion_r2157043944 + # This is necessary for cases where torch.compile is used as a decorator (defaulting to inductor) + # https://github.com/huggingface/transformers/blob/af6120b3eb2470b994c21421bb6eaa76576128b0/src/transformers/models/modernbert/modeling_modernbert.py#L204 + original_compile = torch.compile + + def hpu_backend_compile(*args, **kwargs): + if kwargs.get("backend") not in ["hpu_backend", "eager"]: + logger.warning( + f"Calling torch.compile with backend={kwargs.get('backend')} on a Gaudi device is not supported. " + "We will override the backend with 'hpu_backend' to avoid errors." + ) + kwargs["backend"] = "hpu_backend" + + return original_compile(*args, **kwargs) + + torch.compile = hpu_backend_compile + + return True + + +@lru_cache +def is_torch_neuron_available(check_device: bool = False) -> bool: + import torch + + if importlib.util.find_spec("torch_neuronx") is None: + return False + + if check_device: + try: + import torch_neuronx # noqa: F401 + + # Will raise a RuntimeError if no Neuron is found + if hasattr(torch, "neuron"): + _ = torch.neuron.device_count() + return torch.neuron.is_available() + return False + except RuntimeError: + return False + + return hasattr(torch, "neuron") and torch.neuron.is_available() + + +@lru_cache +def is_torch_bf16_gpu_available() -> bool: + if not is_torch_available(): + return False + + import torch + + if torch.cuda.is_available(): + return torch.cuda.is_bf16_supported() + if is_torch_xpu_available(): + return torch.xpu.is_bf16_supported() + if is_torch_hpu_available(): + return True + if is_torch_npu_available() and hasattr(torch, "npu"): + return torch.npu.is_bf16_supported() + if is_torch_mps_available(): + # Note: Emulated in software by Metal using fp32 for hardware without native support (like M1/M2) + return torch.backends.mps.is_macos_or_newer(14, 0) + if is_torch_musa_available() and hasattr(torch, "musa"): + return torch.musa.is_bf16_supported() + if is_torch_mlu_available() and hasattr(torch, "mlu"): + return torch.mlu.is_bf16_supported() + if is_torch_neuron_available() and hasattr(torch, "neuron"): + return torch.neuron.is_bf16_supported() + return False + + +@lru_cache +def is_torch_fp16_available_on_device(device: str) -> bool: + if not is_torch_available(): + return False + + if is_torch_hpu_available(): + if is_habana_gaudi1(): + return False + else: + return True + + import torch + + try: + x = torch.zeros(2, 2, dtype=torch.float16, device=device) + _ = x @ x + # At this moment, let's be strict of the check: check if `LayerNorm` is also supported on device, because many + # models use this layer. + batch, sentence_length, embedding_dim = 3, 4, 5 + embedding = torch.randn(batch, sentence_length, embedding_dim, dtype=torch.float16, device=device) + layer_norm = torch.nn.LayerNorm(embedding_dim, dtype=torch.float16, device=device) + _ = layer_norm(embedding) + return True + except Exception: + return False + + +@lru_cache +def is_torch_bf16_available_on_device(device: str) -> bool: + if not is_torch_available(): + return False + + import torch + + if device == "cuda": + return is_torch_bf16_gpu_available() + + if device == "hpu": + return True + + try: + x = torch.zeros(2, 2, dtype=torch.bfloat16, device=device) + _ = x @ x + return True + except Exception: + return False + + +@lru_cache +def is_torch_tf32_available() -> bool: + if not is_torch_available(): + return False + + import torch + + if is_torch_musa_available() and hasattr(torch, "musa"): + device_info = torch.musa.get_device_properties(torch.musa.current_device()) + if f"{device_info.major}{device_info.minor}" >= "22": + return True + return False + torch_version = getattr(torch, "version") + if not torch.cuda.is_available() or torch_version.cuda is None: + return False + if torch.cuda.get_device_properties(torch.cuda.current_device()).major < 8: + return False + return True + + +@lru_cache +def enable_tf32(enable: bool) -> None: + """ + Set TF32 mode using the appropriate PyTorch API. + For PyTorch 2.9+, uses the new fp32_precision API. + For older versions, uses the legacy allow_tf32 flags. + Args: + enable: Whether to enable TF32 mode + """ + import torch + + pytorch_version = version.parse(get_torch_version()) + if pytorch_version >= version.parse("2.9.0"): + precision_mode = "tf32" if enable else "ieee" + if hasattr(torch.backends, "fp32_precision"): + torch.backends.fp32_precision = precision_mode + else: + if is_torch_musa_available(): + if hasattr(torch.backends, "mudnn"): + torch.backends.mudnn.allow_tf32 = enable + else: + torch.backends.cuda.matmul.allow_tf32 = enable + torch.backends.cudnn.allow_tf32 = enable + + +@lru_cache +def is_torch_flex_attn_available() -> bool: + return is_torch_available() and version.parse(get_torch_version()) >= version.parse("2.5.0") + + +@lru_cache +def is_grouped_mm_available() -> bool: + return is_torch_available() and version.parse(get_torch_version()) >= version.parse("2.9.0") + + +@lru_cache +def is_kenlm_available() -> bool: + return _is_package_available("kenlm")[0] + + +@lru_cache +def is_kernels_available(MIN_VERSION: str = KERNELS_MIN_VERSION) -> bool: + is_available, kernels_version = _is_package_available("kernels", return_version=True) + return is_available and version.parse(kernels_version) >= version.parse(MIN_VERSION) + + +@lru_cache +def is_cv2_available() -> bool: + return _is_package_available("cv2")[0] + + +@lru_cache +def is_yt_dlp_available() -> bool: + return _is_package_available("yt_dlp")[0] + + +@lru_cache +def is_libcst_available() -> bool: + return _is_package_available("libcst")[0] + + +@lru_cache +def is_accelerate_available(min_version: str = ACCELERATE_MIN_VERSION) -> bool: + if not is_torch_available(): + return False + is_available, accelerate_version = _is_package_available("accelerate", return_version=True) + return is_available and version.parse(accelerate_version) >= version.parse(min_version) + + +@lru_cache +def is_triton_available(min_version: str = TRITON_MIN_VERSION) -> bool: + is_available, triton_version = _is_package_available("triton", return_version=True) + return is_available and version.parse(triton_version) >= version.parse(min_version) + + +@lru_cache +def is_hadamard_available() -> bool: + return _is_package_available("fast_hadamard_transform")[0] + + +@lru_cache +def is_hqq_available(min_version: str = HQQ_MIN_VERSION) -> bool: + is_available, hqq_version = _is_package_available("hqq", return_version=True) + return is_available and version.parse(hqq_version) >= version.parse(min_version) + + +@lru_cache +def is_pygments_available() -> bool: + return _is_package_available("pygments")[0] + + +@lru_cache +def is_torchvision_available() -> bool: + return is_vision_available() and is_torch_available() and _is_package_available("torchvision")[0] + + +@lru_cache +def is_torchvision_v2_available() -> bool: + return is_torchvision_available() + + +@lru_cache +def is_galore_torch_available() -> bool: + return _is_package_available("galore_torch")[0] + + +@lru_cache +def is_apollo_torch_available() -> bool: + return _is_package_available("apollo_torch")[0] + + +@lru_cache +def is_torch_optimi_available() -> bool: + return _is_package_available("optimi")[0] + + +@lru_cache +def is_lomo_available() -> bool: + return _is_package_available("lomo_optim")[0] + + +@lru_cache +def is_grokadamw_available() -> bool: + return _is_package_available("grokadamw")[0] + + +@lru_cache +def is_schedulefree_available(min_version: str = SCHEDULEFREE_MIN_VERSION) -> bool: + is_available, schedulefree_version = _is_package_available("schedulefree", return_version=True) + return is_available and version.parse(schedulefree_version) >= version.parse(min_version) + + +@lru_cache +def is_pyctcdecode_available() -> bool: + return _is_package_available("pyctcdecode")[0] + + +@lru_cache +def is_librosa_available() -> bool: + return _is_package_available("librosa")[0] + + +@lru_cache +def is_multipart_available() -> bool: + return _is_package_available("multipart")[0] + + +@lru_cache +def is_essentia_available() -> bool: + return _is_package_available("essentia")[0] + + +@lru_cache +def is_pydantic_available() -> bool: + return _is_package_available("pydantic")[0] + + +@lru_cache +def is_fastapi_available() -> bool: + return _is_package_available("fastapi")[0] + + +@lru_cache +def is_uvicorn_available() -> bool: + return _is_package_available("uvicorn")[0] + + +@lru_cache +def is_openai_available() -> bool: + return _is_package_available("openai")[0] + + +@lru_cache +def is_serve_available() -> bool: + return is_pydantic_available() and is_fastapi_available() and is_uvicorn_available() and is_openai_available() + + +@lru_cache +def is_pretty_midi_available() -> bool: + return _is_package_available("pretty_midi")[0] + + +@lru_cache +def is_mamba_ssm_available() -> bool: + return is_torch_cuda_available() and _is_package_available("mamba_ssm")[0] + + +@lru_cache +def is_mamba_2_ssm_available() -> bool: + is_available, mamba_ssm_version = _is_package_available("mamba_ssm", return_version=True) + return is_torch_cuda_available() and is_available and version.parse(mamba_ssm_version) >= version.parse("2.0.4") + + +@lru_cache +def is_flash_linear_attention_available(): + is_available, fla_version = _is_package_available("fla", return_version=True) + return is_torch_cuda_available() and is_available and version.parse(fla_version) >= version.parse("0.2.2") + + +@lru_cache +def is_causal_conv1d_available() -> bool: + return is_torch_cuda_available() and _is_package_available("causal_conv1d")[0] + + +@lru_cache +def is_xlstm_available() -> bool: + return is_torch_available() and _is_package_available("xlstm")[0] + + +@lru_cache +def is_mambapy_available() -> bool: + return is_torch_available() and _is_package_available("mambapy")[0] + + +@lru_cache +def is_peft_available() -> bool: + return _is_package_available("peft")[0] + + +@lru_cache +def is_bs4_available() -> bool: + return _is_package_available("bs4")[0] + + +@lru_cache +def is_coloredlogs_available() -> bool: + return _is_package_available("coloredlogs")[0] + + +@lru_cache +def is_onnx_available() -> bool: + return _is_package_available("onnx")[0] + + +@lru_cache +def is_flute_available() -> bool: + is_available, flute_version = _is_package_available("flute", return_version=True) + return is_available and version.parse(flute_version) >= version.parse("0.4.1") + + +@lru_cache +def is_g2p_en_available() -> bool: + return _is_package_available("g2p_en")[0] + + +@lru_cache +def is_torch_neuroncore_available(check_device=True) -> bool: + return is_torch_xla_available() and _is_package_available("torch_neuronx")[0] + + +@lru_cache +def is_torch_tensorrt_fx_available() -> bool: + return _is_package_available("torch_tensorrt")[0] and _is_package_available("torch_tensorrt.fx")[0] + + +@lru_cache +def is_datasets_available() -> bool: + return _is_package_available("datasets")[0] + + +@lru_cache +def is_detectron2_available() -> bool: + # We need this try/except block because otherwise after uninstalling the library, it stays available for some reason + # i.e. `import detectron2` and `import detectron2.modeling` still work, even though the library is uninstalled + # (the package exists but the objects are not reachable) - so here we explicitly try to import an object from it + try: + from detectron2.modeling import META_ARCH_REGISTRY # noqa + + return True + except Exception: + return False + + +@lru_cache +def is_rjieba_available() -> bool: + return _is_package_available("rjieba")[0] + + +@lru_cache +def is_psutil_available() -> bool: + return _is_package_available("psutil")[0] + + +@lru_cache +def is_py3nvml_available() -> bool: + return _is_package_available("py3nvml")[0] + + +@lru_cache +def is_sacremoses_available() -> bool: + return _is_package_available("sacremoses")[0] + + +@lru_cache +def is_apex_available() -> bool: + return _is_package_available("apex")[0] + + +@lru_cache +def is_aqlm_available() -> bool: + return _is_package_available("aqlm")[0] + + +@lru_cache +def is_vptq_available(min_version: str = VPTQ_MIN_VERSION) -> bool: + is_available, vptq_version = _is_package_available("vptq", return_version=True) + return is_available and version.parse(vptq_version) >= version.parse(min_version) + + +@lru_cache +def is_av_available() -> bool: + return _is_package_available("av")[0] + + +@lru_cache +def is_decord_available() -> bool: + return _is_package_available("decord")[0] + + +@lru_cache +def is_torchcodec_available() -> bool: + return _is_package_available("torchcodec")[0] + + +@lru_cache +def is_ninja_available() -> bool: + r""" + Code comes from *torch.utils.cpp_extension.is_ninja_available()*. Returns `True` if the + [ninja](https://ninja-build.org/) build system is available on the system, `False` otherwise. + """ + try: + subprocess.check_output(["ninja", "--version"]) + except Exception: + return False + else: + return True + + +@lru_cache +def is_bitsandbytes_available(min_version: str = BITSANDBYTES_MIN_VERSION) -> bool: + is_available, bitsandbytes_version = _is_package_available("bitsandbytes", return_version=True) + return is_available and version.parse(bitsandbytes_version) >= version.parse(min_version) + + +@lru_cache +def is_flash_attn_2_available() -> bool: + is_available, flash_attn_version = _is_package_available("flash_attn", return_version=True) + # FA4 is also distributed under "flash_attn", hence we need to check the naming here + is_available = is_available and "flash-attn" in [ + pkg.replace("_", "-") for pkg in PACKAGE_DISTRIBUTION_MAPPING["flash_attn"] + ] + + if not is_available or not (is_torch_cuda_available() or is_torch_mlu_available()): + return False + + # Only allow versions >= 2.3.3 to avoid very old legacy workarounds that are now 2+ years old + try: + return version.parse(flash_attn_version) >= version.parse("2.3.3") + except packaging.version.InvalidVersion: + return False + + +@lru_cache +def is_flash_attn_3_available() -> bool: + # Universally available under `flash_attn_interface` + is_available = _is_package_available("flash_attn_interface")[0] + # Resolving and ensuring the proper name of FA3 being associated + is_available = is_available and "flash-attn-3" in [ + pkg.replace("_", "-") for pkg in PACKAGE_DISTRIBUTION_MAPPING["flash_attn_interface"] + ] + return is_available and is_torch_cuda_available() + + +@lru_cache +def is_flash_attn_4_available() -> bool: + is_available = _is_package_available("flash_attn")[0] + # FA2 is also distributed under "flash_attn", hence we need to check the naming here + # NOTE: FA2 seems to distribute the `cute` subdirectory even if only FA2 has been installed + # -> check for the proper (normalized) distribution name + is_available = is_available and "flash-attn-4" in [ + pkg.replace("_", "-") for pkg in PACKAGE_DISTRIBUTION_MAPPING["flash_attn"] + ] + + return is_available and is_torch_cuda_available() + + +@lru_cache +def is_flash_attn_greater_or_equal(library_version: str) -> bool: + is_available, flash_attn_version = _is_package_available("flash_attn", return_version=True) + # FA4 is also distributed under "flash_attn", hence we need to check the naming here + is_available = is_available and "flash-attn" in [ + pkg.replace("_", "-") for pkg in PACKAGE_DISTRIBUTION_MAPPING["flash_attn"] + ] + + if not is_available: + return False + try: + return version.parse(flash_attn_version) >= version.parse(library_version) + except packaging.version.InvalidVersion: + return False + + +@lru_cache +def is_flash_attn_greater_or_equal_2_10() -> bool: + warnings.warn( + "`is_flash_attn_greater_or_equal_2_10` is deprecated and will be removed in v5.8. " + "Please use `is_flash_attn_greater_or_equal(library_version='2.1.0')` instead if needed.", + FutureWarning, + ) + return is_flash_attn_greater_or_equal("2.1.0") + + +@lru_cache +def is_huggingface_hub_greater_or_equal(library_version: str, accept_dev: bool = False) -> bool: + is_available, hub_version = _is_package_available("huggingface_hub", return_version=True) + if not is_available: + return False + + if accept_dev: + return version.parse(version.parse(hub_version).base_version) >= version.parse(library_version) + else: + return version.parse(hub_version) >= version.parse(library_version) + + +@lru_cache +def is_quanto_greater(library_version: str, accept_dev: bool = False) -> bool: + """ + Accepts a library version and returns True if the current version of the library is greater than or equal to the + given version. If `accept_dev` is True, it will also accept development versions (e.g. 2.7.0.dev20250320 matches + 2.7.0). + """ + if not is_optimum_quanto_available(): + return False + + _, quanto_version = _is_package_available("optimum.quanto", return_version=True) + if accept_dev: + return version.parse(version.parse(quanto_version).base_version) > version.parse(library_version) + else: + return version.parse(quanto_version) > version.parse(library_version) + + +@lru_cache +def is_torchdistx_available(): + return _is_package_available("torchdistx")[0] + + +@lru_cache +def is_faiss_available() -> bool: + return _is_package_available("faiss")[0] + + +@lru_cache +def is_fouroversix_available() -> bool: + return _is_package_available("fouroversix") + + +@lru_cache +def is_scipy_available() -> bool: + return _is_package_available("scipy")[0] + + +@lru_cache +def is_sklearn_available() -> bool: + return _is_package_available("sklearn")[0] + + +@lru_cache +def is_sentencepiece_available() -> bool: + return _is_package_available("sentencepiece")[0] + + +@lru_cache +def is_seqio_available() -> bool: + return _is_package_available("seqio")[0] + + +@lru_cache +def is_gguf_available(min_version: str = GGUF_MIN_VERSION) -> bool: + is_available, gguf_version = _is_package_available("gguf", return_version=True) + return is_available and version.parse(gguf_version) >= version.parse(min_version) + + +@lru_cache +def is_protobuf_available() -> bool: + return _is_package_available("google")[0] and _is_package_available("google.protobuf")[0] + + +@lru_cache +def is_fsdp_available(min_version: str = FSDP_MIN_VERSION) -> bool: + return is_torch_available() and version.parse(get_torch_version()) >= version.parse(min_version) + + +@lru_cache +def is_optimum_available() -> bool: + return _is_package_available("optimum")[0] + + +@lru_cache +def is_llm_awq_available() -> bool: + return _is_package_available("awq")[0] + + +@lru_cache +def is_auto_round_available(min_version: str = AUTOROUND_MIN_VERSION) -> bool: + is_available, auto_round_version = _is_package_available("auto_round", return_version=True) + return is_available and version.parse(auto_round_version) >= version.parse(min_version) + + +@lru_cache +def is_optimum_quanto_available(): + return is_optimum_available() and _is_package_available("optimum.quanto")[0] + + +@lru_cache +def is_quark_available() -> bool: + return _is_package_available("quark")[0] + + +@lru_cache +def is_fp_quant_available(): + is_available, fp_quant_version = _is_package_available("fp_quant", return_version=True) + return is_available and version.parse(fp_quant_version) >= version.parse("0.3.2") + + +@lru_cache +def is_qutlass_available(): + is_available, qutlass_version = _is_package_available("qutlass", return_version=True) + return is_available and version.parse(qutlass_version) >= version.parse("0.2.0") + + +@lru_cache +def is_compressed_tensors_available() -> bool: + return _is_package_available("compressed_tensors")[0] + + +@lru_cache +def is_sinq_available() -> bool: + return _is_package_available("sinq") + + +@lru_cache +def is_gptqmodel_available() -> bool: + return _is_package_available("gptqmodel")[0] + + +@lru_cache +def is_fbgemm_gpu_available() -> bool: + return _is_package_available("fbgemm_gpu")[0] + + +@lru_cache +def is_levenshtein_available() -> bool: + return _is_package_available("Levenshtein")[0] + + +@lru_cache +def is_optimum_neuron_available() -> bool: + return is_optimum_available() and _is_package_available("optimum.neuron")[0] + + +@lru_cache +def is_tokenizers_available() -> bool: + return _is_package_available("tokenizers")[0] + + +@lru_cache +def is_vision_available() -> bool: + try: + import PIL.Image # noqa: F401 + + return True + except ImportError: + return False + + +@lru_cache +def is_pytesseract_available() -> bool: + return _is_package_available("pytesseract")[0] and is_vision_available() + + +@lru_cache +def is_pytest_available() -> bool: + return _is_package_available("pytest")[0] + + +@lru_cache +def is_pytest_order_available() -> bool: + return is_pytest_available() and _is_package_available("pytest_order")[0] + + +@lru_cache +def is_spacy_available() -> bool: + return _is_package_available("spacy")[0] + + +@lru_cache +def is_pytorch_quantization_available() -> bool: + return _is_package_available("pytorch_quantization")[0] + + +@lru_cache +def is_pandas_available() -> bool: + return _is_package_available("pandas")[0] + + +@lru_cache +def is_soundfile_available() -> bool: + return _is_package_available("soundfile")[0] + + +@lru_cache +def is_timm_available() -> bool: + return is_vision_available() and is_torch_available() and _is_package_available("timm")[0] + + +@lru_cache +def is_natten_available() -> bool: + return _is_package_available("natten")[0] + + +@lru_cache +def is_nltk_available() -> bool: + return _is_package_available("nltk")[0] + + +@lru_cache +def is_numba_available() -> bool: + is_available = _is_package_available("numba")[0] + if not is_available: + return False + + numpy_available, numpy_version = _is_package_available("numpy", return_version=True) + return not numpy_available or version.parse(numpy_version) < version.parse("2.2.0") + + +@lru_cache +def is_torchaudio_available() -> bool: + return is_torch_available() and _is_package_available("torchaudio")[0] + + +@lru_cache +def is_torchao_available(min_version: str = TORCHAO_MIN_VERSION) -> bool: + if not is_torch_available(): + return False + is_available, torchao_version = _is_package_available("torchao", return_version=True) + return is_available and version.parse(torchao_version) >= version.parse(min_version) + + +@lru_cache +def is_speech_available() -> bool: + # For now this depends on torchaudio but the exact dependency might evolve in the future. + return is_torchaudio_available() + + +@lru_cache +def is_spqr_available() -> bool: + return _is_package_available("spqr_quant")[0] + + +@lru_cache +def is_phonemizer_available() -> bool: + return _is_package_available("phonemizer")[0] + + +@lru_cache +def is_uroman_available() -> bool: + return _is_package_available("uroman")[0] + + +@lru_cache +def is_sudachi_available() -> bool: + return _is_package_available("sudachipy")[0] + + +@lru_cache +def is_sudachi_projection_available() -> bool: + is_available, sudachipy_version = _is_package_available("sudachipy", return_version=True) + return is_available and version.parse(sudachipy_version) >= version.parse("0.6.8") + + +@lru_cache +def is_jumanpp_available() -> bool: + return _is_package_available("rhoknp")[0] and shutil.which("jumanpp") is not None + + +@lru_cache +def is_cython_available() -> bool: + return _is_package_available("pyximport")[0] + + +@lru_cache +def is_jinja_available() -> bool: + return _is_package_available("jinja2")[0] + + +@lru_cache +def is_jmespath_available() -> bool: + return _is_package_available("jmespath")[0] + + +@lru_cache +def is_mlx_available() -> bool: + return _is_package_available("mlx")[0] + + +@lru_cache +def is_num2words_available() -> bool: + return _is_package_available("num2words")[0] + + +@lru_cache +def is_tiktoken_available(with_blobfile: bool = True) -> bool: + if not _is_package_available("tiktoken")[0]: + return False + return with_blobfile and _is_package_available("blobfile")[0] or True + + +@lru_cache +def is_liger_kernel_available() -> bool: + is_available, liger_kernel_version = _is_package_available("liger_kernel", return_version=True) + return is_available and version.parse(liger_kernel_version) >= version.parse("0.3.0") + + +@lru_cache +def is_rich_available() -> bool: + return _is_package_available("rich")[0] + + +@lru_cache +def is_matplotlib_available() -> bool: + return _is_package_available("matplotlib")[0] + + +@lru_cache +def is_mistral_common_available() -> bool: + return is_vision_available() and _is_package_available("mistral_common")[0] + + +@lru_cache +def is_opentelemetry_available() -> bool: + try: + return _is_package_available("opentelemetry")[0] and version.parse( + importlib.metadata.version("opentelemetry-api") + ) >= version.parse("1.30.0") + except Exception as _: + return False + + +@lru_cache +def is_pynvml_available() -> bool: + return _is_package_available("pynvml")[0] + + +def check_torch_load_is_safe() -> None: + if not is_torch_greater_or_equal("2.6"): + raise ValueError( + "Due to a serious vulnerability issue in `torch.load`, even with `weights_only=True`, we now require users " + "to upgrade torch to at least v2.6 in order to use the function. This version restriction does not apply " + "when loading files with safetensors." + "\nSee the vulnerability report here https://nvd.nist.gov/vuln/detail/CVE-2025-32434" + ) + + +def torch_only_method(fn: Callable) -> Callable: + def wrapper(*args, **kwargs): + if not is_torch_available(): + raise ImportError("You need to install pytorch to use this method or class") + else: + return fn(*args, **kwargs) + + return wrapper + + +def is_torch_deterministic() -> bool: + """ + Check whether pytorch uses deterministic algorithms by looking if torch.set_deterministic_debug_mode() is set to 1 or 2" + """ + if is_torch_available(): + import torch + + if torch.get_deterministic_debug_mode() == 0: + return False + else: + return True + + return False + + +@lru_cache +def get_torch_major_and_minor_version() -> str: + torch_version = get_torch_version() + if torch_version == "N/A": + return "N/A" + parsed_version = version.parse(torch_version) + return str(parsed_version.major) + "." + str(parsed_version.minor) + + +def is_torchdynamo_compiling() -> bool: + # Importing torch._dynamo causes issues with PyTorch profiler (https://github.com/pytorch/pytorch/issues/130622) + # hence rather relying on `torch.compiler.is_compiling()` when possible (torch>=2.3) + try: + import torch + + if hasattr(torch, "compiler"): + return torch.compiler.is_compiling() + return False + except Exception: + return False + + +def is_torchdynamo_exporting() -> bool: + try: + import torch + + if hasattr(torch, "compiler"): + return torch.compiler.is_exporting() + return False + except Exception: + return False + + +def is_torch_fx_proxy(x) -> bool: + try: + import torch.fx + + return isinstance(x, torch.fx.Proxy) + except Exception: + return False + + +def is_fake_tensor(x) -> bool: + try: + import torch + + return isinstance(x, getattr(torch, "_subclasses").FakeTensor) + except Exception: + return False + + +def is_jax_jitting(x): + """returns True if we are inside of `jax.jit` context, False otherwise. + + When a torch model is being compiled with `jax.jit` using torchax, + the tensor that goes through the model would be an instance of + `torchax.tensor.Tensor`, which is a tensor subclass. This tensor has + a `jax` method to return the inner Jax array + (https://github.com/google/torchax/blob/13ce870a1d9adb2430333c27bb623469e3aea34e/torchax/tensor.py#L134). + Here we use ducktyping to detect if the inner jax array is a jax Tracer + then we are in tracing context. (See more at: https://github.com/jax-ml/jax/discussions/9241) + + Args: + x: torch.Tensor + + Returns: + bool: whether we are inside of jax jit tracing. + """ + + if not hasattr(x, "jax"): + return False + try: + import jax + + return isinstance(x.jax(), getattr(jax, "core").Tracer) + except Exception: + return False + + +def is_jit_tracing() -> bool: + try: + import torch + + return torch.jit.is_tracing() + except Exception: + return False + + +def is_cuda_stream_capturing() -> bool: + try: + import torch + + return torch.cuda.is_current_stream_capturing() + except Exception: + return False + + +def is_tracing(tensor=None) -> bool: + """Checks whether we are tracing a graph with dynamo (compile or export), torch.jit, torch.fx, jax.jit (with torchax) or + CUDA stream capturing or FakeTensor""" + + # Note that `is_torchdynamo_compiling` checks both compiling and exporting (the export check is stricter and + # only checks export) + _is_tracing = is_torchdynamo_compiling() or is_jit_tracing() or is_cuda_stream_capturing() + if tensor is not None: + _is_tracing |= is_torch_fx_proxy(tensor) + _is_tracing |= is_fake_tensor(tensor) + _is_tracing |= is_jax_jitting(tensor) + + return _is_tracing + + +def torch_compilable_check(cond: Any, msg: str | Callable[[], str], error_type: type[Exception] = ValueError) -> None: + """ + Combines the functionalities of `torch._check`, `torch._check_with` and `torch._check_tensor_all_with` to provide a + unified way to perform checks that are compatible with TorchDynamo (torch.compile & torch.export). + + The advantage of using `torch._check(cond, msg, error_type)` over `if cond: raise error_type(msg)` is that the former + works as a truthfulness hint for TorchDynamo, instead of failing with a data-dependent control flow error during compilation. + + All checks using this method can be disabled in production environments by setting `TRANSFORMERS_DISABLE_TORCH_CHECK=1`. + + Args: + cond (`bool`, `torch.Tensor` or `Callable[[], bool | torch.Tensor]`): The condition to check. + msg (`str` or `Callable[[], str]`): The error message to display if the condition is not met. + error_type (`type[Exception]`, *optional*, defaults to `ValueError`): The type of error to raise if the condition is not met. + + Raises: + error_type: If the condition is not met. + """ + if os.getenv("TRANSFORMERS_DISABLE_TORCH_CHECK", "0") == "1": + return + + import torch + + if not callable(msg): + # torch._check requires msg to be a callable but we want to keep the API simple for users + def msg_callable(): + return msg + else: + msg_callable = msg + + if callable(cond): + cond = cond() + + # These checks are also compiler hints for TorchDynamo telling + # it that the condition is expected to be True during compilation + if isinstance(cond, torch.Tensor): + torch._check_tensor_all_with(error_type, cond, msg_callable) + else: + torch._check_with(error_type, cond, msg_callable) + + +@lru_cache +def is_ipython_available() -> bool: + return importlib.util.find_spec("IPython") is not None + + +@lru_cache +def is_in_notebook() -> bool: + try: + # Check if we are running inside Marimo + if "marimo" in sys.modules: + return True + # Test adapted from tqdm.autonotebook: https://github.com/tqdm/tqdm/blob/master/tqdm/autonotebook.py + get_ipython = sys.modules["IPython"].get_ipython + if "IPKernelApp" not in get_ipython().config: + raise ImportError("console") + # Removed the lines to include VSCode + if "DATABRICKS_RUNTIME_VERSION" in os.environ and os.environ["DATABRICKS_RUNTIME_VERSION"] < "11.0": + # Databricks Runtime 11.0 and above uses IPython kernel by default so it should be compatible with Jupyter notebook + # https://docs.microsoft.com/en-us/azure/databricks/notebooks/ipython-kernel + raise ImportError("databricks") + + return importlib.util.find_spec("IPython") is not None + except (AttributeError, ImportError, KeyError): + return False + + +def is_sagemaker_dp_enabled() -> bool: + # Get the sagemaker specific env variable. + sagemaker_params = os.getenv("SM_FRAMEWORK_PARAMS", "{}") + try: + # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". + sagemaker_params = json.loads(sagemaker_params) + if not sagemaker_params.get("sagemaker_distributed_dataparallel_enabled", False): + return False + except json.JSONDecodeError: + return False + # Lastly, check if the `smdistributed` module is present. + return _is_package_available("smdistributed")[0] + + +def is_sagemaker_mp_enabled() -> bool: + # Get the sagemaker specific mp parameters from smp_options variable. + smp_options = os.getenv("SM_HP_MP_PARAMETERS", "{}") + try: + # Parse it and check the field "partitions" is included, it is required for model parallel. + smp_options = json.loads(smp_options) + if "partitions" not in smp_options: + return False + except json.JSONDecodeError: + return False + + # Get the sagemaker specific framework parameters from mpi_options variable. + mpi_options = os.getenv("SM_FRAMEWORK_PARAMS", "{}") + try: + # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". + mpi_options = json.loads(mpi_options) + if not mpi_options.get("sagemaker_mpi_enabled", False): + return False + except json.JSONDecodeError: + return False + # Lastly, check if the `smdistributed` module is present. + return _is_package_available("smdistributed")[0] + + +def is_training_run_on_sagemaker() -> bool: + return "SAGEMAKER_JOB_NAME" in os.environ + + +# docstyle-ignore +AV_IMPORT_ERROR = """ +{0} requires the PyAv library but it was not found in your environment. You can install it with: +``` +pip install av +``` +Please note that you may need to restart your runtime after installation. +""" + +# docstyle-ignore +YT_DLP_IMPORT_ERROR = """ +{0} requires the YT-DLP library but it was not found in your environment. You can install it with: +``` +pip install yt-dlp +``` +Please note that you may need to restart your runtime after installation. +""" + +DECORD_IMPORT_ERROR = """ +{0} requires the PyAv library but it was not found in your environment. You can install it with: +``` +pip install decord +``` +Please note that you may need to restart your runtime after installation. +""" + +TORCHCODEC_IMPORT_ERROR = """ +{0} requires the TorchCodec (https://github.com/pytorch/torchcodec) library, but it was not found in your environment. You can install it with: +``` +pip install torchcodec +``` +Please note that you may need to restart your runtime after installation. +""" + +# docstyle-ignore +CV2_IMPORT_ERROR = """ +{0} requires the OpenCV library but it was not found in your environment. You can install it with: +``` +pip install opencv-python +``` +Please note that you may need to restart your runtime after installation. +""" + + +# docstyle-ignore +DATASETS_IMPORT_ERROR = """ +{0} requires the 🤗 Datasets library but it was not found in your environment. You can install it with: +``` +pip install datasets +``` +In a notebook or a colab, you can install it by executing a cell with +``` +!pip install datasets +``` +then restarting your kernel. + +Note that if you have a local folder named `datasets` or a local python file named `datasets.py` in your current +working directory, python may try to import this instead of the 🤗 Datasets library. You should rename this folder or +that python file if that's the case. Please note that you may need to restart your runtime after installation. +""" + + +# docstyle-ignore +TOKENIZERS_IMPORT_ERROR = """ +{0} requires the 🤗 Tokenizers library but it was not found in your environment. You can install it with: +``` +pip install tokenizers +``` +In a notebook or a colab, you can install it by executing a cell with +``` +!pip install tokenizers +``` +Please note that you may need to restart your runtime after installation. +""" + + +# docstyle-ignore +SENTENCEPIECE_IMPORT_ERROR = """ +{0} requires the SentencePiece library but it was not found in your environment. Check out the instructions on the +installation page of its repo: https://github.com/google/sentencepiece#installation and follow the ones +that match your environment. Please note that you may need to restart your runtime after installation. +""" + + +# docstyle-ignore +PROTOBUF_IMPORT_ERROR = """ +{0} requires the protobuf library but it was not found in your environment. Check out the instructions on the +installation page of its repo: https://github.com/protocolbuffers/protobuf/tree/master/python#installation and follow the ones +that match your environment. Please note that you may need to restart your runtime after installation. +""" + + +# docstyle-ignore +FAISS_IMPORT_ERROR = """ +{0} requires the faiss library but it was not found in your environment. Check out the instructions on the +installation page of its repo: https://github.com/facebookresearch/faiss/blob/master/INSTALL.md and follow the ones +that match your environment. Please note that you may need to restart your runtime after installation. +""" + + +# docstyle-ignore +PYTORCH_IMPORT_ERROR = """ +{0} requires the PyTorch library but it was not found in your environment. Check out the instructions on the +installation page: https://pytorch.org/get-started/locally/ and follow the ones that match your environment. +Please note that you may need to restart your runtime after installation. +""" + + +# docstyle-ignore +TORCHVISION_IMPORT_ERROR = """ +{0} requires the Torchvision library but it was not found in your environment. Check out the instructions on the +installation page: https://pytorch.org/get-started/locally/ and follow the ones that match your environment. +Please note that you may need to restart your runtime after installation. +""" + +# docstyle-ignore +BS4_IMPORT_ERROR = """ +{0} requires the Beautiful Soup library but it was not found in your environment. You can install it with pip: +`pip install beautifulsoup4`. Please note that you may need to restart your runtime after installation. +""" + + +# docstyle-ignore +SKLEARN_IMPORT_ERROR = """ +{0} requires the scikit-learn library but it was not found in your environment. You can install it with: +``` +pip install -U scikit-learn +``` +In a notebook or a colab, you can install it by executing a cell with +``` +!pip install -U scikit-learn +``` +Please note that you may need to restart your runtime after installation. +""" + + +# docstyle-ignore +DETECTRON2_IMPORT_ERROR = """ +{0} requires the detectron2 library but it was not found in your environment. Check out the instructions on the +installation page: https://github.com/facebookresearch/detectron2/blob/master/INSTALL.md and follow the ones +that match your environment. Please note that you may need to restart your runtime after installation. +""" + + +LEVENSHTEIN_IMPORT_ERROR = """ +{0} requires the python-Levenshtein library but it was not found in your environment. You can install it with pip: `pip +install python-Levenshtein`. Please note that you may need to restart your runtime after installation. +""" + +# docstyle-ignore +G2P_EN_IMPORT_ERROR = """ +{0} requires the g2p-en library but it was not found in your environment. You can install it with pip: +`pip install g2p-en`. Please note that you may need to restart your runtime after installation. +""" + +# docstyle-ignore +PYTORCH_QUANTIZATION_IMPORT_ERROR = """ +{0} requires the pytorch-quantization library but it was not found in your environment. You can install it with pip: +`pip install pytorch-quantization --extra-index-url https://pypi.ngc.nvidia.com` +Please note that you may need to restart your runtime after installation. +""" + +# docstyle-ignore +TORCHAUDIO_IMPORT_ERROR = """ +{0} requires the torchaudio library but it was not found in your environment. Please install it and restart your +runtime. +""" + +# docstyle-ignore +PANDAS_IMPORT_ERROR = """ +{0} requires the pandas library but it was not found in your environment. You can install it with pip as +explained here: https://pandas.pydata.org/pandas-docs/stable/getting_started/install.html. +Please note that you may need to restart your runtime after installation. +""" + + +# docstyle-ignore +PHONEMIZER_IMPORT_ERROR = """ +{0} requires the phonemizer library but it was not found in your environment. You can install it with pip: +`pip install phonemizer`. Please note that you may need to restart your runtime after installation. +""" +# docstyle-ignore +UROMAN_IMPORT_ERROR = """ +{0} requires the uroman library but it was not found in your environment. You can install it with pip: +`pip install uroman`. Please note that you may need to restart your runtime after installation. +""" + + +# docstyle-ignore +SACREMOSES_IMPORT_ERROR = """ +{0} requires the sacremoses library but it was not found in your environment. You can install it with pip: +`pip install sacremoses`. Please note that you may need to restart your runtime after installation. +""" + +# docstyle-ignore +SCIPY_IMPORT_ERROR = """ +{0} requires the scipy library but it was not found in your environment. You can install it with pip: +`pip install scipy`. Please note that you may need to restart your runtime after installation. +""" + +# docstyle-ignore +SPEECH_IMPORT_ERROR = """ +{0} requires the torchaudio library but it was not found in your environment. You can install it with pip: +`pip install torchaudio`. Please note that you may need to restart your runtime after installation. +""" + +# docstyle-ignore +TIMM_IMPORT_ERROR = """ +{0} requires the timm library but it was not found in your environment. You can install it with pip: +`pip install timm`. Please note that you may need to restart your runtime after installation. +""" + +# docstyle-ignore +NATTEN_IMPORT_ERROR = """ +{0} requires the natten library but it was not found in your environment. You can install it by referring to: +shi-labs.com/natten . You can also install it with pip (may take longer to build): +`pip install natten`. Please note that you may need to restart your runtime after installation. +""" + +NUMEXPR_IMPORT_ERROR = """ +{0} requires the numexpr library but it was not found in your environment. You can install it by referring to: +https://numexpr.readthedocs.io/en/latest/index.html. +""" + + +# docstyle-ignore +NLTK_IMPORT_ERROR = """ +{0} requires the NLTK library but it was not found in your environment. You can install it by referring to: +https://www.nltk.org/install.html. Please note that you may need to restart your runtime after installation. +""" + + +# docstyle-ignore +VISION_IMPORT_ERROR = """ +{0} requires the PIL library but it was not found in your environment. You can install it with pip: +`pip install pillow`. Please note that you may need to restart your runtime after installation. +""" + +# docstyle-ignore +PYDANTIC_IMPORT_ERROR = """ +{0} requires the pydantic library but it was not found in your environment. You can install it with pip: +`pip install pydantic`. Please note that you may need to restart your runtime after installation. +""" + +# docstyle-ignore +FASTAPI_IMPORT_ERROR = """ +{0} requires the fastapi library but it was not found in your environment. You can install it with pip: +`pip install fastapi`. Please note that you may need to restart your runtime after installation. +""" + +# docstyle-ignore +UVICORN_IMPORT_ERROR = """ +{0} requires the uvicorn library but it was not found in your environment. You can install it with pip: +`pip install uvicorn`. Please note that you may need to restart your runtime after installation. +""" + +# docstyle-ignore +OPENAI_IMPORT_ERROR = """ +{0} requires the openai library but it was not found in your environment. You can install it with pip: +`pip install openai`. Please note that you may need to restart your runtime after installation. +""" + +# docstyle-ignore +PYTESSERACT_IMPORT_ERROR = """ +{0} requires the PyTesseract library but it was not found in your environment. You can install it with pip: +`pip install pytesseract`. Please note that you may need to restart your runtime after installation. +""" + +# docstyle-ignore +PYCTCDECODE_IMPORT_ERROR = """ +{0} requires the pyctcdecode library but it was not found in your environment. You can install it with pip: +`pip install pyctcdecode`. Please note that you may need to restart your runtime after installation. +""" + +# docstyle-ignore +ACCELERATE_IMPORT_ERROR = """ +{0} requires the accelerate library >= {ACCELERATE_MIN_VERSION} it was not found in your environment. +You can install or update it with pip: `pip install --upgrade accelerate`. Please note that you may need to restart your +runtime after installation. +""" + +# docstyle-ignore +ESSENTIA_IMPORT_ERROR = """ +{0} requires essentia library. But that was not found in your environment. You can install them with pip: +`pip install essentia==2.1b6.dev1034` +Please note that you may need to restart your runtime after installation. +""" + +# docstyle-ignore +LIBROSA_IMPORT_ERROR = """ +{0} requires the librosa library. But that was not found in your environment. You can install them with pip: +`pip install librosa` +Please note that you may need to restart your runtime after installation. +""" + +# docstyle-ignore +PRETTY_MIDI_IMPORT_ERROR = """ +{0} requires the pretty_midi library. But that was not found in your environment. You can install them with pip: +`pip install pretty_midi` +Please note that you may need to restart your runtime after installation. +""" + + +CYTHON_IMPORT_ERROR = """ +{0} requires the Cython library but it was not found in your environment. You can install it with pip: `pip install +Cython`. Please note that you may need to restart your runtime after installation. +""" + +RJIEBA_IMPORT_ERROR = """ +{0} requires the rjieba library but it was not found in your environment. You can install it with pip: `pip install +rjieba`. Please note that you may need to restart your runtime after installation. +""" + +PEFT_IMPORT_ERROR = """ +{0} requires the peft library but it was not found in your environment. You can install it with pip: `pip install +peft`. Please note that you may need to restart your runtime after installation. +""" + +JINJA_IMPORT_ERROR = """ +{0} requires the jinja library but it was not found in your environment. You can install it with pip: `pip install +jinja2`. Please note that you may need to restart your runtime after installation. +""" + +RICH_IMPORT_ERROR = """ +{0} requires the rich library but it was not found in your environment. You can install it with pip: `pip install +rich`. Please note that you may need to restart your runtime after installation. +""" + +MISTRAL_COMMON_IMPORT_ERROR = """ +{0} requires the mistral-common library but it was not found in your environment. You can install it with pip: `pip install mistral-common`. Please note that you may need to restart your runtime after installation. +""" + + +BACKENDS_MAPPING = OrderedDict( + [ + ("av", (is_av_available, AV_IMPORT_ERROR)), + ("bs4", (is_bs4_available, BS4_IMPORT_ERROR)), + ("cv2", (is_cv2_available, CV2_IMPORT_ERROR)), + ("datasets", (is_datasets_available, DATASETS_IMPORT_ERROR)), + ("decord", (is_decord_available, DECORD_IMPORT_ERROR)), + ("detectron2", (is_detectron2_available, DETECTRON2_IMPORT_ERROR)), + ("essentia", (is_essentia_available, ESSENTIA_IMPORT_ERROR)), + ("faiss", (is_faiss_available, FAISS_IMPORT_ERROR)), + ("g2p_en", (is_g2p_en_available, G2P_EN_IMPORT_ERROR)), + ("pandas", (is_pandas_available, PANDAS_IMPORT_ERROR)), + ("phonemizer", (is_phonemizer_available, PHONEMIZER_IMPORT_ERROR)), + ("uroman", (is_uroman_available, UROMAN_IMPORT_ERROR)), + ("pretty_midi", (is_pretty_midi_available, PRETTY_MIDI_IMPORT_ERROR)), + ("levenshtein", (is_levenshtein_available, LEVENSHTEIN_IMPORT_ERROR)), + ("librosa", (is_librosa_available, LIBROSA_IMPORT_ERROR)), + ("protobuf", (is_protobuf_available, PROTOBUF_IMPORT_ERROR)), + ("pyctcdecode", (is_pyctcdecode_available, PYCTCDECODE_IMPORT_ERROR)), + ("pytesseract", (is_pytesseract_available, PYTESSERACT_IMPORT_ERROR)), + ("sacremoses", (is_sacremoses_available, SACREMOSES_IMPORT_ERROR)), + ("pytorch_quantization", (is_pytorch_quantization_available, PYTORCH_QUANTIZATION_IMPORT_ERROR)), + ("sentencepiece", (is_sentencepiece_available, SENTENCEPIECE_IMPORT_ERROR)), + ("sklearn", (is_sklearn_available, SKLEARN_IMPORT_ERROR)), + ("speech", (is_speech_available, SPEECH_IMPORT_ERROR)), + ("timm", (is_timm_available, TIMM_IMPORT_ERROR)), + ("torchaudio", (is_torchaudio_available, TORCHAUDIO_IMPORT_ERROR)), + ("natten", (is_natten_available, NATTEN_IMPORT_ERROR)), + ("nltk", (is_nltk_available, NLTK_IMPORT_ERROR)), + ("tokenizers", (is_tokenizers_available, TOKENIZERS_IMPORT_ERROR)), + ("torch", (is_torch_available, PYTORCH_IMPORT_ERROR)), + ("torchvision", (is_torchvision_available, TORCHVISION_IMPORT_ERROR)), + ("torchcodec", (is_torchcodec_available, TORCHCODEC_IMPORT_ERROR)), + ("vision", (is_vision_available, VISION_IMPORT_ERROR)), + ("scipy", (is_scipy_available, SCIPY_IMPORT_ERROR)), + ("accelerate", (is_accelerate_available, ACCELERATE_IMPORT_ERROR)), + ("cython", (is_cython_available, CYTHON_IMPORT_ERROR)), + ("rjieba", (is_rjieba_available, RJIEBA_IMPORT_ERROR)), + ("peft", (is_peft_available, PEFT_IMPORT_ERROR)), + ("jinja", (is_jinja_available, JINJA_IMPORT_ERROR)), + ("yt_dlp", (is_yt_dlp_available, YT_DLP_IMPORT_ERROR)), + ("rich", (is_rich_available, RICH_IMPORT_ERROR)), + ("pydantic", (is_pydantic_available, PYDANTIC_IMPORT_ERROR)), + ("fastapi", (is_fastapi_available, FASTAPI_IMPORT_ERROR)), + ("uvicorn", (is_uvicorn_available, UVICORN_IMPORT_ERROR)), + ("openai", (is_openai_available, OPENAI_IMPORT_ERROR)), + ("mistral-common", (is_mistral_common_available, MISTRAL_COMMON_IMPORT_ERROR)), + ] +) + + +def requires_backends(obj, backends): + """ + Method that automatically raises in case the specified backends are not available. It is often used during class + initialization to ensure the required dependencies are installed: + + ```py + requires_backends(self, ["torch"]) + ``` + + The backends should be defined in the `BACKEND_MAPPING` defined in `transformers.utils.import_utils`. + + Args: + obj: object to be checked + backends: list or tuple of backends to check. + """ + if not isinstance(backends, list | tuple): + backends = [backends] + + name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__ + + failed = [] + for backend in backends: + if isinstance(backend, Backend): + available, msg = backend.is_satisfied, backend.error_message + else: + available, msg = BACKENDS_MAPPING[backend] + + if not available(): + failed.append(msg.format(name)) + + if failed: + raise ImportError("".join(failed)) + + +class DummyObject(type): + """ + Metaclass for the dummy objects. Any class inheriting from it will return the ImportError generated by + `requires_backend` each time a user tries to access any method of that class. + """ + + is_dummy = True + + def __getattribute__(cls, key): + if (key.startswith("_") and key != "_from_config") or key == "is_dummy" or key == "mro" or key == "call": + return super().__getattribute__(key) + requires_backends(cls, cls._backends) + + +BACKENDS_T = frozenset[str] +IMPORT_STRUCTURE_T = dict[BACKENDS_T, dict[str, set[str]]] + + +class _LazyModule(ModuleType): + """ + Module class that surfaces all objects but only performs associated imports when the objects are requested. + """ + + # Very heavily inspired by optuna.integration._IntegrationModule + # https://github.com/optuna/optuna/blob/master/optuna/integration/__init__.py + def __init__( + self, + name: str, + module_file: str, + import_structure: IMPORT_STRUCTURE_T, + module_spec: importlib.machinery.ModuleSpec | None = None, + extra_objects: dict[str, object] | None = None, + explicit_import_shortcut: dict[str, list[str]] | None = None, + ): + super().__init__(name) + + self._object_missing_backend = {} + self._explicit_import_shortcut = explicit_import_shortcut if explicit_import_shortcut else {} + + if any(isinstance(key, frozenset) for key in import_structure): + self._modules = set() + self._class_to_module = {} + self.__all__ = [] + + _import_structure = {} + + for backends, module in import_structure.items(): + missing_backends = [] + + # This ensures that if a module is importable, then all other keys of the module are importable. + # As an example, in module.keys() we might have the following: + # + # dict_keys(['models.nllb_moe.configuration_nllb_moe', 'models.sew_d.configuration_sew_d']) + # + # with this, we don't only want to be able to import these explicitly, we want to be able to import + # every intermediate module as well. Therefore, this is what is returned: + # + # { + # 'models.nllb_moe.configuration_nllb_moe', + # 'models.sew_d.configuration_sew_d', + # 'models', + # 'models.sew_d', 'models.nllb_moe' + # } + + module_keys = set( + chain(*[[k.rsplit(".", i)[0] for i in range(k.count(".") + 1)] for k in list(module.keys())]) + ) + + for backend in backends: + if backend in BACKENDS_MAPPING: + callable, _ = BACKENDS_MAPPING[backend] + else: + if any(key in backend for key in ["=", "<", ">"]): + backend = Backend(backend) + callable = backend.is_satisfied + else: + raise ValueError( + f"Backend should be defined in the BACKENDS_MAPPING. Offending backend: {backend}" + ) + + try: + if not callable(): + missing_backends.append(backend) + except (ModuleNotFoundError, RuntimeError): + missing_backends.append(backend) + + self._modules = self._modules.union(module_keys) + + for key, values in module.items(): + if missing_backends: + self._object_missing_backend[key] = missing_backends + + for value in values: + self._class_to_module[value] = key + if missing_backends: + self._object_missing_backend[value] = missing_backends + _import_structure.setdefault(key, []).extend(values) + + # Needed for autocompletion in an IDE + self.__all__.extend(module_keys | set(chain(*module.values()))) + + self.__file__ = module_file + self.__spec__ = module_spec + self.__path__ = [os.path.dirname(module_file)] + self._objects = {} if extra_objects is None else extra_objects + self._name = name + self._import_structure = _import_structure + + # This can be removed once every exportable object has a `require()` require. + else: + self._modules = set(import_structure.keys()) + self._class_to_module = {} + for key, values in import_structure.items(): + for value in values: + self._class_to_module[value] = key + # Needed for autocompletion in an IDE + self.__all__ = list(import_structure.keys()) + list(chain(*import_structure.values())) + self.__file__ = module_file + self.__spec__ = module_spec + self.__path__ = [os.path.dirname(module_file)] + self._objects = {} if extra_objects is None else extra_objects + self._name = name + self._import_structure = import_structure + + # Needed for autocompletion in an IDE + def __dir__(self): + result = list(super().__dir__()) + # The elements of self.__all__ that are submodules may or may not be in the dir already, depending on whether + # they have been accessed or not. So we only add the elements of self.__all__ that are not already in the dir. + for attr in self.__all__: + if attr not in result: + result.append(attr) + return result + + def __getattr__(self, name: str) -> Any: + if name in self._objects: + return self._objects[name] + if name in self._object_missing_backend: + missing_backends = self._object_missing_backend[name] + + # Backward-compat fallback: before the image processor refactoring, the base + # `ImageProcessor` name referred to the PIL/slow backend. After the refactoring + # it refers to the TorchvisionBackend (which requires torchvision). So if torchvision + # is not installed, transparently fall back to `ImageProcessorPil` and warn once. + if "torchvision" in missing_backends and name.endswith("ImageProcessor"): + pil_name = f"{name}Pil" + if pil_name in self._class_to_module and pil_name not in self._object_missing_backend: + try: + pil_module = self._get_module(self._class_to_module[pil_name]) + pil_value = getattr(pil_module, pil_name) + logger.warning_once( + f"`{name}` requires torchvision (not installed); falling back to `{pil_name}` " + f"for backward compatibility. Install torchvision to use the default backend, " + f"or import `{pil_name}` directly to silence this warning." + ) + setattr(self, name, pil_value) + return pil_value + except Exception as e: + logger.debug(f"Could not load PIL fallback {pil_name}: {e}") + + class Placeholder(metaclass=DummyObject): + _backends = missing_backends + + def __init__(self, *args, **kwargs): + requires_backends(self, missing_backends) + + def call(self, *args, **kwargs): + pass + + Placeholder.__name__ = name + + if name not in self._class_to_module: + module_name = f"transformers.{name}" + else: + module_name = self._class_to_module[name] + if not module_name.startswith("transformers."): + module_name = f"transformers.{module_name}" + + Placeholder.__module__ = module_name + + value = Placeholder + elif name in self._class_to_module: + try: + module = self._get_module(self._class_to_module[name]) + value = getattr(module, name) + except (ModuleNotFoundError, RuntimeError, AttributeError) as e: + # V5: If trying to import a *TokenizerFast symbol, transparently fall back to the + # non-Fast symbol from the same module when available. This lets us keep only one + # backend tokenizer class while preserving legacy public names. + if name.endswith("TokenizerFast"): + fallback_name = name[:-4] + # Prefer importing the module that declares the fallback symbol if known + try: + if fallback_name in self._class_to_module: + fb_module = self._get_module(self._class_to_module[fallback_name]) + fallback_value = getattr(fb_module, fallback_name) + else: + module = self._get_module(self._class_to_module[name]) + fallback_value = getattr(module, fallback_name) + setattr(self, fallback_name, fallback_value) + value = fallback_value + except Exception: + # If we can't find the fallback here, try converter logic as a last resort + # before giving up + value = None + # Try converter mapping for Fast tokenizers that don't exist + if value is None and name.endswith("TokenizerFast"): + lookup_name = name[:-4] + try: + from ..convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS + + if lookup_name in SLOW_TO_FAST_CONVERTERS: + converter_class = SLOW_TO_FAST_CONVERTERS[lookup_name] + converter_base_name = converter_class.__name__.replace("Converter", "") + preferred_tokenizer_name = f"{converter_base_name}Tokenizer" + + candidate_names = [preferred_tokenizer_name] + for tokenizer_name, tokenizer_converter in SLOW_TO_FAST_CONVERTERS.items(): + if tokenizer_converter is converter_class and tokenizer_name != lookup_name: + if tokenizer_name not in candidate_names: + candidate_names.append(tokenizer_name) + + # Try to import the preferred candidate directly + import importlib + + for candidate_name in candidate_names: + base_tokenizer_class = None + + # Try to derive module path from tokenizer name (e.g., "AlbertTokenizer" -> "albert") + # Remove "Tokenizer" suffix and convert to lowercase + if candidate_name.endswith("Tokenizer"): + model_name = candidate_name[:-10].lower() # Remove "Tokenizer" + module_path = f"transformers.models.{model_name}.tokenization_{model_name}" + try: + module = importlib.import_module(module_path) + base_tokenizer_class = getattr(module, candidate_name) + except Exception: + logger.debug(f"{module_path} does not have {candidate_name} defined.") + + # Fallback: try via _class_to_module + if base_tokenizer_class is None and candidate_name in self._class_to_module: + try: + alias_module_name = self._class_to_module[candidate_name] + alias_module = self._get_module(alias_module_name) + base_tokenizer_class = getattr(alias_module, candidate_name) + except Exception: + logger.debug( + f"{alias_module_name} does not have {candidate_name} defined" + ) + + # If we still don't have base_tokenizer_class, skip this candidate + if base_tokenizer_class is None: + logger.debug(f"skipping candidate {candidate_name}") + continue + + # If we got here, we have base_tokenizer_class + value = base_tokenizer_class + + setattr(self, candidate_name, base_tokenizer_class) + if lookup_name != candidate_name: + setattr(self, lookup_name, value) + setattr(self, name, value) + break + except Exception as e: + logger.debug(f"Could not create tokenizer alias: {e}") + + if value is None: + raise ModuleNotFoundError( + f"Could not import module '{name}'. Are this object's requirements defined correctly?" + ) from e + else: + raise ModuleNotFoundError( + f"Could not import module '{name}'. Are this object's requirements defined correctly?" + ) from e + + elif name in self._modules: + try: + value = self._get_module(name) + except (ModuleNotFoundError, RuntimeError) as e: + raise ModuleNotFoundError( + f"Could not import module '{name}'. Are this object's requirements defined correctly?" + ) from e + else: + # V5: If a *TokenizerFast symbol is requested but not present in the import structure, + # try to resolve to the corresponding non-Fast symbol's module if available. + if name.endswith("TokenizerFast"): + fallback_name = name[:-4] + if fallback_name in self._class_to_module: + try: + fb_module = self._get_module(self._class_to_module[fallback_name]) + value = getattr(fb_module, fallback_name) + setattr(self, fallback_name, value) + setattr(self, name, value) + return value + except Exception as e: + logger.debug(f"Could not load fallback {fallback_name}: {e}") + # V5: Handle *ImageProcessorFast backward compatibility + # Similar to TokenizerFast, but for image processors + if name.endswith("ImageProcessorFast"): + fallback_name = name[:-4] # Remove "Fast" + if fallback_name in self._class_to_module: + logger.warning_once( + f"`{name}` is deprecated. The `Fast` suffix for image processors has been removed; " + f"use `{fallback_name}` instead." + ) + if fallback_name in self._object_missing_backend: + # The Fast alias has no entry in the import structure, so `requires_backends` on + # the real class never runs. Handle the missing backend explicitly here, otherwise + # `_get_module` swallows the ImportError and the caller gets an AttributeError. + # Do not fall through to the PIL fallback since a legacy "Fast" image processor was explicitly requested. + missing_backends = self._object_missing_backend[fallback_name] + + class Placeholder(metaclass=DummyObject): + _backends = missing_backends + + def __init__(self, *args, **kwargs): + requires_backends(self, missing_backends) + + def call(self, *args, **kwargs): + pass + + Placeholder.__name__ = fallback_name + module_name = self._class_to_module[fallback_name] + Placeholder.__module__ = ( + module_name if module_name.startswith("transformers.") else f"transformers.{module_name}" + ) + setattr(self, name, Placeholder) + return Placeholder + try: + fb_module = self._get_module(self._class_to_module[fallback_name]) + value = getattr(fb_module, fallback_name) + setattr(self, fallback_name, value) + setattr(self, name, value) + return value + except Exception as e: + logger.debug(f"Could not load fallback {fallback_name}: {e}") + # V5: If a tokenizer class doesn't exist, check if it should alias to another tokenizer + # via the converter mapping (e.g., FNetTokenizer -> AlbertTokenizer via AlbertConverter) + value = None + if name.endswith("Tokenizer") or name.endswith("TokenizerFast"): + # Strip "Fast" suffix for converter lookup if present + lookup_name = name[:-4] if name.endswith("TokenizerFast") else name + + try: + # Lazy import to avoid circular dependencies + from ..convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS + + # Check if this tokenizer has a converter mapping + if lookup_name in SLOW_TO_FAST_CONVERTERS: + converter_class = SLOW_TO_FAST_CONVERTERS[lookup_name] + + # Find which tokenizer class uses the same converter (reverse lookup) + # Prefer the tokenizer that matches the converter name pattern + # (e.g., AlbertConverter -> AlbertTokenizer) + converter_base_name = converter_class.__name__.replace("Converter", "") + preferred_tokenizer_name = f"{converter_base_name}Tokenizer" + + # Try preferred tokenizer first + candidate_names = [preferred_tokenizer_name] + # Then try all other tokenizers with the same converter + for tokenizer_name, tokenizer_converter in SLOW_TO_FAST_CONVERTERS.items(): + if tokenizer_converter is converter_class and tokenizer_name != lookup_name: + if tokenizer_name not in candidate_names: + candidate_names.append(tokenizer_name) + + # Try to import one of the candidate tokenizers + for candidate_name in candidate_names: + if candidate_name in self._class_to_module: + try: + alias_module = self._get_module(self._class_to_module[candidate_name]) + base_tokenizer_class = getattr(alias_module, candidate_name) + value = base_tokenizer_class + + # Cache both names for future imports + setattr(self, candidate_name, base_tokenizer_class) + if lookup_name != candidate_name: + setattr(self, lookup_name, value) + setattr(self, name, value) + break + except Exception: + # If this candidate fails, try the next one + continue + else: + # Candidate not in _class_to_module - might need recursive resolution + # Try importing it directly to trigger lazy loading + try: + # Try to get it from transformers module to trigger lazy loading + transformers_module = sys.modules.get("transformers") + if transformers_module and hasattr(transformers_module, candidate_name): + base_tokenizer_class = getattr(transformers_module, candidate_name) + value = base_tokenizer_class + + if lookup_name != candidate_name: + setattr(self, lookup_name, value) + setattr(self, name, value) + break + except Exception: + continue + except (ImportError, AttributeError): + pass + + if value is None: + for key, values in self._explicit_import_shortcut.items(): + if name in values: + value = self._get_module(key) + break + + if value is None: + raise AttributeError(f"module {self.__name__} has no attribute {name}") + + setattr(self, name, value) + return value + + def _get_module(self, module_name: str): + try: + return importlib.import_module("." + module_name, self.__name__) + except Exception as e: + raise e + + def __reduce__(self): + return (self.__class__, (self._name, self.__file__, self._import_structure)) + + +class OptionalDependencyNotAvailable(BaseException): + """Internally used error class for signalling an optional dependency was not found.""" + + +def direct_transformers_import(path: str, file="__init__.py") -> ModuleType: + """Imports transformers directly + + Args: + path (`str`): The path to the source file + file (`str`, *optional*): The file to join with the path. Defaults to "__init__.py". + + Returns: + `ModuleType`: The resulting imported module + """ + name = "transformers" + location = os.path.join(path, file) + spec = importlib.util.spec_from_file_location(name, location, submodule_search_locations=[path]) + if spec is not None and spec.loader is not None: + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + module = sys.modules[name] + return module + raise ImportError(f"Could not load module {name} from {location}") + + +class VersionComparison(Enum): + EQUAL = operator.eq + NOT_EQUAL = operator.ne + GREATER_THAN = operator.gt + LESS_THAN = operator.lt + GREATER_THAN_OR_EQUAL = operator.ge + LESS_THAN_OR_EQUAL = operator.le + + @staticmethod + def from_string(version_string: str) -> "VersionComparison": + string_to_operator = { + "=": VersionComparison.EQUAL, + "==": VersionComparison.EQUAL, + "!=": VersionComparison.NOT_EQUAL, + ">": VersionComparison.GREATER_THAN, + "<": VersionComparison.LESS_THAN, + ">=": VersionComparison.GREATER_THAN_OR_EQUAL, + "<=": VersionComparison.LESS_THAN_OR_EQUAL, + } + + return string_to_operator[version_string] + + +@lru_cache +def split_package_version(package_version_str) -> tuple[str, str, str]: + pattern = r"([a-zA-Z0-9_-]+)([!<>=~]+)([0-9.]+)" + match = re.match(pattern, package_version_str) + if match: + return (match.group(1), match.group(2), match.group(3)) + else: + raise ValueError(f"Invalid package version string: {package_version_str}") + + +class Backend: + def __init__(self, backend_requirement: str): + self.package_name, self.version_comparison, self.version = split_package_version(backend_requirement) + + if self.package_name not in BACKENDS_MAPPING: + raise ValueError( + f"Backends should be defined in the BACKENDS_MAPPING. Offending backend: {self.package_name}" + ) + + def get_installed_version(self) -> str: + """Return the currently installed version of the backend""" + is_available, current_version = _is_package_available(self.package_name, return_version=True) + if not is_available: + raise RuntimeError(f"Backend {self.package_name} is not available.") + return current_version + + def is_satisfied(self) -> bool: + return VersionComparison.from_string(self.version_comparison).value( + version.parse(self.get_installed_version()), version.parse(self.version) + ) + + def __repr__(self) -> str: + return f'Backend("{self.package_name}", {VersionComparison[self.version_comparison]}, "{self.version}")' + + @property + def error_message(self): + return ( + f"{{0}} requires the {self.package_name} library version {self.version_comparison}{self.version}. That" + f" library was not found with this version in your environment." + ) + + +def requires(*, backends=()): + """ + This decorator enables two things: + - Attaching a `__backends` tuple to an object to see what are the necessary backends for it + to execute correctly without instantiating it + - The '@requires' string is used to dynamically import objects + """ + + if not isinstance(backends, (tuple, list)): + raise TypeError("Backends should be a tuple or list.") + backends = tuple(backends) + + applied_backends = [] + for backend in backends: + if backend in BACKENDS_MAPPING: + applied_backends.append(backend) + else: + if any(key in backend for key in ["=", "<", ">"]): + applied_backends.append(Backend(backend)) + else: + raise ValueError(f"Backend should be defined in the BACKENDS_MAPPING. Offending backend: {backend}") + + def inner_fn(fun): + if isinstance(fun, type): + # For classes, just attach the metadata — don't wrap, as that would + # turn the class into a plain function and break isinstance checks. + fun.__backends = applied_backends + return fun + + @functools.wraps(fun) + def wrapper(*args, **kwargs): + requires_backends(fun, applied_backends) + return fun(*args, **kwargs) + + wrapper.__backends = applied_backends # type: ignore [unresolved-attribute] + return wrapper + + return inner_fn + + +BASE_FILE_REQUIREMENTS = { + lambda name, content: "modeling_" in name: ("torch",), + lambda name, content: "tokenization_" in name and name.endswith("_fast"): ("tokenizers",), + lambda name, content: "image_processing_" in name and "TorchvisionBackend" in content: ( + "vision", + "torch", + "torchvision", + ), + lambda name, content: "image_processing_" in name: ("vision",), + lambda name, content: "video_processing_" in name: ("vision", "torch", "torchvision"), +} + + +def fetch__all__(file_content) -> list[str]: + """ + Returns the content of the __all__ variable in the file content. + Returns None if not defined, otherwise returns a list of strings. + """ + + if "__all__" not in file_content: + return [] + + start_index = None + lines = file_content.splitlines() + for index, line in enumerate(lines): + if line.startswith("__all__"): + start_index = index + + # There is no line starting with `__all__` + if start_index is None: + return [] + + lines = lines[start_index:] + + if not lines[0].startswith("__all__"): + raise ValueError( + "fetch__all__ accepts a list of lines, with the first line being the __all__ variable declaration" + ) + + # __all__ is defined on a single line + if lines[0].endswith("]"): + return [obj.strip("\"' ") for obj in lines[0].split("=")[1].strip(" []").split(",")] + + # __all__ is defined on multiple lines + else: + _all: list[str] = [] + for __all__line_index in range(1, len(lines)): + if lines[__all__line_index].strip() == "]": + return _all + else: + _all.append(lines[__all__line_index].strip("\"', ")) + + return _all + + +@lru_cache +def create_import_structure_from_path(module_path): + """ + This method takes the path to a file/a folder and returns the import structure. + If a file is given, it will return the import structure of the parent folder. + + Import structures are designed to be digestible by `_LazyModule` objects. They are + created from the __all__ definitions in each files as well as the `@require` decorators + above methods and objects. + + The import structure allows explicit display of the required backends for a given object. + These backends are specified in two ways: + + 1. Through their `@require`, if they are exported with that decorator. This `@require` decorator + accepts a `backend` tuple kwarg mentioning which backends are required to run this object. + + 2. If an object is defined in a file with "default" backends, it will have, at a minimum, this + backend specified. The default backends are defined according to the filename: + + - If a file is named like `modeling_*.py`, it will have a `torch` backend + - If a file is named like `tokenization_*_fast.py`, it will have a `tokenizers` backend + - If a file is named like `image_processing*_fast.py`, it will have a `torchvision` + `torch` backend + + Backends serve the purpose of displaying a clear error message to the user in case the backends are not installed. + Should an object be imported without its required backends being in the environment, any attempt to use the + object will raise an error mentioning which backend(s) should be added to the environment in order to use + that object. + + Here's an example of an input import structure at the src.transformers.models level: + + { + 'albert': { + frozenset(): { + 'configuration_albert': {'AlbertConfig'} + }, + frozenset({'tokenizers'}): { + 'tokenization_albert_fast': {'AlbertTokenizer'} + }, + }, + 'align': { + frozenset(): { + 'configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'}, + 'processing_align': {'AlignProcessor'} + }, + }, + 'altclip': { + frozenset(): { + 'configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'}, + 'processing_altclip': {'AltCLIPProcessor'}, + } + } + } + """ + import_structure = {} + + if os.path.isfile(module_path): + module_path = os.path.dirname(module_path) + + adjacent_modules = [] + + with os.scandir(module_path) as entries: + for entry in entries: + if entry.name == "__pycache__": + continue + if entry.is_dir(): + import_structure[entry.name] = create_import_structure_from_path(entry.path) + elif not entry.name.startswith(("convert_", "modular_")): + adjacent_modules.append(entry.name) + + # We're only taking a look at files different from __init__.py + # We could theoretically require things directly from the __init__.py + # files, but this is not supported at this time. + if "__init__.py" in adjacent_modules: + adjacent_modules.remove("__init__.py") + + module_requirements = {} + for module_name in adjacent_modules: + # Only modules ending in `.py` are accepted here. + if not module_name.endswith(".py"): + continue + + with open(os.path.join(module_path, module_name), encoding="utf-8") as f: + file_content = f.read() + + # Remove the .py suffix + module_name = module_name[:-3] + + previous_line = "" + previous_index = 0 + + # Some files have some requirements by default. + # For example, any file named `modeling_xxx.py` + # should have torch as a required backend. + base_requirements = () + for check, requirements in BASE_FILE_REQUIREMENTS.items(): + if check(module_name, file_content): + base_requirements = requirements + break + + # Objects that have a `@require` assigned to them will get exported + # with the backends specified in the decorator as well as the file backends. + exported_objects = set() + if "@requires" in file_content: + lines = file_content.split("\n") + for index, line in enumerate(lines): + # This allows exporting items with other decorators. We'll take a look + # at the line that follows at the same indentation level. + if line.startswith((" ", "\t", "@", ")")) and not line.startswith("@requires"): + continue + + # Skipping line enables putting whatever we want between the + # requires() call and the actual class/method definition. + # This is what enables having # Copied from statements, docs, etc. + skip_line = False + + if "@requires" in previous_line: + skip_line = False + + # Backends are defined on the same line as requires + if "backends" in previous_line: + try: + backends_string = previous_line.split("backends=")[1].split("(")[1].split(")")[0] + except IndexError: + raise ValueError( + f"Couldn't parse backends for @requires decorator in file {module_name}:{previous_line}" + ) + backends = tuple(sorted([b.strip("'\",") for b in backends_string.split(", ") if b])) + + # Backends are defined in the lines following requires, for example such as: + # @requires( + # backends=( + # "sentencepiece", + # "torch", + # ) + # ) + # + # or + # + # @requires( + # backends=( + # "sentencepiece", + # ) + # ) + elif "backends" in lines[previous_index + 1]: + backends = [] + for backend_line in lines[previous_index:index]: + if "backends" in backend_line: + backend_line = backend_line.split("=")[1] + if '"' in backend_line or "'" in backend_line: + if ", " in backend_line: + backends.extend(backend.strip("()\"', ") for backend in backend_line.split(", ")) + else: + backends.append(backend_line.strip("()\"', ")) + + # If the line is only a ')', then we reached the end of the backends and we break. + if backend_line.strip() == ")": + break + backends = tuple(backends) + + # No backends are registered for requires + else: + backends = () + + backends = frozenset(backends + base_requirements) + if backends not in module_requirements: + module_requirements[backends] = {} + if module_name not in module_requirements[backends]: + module_requirements[backends][module_name] = set() + + if not line.startswith("class") and not line.startswith("def"): + skip_line = True + else: + start_index = 6 if line.startswith("class") else 4 + object_name = line[start_index:].split("(")[0].strip(":") + module_requirements[backends][module_name].add(object_name) + exported_objects.add(object_name) + + if not skip_line: + previous_line = line + previous_index = index + + # All objects that are in __all__ should be exported by default. + # These objects are exported with the file backends. + if "__all__" in file_content: + for _all_object in fetch__all__(file_content): + if _all_object not in exported_objects: + backends = frozenset(base_requirements) + if backends not in module_requirements: + module_requirements[backends] = {} + if module_name not in module_requirements[backends]: + module_requirements[backends][module_name] = set() + + module_requirements[backends][module_name].add(_all_object) + + import_structure = {**module_requirements, **import_structure} + return import_structure + + +def spread_import_structure(nested_import_structure): + """ + This method takes as input an unordered import structure and brings the required backends at the top-level, + aggregating modules and objects under their required backends. + + Here's an example of an input import structure at the src.transformers.models level: + + { + 'albert': { + frozenset(): { + 'configuration_albert': {'AlbertConfig'} + }, + frozenset({'tokenizers'}): { + 'tokenization_albert_fast': {'AlbertTokenizer'} + }, + }, + 'align': { + frozenset(): { + 'configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'}, + 'processing_align': {'AlignProcessor'} + }, + }, + 'altclip': { + frozenset(): { + 'configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'}, + 'processing_altclip': {'AltCLIPProcessor'}, + } + } + } + + Here's an example of an output import structure at the src.transformers.models level: + + { + frozenset({'tokenizers'}): { + 'albert.tokenization_albert_fast': {'AlbertTokenizer'} + }, + frozenset(): { + 'albert.configuration_albert': {'AlbertConfig'}, + 'align.processing_align': {'AlignProcessor'}, + 'align.configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'}, + 'altclip.configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'}, + 'altclip.processing_altclip': {'AltCLIPProcessor'} + } + } + + """ + + def propagate_frozenset(unordered_import_structure): + frozenset_first_import_structure = {} + for _key, _value in unordered_import_structure.items(): + # If the value is not a dict but a string, no need for custom manipulation + if not isinstance(_value, dict): + frozenset_first_import_structure[_key] = _value + + elif any(isinstance(v, frozenset) for v in _value): + for k, v in _value.items(): + if isinstance(k, frozenset): + # Here we want to switch around _key and k to propagate k upstream if it is a frozenset + if k not in frozenset_first_import_structure: + frozenset_first_import_structure[k] = {} + if _key not in frozenset_first_import_structure[k]: + frozenset_first_import_structure[k][_key] = {} + + frozenset_first_import_structure[k][_key].update(v) + + else: + # If k is not a frozenset, it means that the dictionary is not "level": some keys (top-level) + # are frozensets, whereas some are not -> frozenset keys are at an unknown depth-level of the + # dictionary. + # + # We recursively propagate the frozenset for this specific dictionary so that the frozensets + # are at the top-level when we handle them. + propagated_frozenset = propagate_frozenset({k: v}) + for r_k, r_v in propagated_frozenset.items(): + if isinstance(_key, frozenset): + if r_k not in frozenset_first_import_structure: + frozenset_first_import_structure[r_k] = {} + if _key not in frozenset_first_import_structure[r_k]: + frozenset_first_import_structure[r_k][_key] = {} + + # _key is a frozenset -> we switch around the r_k and _key + frozenset_first_import_structure[r_k][_key].update(r_v) + else: + if _key not in frozenset_first_import_structure: + frozenset_first_import_structure[_key] = {} + if r_k not in frozenset_first_import_structure[_key]: + frozenset_first_import_structure[_key][r_k] = {} + + # _key is not a frozenset -> we keep the order of r_k and _key + frozenset_first_import_structure[_key][r_k].update(r_v) + + else: + frozenset_first_import_structure[_key] = propagate_frozenset(_value) + + return frozenset_first_import_structure + + def flatten_dict(_dict, previous_key=None): + items = [] + for _key, _value in _dict.items(): + _key = f"{previous_key}.{_key}" if previous_key is not None else _key + if isinstance(_value, dict): + items.extend(flatten_dict(_value, _key).items()) + else: + items.append((_key, _value)) + return dict(items) + + # The tuples contain the necessary backends. We want these first, so we propagate them up the + # import structure. + ordered_import_structure = nested_import_structure + + # 6 is a number that gives us sufficient depth to go through all files and foreseeable folder depths + # while not taking too long to parse. + for i in range(6): + ordered_import_structure = propagate_frozenset(ordered_import_structure) + + # We then flatten the dict so that it references a module path. + flattened_import_structure = {} + for key, value in ordered_import_structure.copy().items(): + if isinstance(key, str): + del ordered_import_structure[key] + else: + flattened_import_structure[key] = flatten_dict(value) + + return flattened_import_structure + + +@lru_cache +def define_import_structure(module_path: str, prefix: str | None = None) -> IMPORT_STRUCTURE_T: + """ + This method takes a module_path as input and creates an import structure digestible by a _LazyModule. + + Here's an example of an output import structure at the src.transformers.models level: + + { + frozenset({'tokenizers'}): { + 'albert.tokenization_albert_fast': {'AlbertTokenizer'} + }, + frozenset(): { + 'albert.configuration_albert': {'AlbertConfig'}, + 'align.processing_align': {'AlignProcessor'}, + 'align.configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'}, + 'altclip.configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'}, + 'altclip.processing_altclip': {'AltCLIPProcessor'} + } + } + + The import structure is a dict defined with frozensets as keys, and dicts of strings to sets of objects. + + If `prefix` is not None, it will add that prefix to all keys in the returned dict. + """ + import_structure = create_import_structure_from_path(module_path) + spread_dict = spread_import_structure(import_structure) + + if prefix is None: + return spread_dict + else: + spread_dict = {k: {f"{prefix}.{kk}": vv for kk, vv in v.items()} for k, v in spread_dict.items()} + return spread_dict + + +def clear_import_cache() -> None: + """ + Clear cached Transformers modules to allow reloading modified code. + + This is useful when actively developing/modifying Transformers code. + """ + # Get all transformers modules + transformers_modules = [mod_name for mod_name in sys.modules if mod_name.startswith("transformers.")] + + # Remove them from sys.modules + for mod_name in transformers_modules: + module = sys.modules[mod_name] + # Clear _LazyModule caches if applicable + if isinstance(module, _LazyModule): + module._objects = {} # Clear cached objects + del sys.modules[mod_name] + + # Force reload main transformers module + if "transformers" in sys.modules: + main_module = sys.modules["transformers"] + if isinstance(main_module, _LazyModule): + main_module._objects = {} # Clear cached objects + importlib.reload(main_module) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/kernel_config.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/kernel_config.py new file mode 100644 index 0000000000000000000000000000000000000000..bb4f965ddbf4b22cb61dc465832af338478eb2f5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/kernel_config.py @@ -0,0 +1,281 @@ +# Copyright 2025 The HuggingFace Inc. team. All rights reserved. +# +# 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. + +from ..utils import PushToHubMixin + + +def infer_device(model): + """ + Infers the device type from the model parameters. + Args: + model: The model instance. + + Returns: + The device type. + """ + EXAMPLE_MAPPING = """ + { + "RMSNorm": { + "cuda": + "kernels-community/layer_norm:LlamaRMSNorm", + ... + }, + ... + } + """ + try: + param = next(model.parameters()) + except StopIteration: + raise ValueError( + f"Cannot determine model device, please provide a device to the mapping. Example: {EXAMPLE_MAPPING}" + ) + + dev_type = param.device.type + if dev_type == "cuda": + # Refine based on actual platform + from ..utils import is_torch_available + + if is_torch_available(): + import torch + + if getattr(torch, "version").hip is not None: + return "rocm" + + return dev_type + + +def add_to_mapping(layer_name, device, repo_name, mode, compatible_mapping): + from kernels import LayerRepository + + if device not in ["cuda", "rocm", "xpu", "npu", "neuron"]: + raise ValueError(f"Only cuda, rocm, xpu, npu and neuron devices supported, got: {device}") + repo_layer_name = repo_name.split(":")[1] + repo_id = repo_name.split(":")[0] + compatible_mapping[layer_name] = { + device: { + mode: LayerRepository( + repo_id=repo_id, + layer_name=repo_layer_name, + ) + } + } + + +def add_to_mapping_local(layer_name, device, repo_name, mode, compatible_mapping): + from pathlib import Path + + from kernels import LocalLayerRepository + + if device not in ["cuda", "rocm", "xpu", "npu", "neuron"]: + raise ValueError(f"Only cuda, rocm, xpu, npu and neuron devices supported, got: {device}") + repo_layer_name = repo_name.split(":")[1] + repo_path = repo_name.split(":")[0] + repo_package_name = repo_path.split("/")[-1] + compatible_mapping[layer_name] = { + device: { + mode: LocalLayerRepository( + repo_path=Path(repo_path), + package_name=repo_package_name, + layer_name=repo_layer_name, + ) + } + } + + +class KernelConfig(PushToHubMixin): + """ + Kernel configuration class. This class is used to configure the kernel mapping for a model. + """ + + def __init__(self, kernel_mapping=None, use_local_kernel=False): + self.kernel_mapping = kernel_mapping if kernel_mapping is not None else {} + self.registered_layer_names = {} + self.use_local_kernel = use_local_kernel + + def update_kernel(self, repo_id, registered_name, layer_name, device, mode, revision=None): + from kernels import LayerRepository + + self.kernel_mapping[registered_name] = { + device: { + mode: LayerRepository( + repo_id=repo_id, + layer_name=layer_name, + revision=revision, + ) + } + } + + def store_registered_layer_names(self, model): + for name, module in model.named_modules(): + if hasattr(module, "kernel_layer_name"): + self.registered_layer_names[name] = module.kernel_layer_name + + def sanitize_kernel_mapping(self, model): + """ + Validates the kernel_mapping to ensure that: + 1. Each layer_name in the mapping is registered in the model (i.e., the model contains a module with a matching kernel_layer_name). + 2. Each kernel value is either a string of the form 'org/repo:layer_name' or a dict mapping device types ("cuda", "rocm", "xpu", "npu") to such strings. + 3. Each device key in a dict is one of "cuda", "rocm", "xpu", or "npu". + 4. Each repo_name is a valid repository and layer name in the format 'org/repo:layer_name' (i.e., a string containing both a slash and a colon). + 5. If a local path is detected, it should be in the format '/abs/path:layer_name'. The absolute path must include the `package_name`, like "/home/user/layer_norm". + + Args: + model: The model instance whose modules are checked for registered kernel_layer_name attributes. + + Raises: + ValueError: If a layer_name is not registered in the model, if a device is not supported, + or if a repo_name is not a valid 'org/repo:layer_name' string. + """ + MAPPING_FORMAT = """ + For single device form remote + { + "RMSNorm": + "kernels-community/layer_norm:LlamaRMSNorm", + ... + }, + For multiple devices form remote + { + "RMSNorm": { + "cuda": + "kernels-community/layer_norm:LlamaRMSNorm", + "rocm": + "kernels-community/layer_norm:LlamaRMSNorm", + ... + }, + ... + } + For single device form local + { + "RMSNorm": + "/abs/path:LlamaRMSNorm", + ... + }, + For multiple devices form local + { + "RMSNorm": { + "cuda": + "/abs/path:LlamaRMSNorm", + "rocm": + "/abs/path:LlamaRMSNorm", + ... + }, + ... + } + """ + self.store_registered_layer_names(model) + # Validate that the kernel mapping is a dict + if not isinstance(self.kernel_mapping, dict): + raise ValueError( + f"Kernel mapping must be a dict of the following format: {MAPPING_FORMAT}, got: {type(self.kernel_mapping)}" + ) + + for layer_name, kernel in self.kernel_mapping.items(): + if layer_name not in self.registered_layer_names.values(): + raise ValueError( + f"Layer {layer_name} is not registered in the model, please register it first using use_kernel_forward_from_hub" + ) + + if isinstance(kernel, str): + if "/" not in kernel or ":" not in kernel: + raise ValueError( + f"Kernel mapping for '{layer_name}' must be a valid repo name with a layer name (e.g., 'org/repo:layer_name' or '/abs/path:layer_name'), got: {kernel}" + ) + + elif isinstance(kernel, dict): + for device, repo_name in kernel.items(): + if device not in ["cuda", "rocm", "xpu", "npu", "neuron"]: + raise ValueError(f"Only cuda, rocm, xpu, npu and neuron devices supported, got: {device}") + + if not isinstance(repo_name, str) or "/" not in repo_name or ":" not in repo_name: + raise ValueError( + f"Kernel mapping for '{layer_name}' must be a valid repo name with a layer name (e.g., 'org/repo:layer_name' or '/abs/path:layer_name'), got: {repo_name}" + ) + else: + raise ValueError(f"Kernel mapping must follow the format: {MAPPING_FORMAT}, got: {kernel}") + + def create_compatible_mapping(self, model, compile=False): + """ + Transforms a simple kernel_mapping of the form: + { + "RMSNorm": + "kernels-community/layer_norm:LlamaRMSNorm", + ... + }, + + or for local path: + + { + "RMSNorm": + "/home/user/liger_kernels:LigerRMSNorm", + ... + }, + + into a nested mapping: + + { + "RMSNorm": { + "cuda": { + Mode.INFERENCE: LayerRepository( + repo_id="kernels-community/layer_norm", + layer_name="LlamaRMSNorm", + ) + } + } + } + + or for local path: + + { + "RMSNorm": { + "cuda": { + Mode.INFERENCE: LocalLayerRepository( + repo_path=Path("/home/user/liger_kernels"), + package_name="liger_kernels", + layer_name="LigerRMSNorm", + ) + } + } + } + + that's compatible with the kernels library. + + The device is inferred from the model's parameters if not provided. + The Mode is inferred from the model's training state. + """ + from kernels import Mode + + compatible_mapping = {} + current_device = infer_device(model) + for layer_name, kernel in self.kernel_mapping.items(): + # Infer Mode: use Mode.TRAINING if model is training, else use Mode.INFERENCE + mode = Mode.TRAINING if model.training else Mode.INFERENCE + if compile: + mode = mode | Mode.TORCH_COMPILE + + if isinstance(kernel, str): + repo_name = kernel + if not self.use_local_kernel: + add_to_mapping(layer_name, current_device, repo_name, mode, compatible_mapping) + else: + add_to_mapping_local(layer_name, current_device, repo_name, mode, compatible_mapping) + elif isinstance(kernel, dict): + for device, repo_name in kernel.items(): + if device != current_device: + continue + if not self.use_local_kernel: + add_to_mapping(layer_name, device, repo_name, mode, compatible_mapping) + else: + add_to_mapping_local(layer_name, device, repo_name, mode, compatible_mapping) + + self.kernel_mapping = compatible_mapping diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/loading_report.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/loading_report.py new file mode 100644 index 0000000000000000000000000000000000000000..0e6ffcb77da4211bad1e8074cf28ed46181fc402 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/loading_report.py @@ -0,0 +1,280 @@ +# Copyright 2025 The HuggingFace Inc. team. All rights reserved. +# +# 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. +import logging +import re +import shutil +import sys +from collections import OrderedDict, defaultdict +from dataclasses import dataclass +from typing import Any + + +_DIGIT_RX = re.compile(r"(?<=\.)(\d+)(?=\.|$)") # numbers between dots or at the end + + +def _pattern_of(key: str) -> str: + """Replace every dot-delimited integer with '*' to get the structure.""" + return _DIGIT_RX.sub("*", key) + + +def _fmt_indices(values: list[int], cutoff=10) -> str: + """Format a list of ints as single number, {a, ..., b}, or first...last.""" + if len(values) == 1: + return str(values[0]) + values = sorted(values) + if len(values) > cutoff: + return f"{values[0]}...{values[-1]}" + return ", ".join(map(str, values)) + + +def update_key_name(mapping: dict[str, Any]) -> dict[str, Any]: + """ + Merge keys like 'layers.0.x', 'layers.1.x' into 'layers.{0, 1}.x' + BUT only merge together keys that have the exact same value. + Returns a new dict {merged_key: value}. + """ + # (pattern, value) -> list[set[int]] (per-star index values) + not_mapping = False + if not isinstance(mapping, dict): + mapping = {k: k for k in mapping} + not_mapping = True + + bucket: dict[str, list[set[int] | Any]] = defaultdict(list) + for key, val in mapping.items(): + digs = _DIGIT_RX.findall(key) + patt = _pattern_of(key) + for i, d in enumerate(digs): + if len(bucket[patt]) <= i: + bucket[patt].append(set()) + bucket[patt][i].add(int(d)) + bucket[patt].append(val) + + out_items = {} + for patt, values in bucket.items(): + sets, val = values[:-1], values[-1] + parts = patt.split("*") # stars are between parts + final = parts[0] + for i in range(1, len(parts)): + if i - 1 < len(sets) and sets[i - 1]: + insert = _fmt_indices(sorted(sets[i - 1])) + if len(sets[i - 1]) > 1: + final += "{" + insert + "}" + else: + final += insert + else: + final += "*" + final += parts[i] + + out_items[final] = val + out = OrderedDict(out_items) + if not_mapping: + return out.keys() + return out + + +_ansi_re = re.compile(r"\x1b\[[0-9;]*m") + + +def _strip_ansi(s: str) -> str: + return _ansi_re.sub("", str(s)) + + +def _pad(text, width): + t = str(text) + pad = max(0, width - len(_strip_ansi(t))) + return t + " " * pad + + +def _make_table(rows, headers): + # compute display widths while ignoring ANSI codes + cols = list(zip(*([headers] + rows))) if rows else [headers] + widths = [max(len(_strip_ansi(x)) for x in col) for col in cols] + header_line = " | ".join(_pad(h, w) for h, w in zip(headers, widths)) + sep_line = "-+-".join("-" * w for w in widths) + body = [" | ".join(_pad(c, w) for c, w in zip(r, widths)) for r in rows] + return "\n".join([header_line, sep_line] + body) + + +PALETTE = { + "reset": "", + "red": "", + "yellow": "", + "orange": "", + "purple": "", + "bold": "", + "italic": "", + "dim": "", +} + + +def _style(s, color): + """Return color/style-formatted input `s` if `sys.stdout` is interactive, e.g. connected to a terminal.""" + if sys.stdout.isatty(): + return f"{PALETTE[color]}{s}{PALETTE['reset']}" + else: + return s + + +def _get_terminal_width(default=80): + try: + return shutil.get_terminal_size().columns + except Exception: + return default + + +@dataclass +class LoadStateDictInfo: + """ + Mutable container for state-dict loading results and diagnostics. Each entry in this structure is mutable, + and will usually be mutated in-place during the loading pipeline. + + Attributes: + missing_keys (`set[str]`): + Keys that are missing from the loaded checkpoints but expected in the model's architecture. + unexpected_keys (`set[str]`): + Keys that are found in the checkpoints, but not expected in the model's architecture. + mismatched_keys (`set[tuple[str, tuple[int], tuple[int]]]`): + Keys that are found in the checkpoints and are expected in the model's architecture, but with a different shape. + error_msgs ( `list[str]`): + Some potential error messages. + conversion_errors (`dict[str, str]`): + Errors happening during the on-the-fly weight conversion process. + """ + + missing_keys: set[str] + unexpected_keys: set[str] + mismatched_keys: set[tuple[str, tuple[int], tuple[int]]] + error_msgs: list[str] + conversion_errors: dict[str, str] + + def missing_and_mismatched(self): + """Return all effective missing keys, including `missing` and `mismatched` keys.""" + return self.missing_keys | {k[0] for k in self.mismatched_keys} + + def to_dict(self): + # Does not include the `conversion_errors` to be coherent with legacy reporting in the tests + return { + "missing_keys": self.missing_keys, + "unexpected_keys": self.unexpected_keys, + "mismatched_keys": self.mismatched_keys, + "error_msgs": self.error_msgs, + } + + def create_loading_report(self) -> str | None: + """Generate the minimal table of a loading report.""" + term_w = _get_terminal_width() + + rows = [] + tips = "\n\nNotes:" + if self.unexpected_keys: + tips += f"\n- {_style('UNEXPECTED:', 'orange')}\t" + _style( + "can be ignored when loading from different task/architecture; not ok if you expect identical arch.", + "italic", + ) + for k in update_key_name(self.unexpected_keys): + status = _style("UNEXPECTED", "orange") + rows.append([k, status, "", ""]) + + if self.missing_keys: + tips += f"\n- {_style('MISSING:', 'red')}\t" + _style( + "those params were newly initialized because missing from the checkpoint. Consider training on your downstream task.", + "italic", + ) + for k in update_key_name(self.missing_keys): + status = _style("MISSING", "red") + rows.append([k, status, ""]) + + if self.mismatched_keys: + tips += f"\n- {_style('MISMATCH:', 'yellow')}\t" + _style( + "ckpt weights were loaded, but they did not match the original empty weight shapes.", "italic" + ) + iterator = {a: (b, c) for a, b, c in self.mismatched_keys} + for key, (shape_ckpt, shape_model) in update_key_name(iterator).items(): + status = _style("MISMATCH", "yellow") + data = [ + key, + status, + f"Reinit due to size mismatch - ckpt: {str(shape_ckpt)} vs model:{str(shape_model)}", + ] + rows.append(data) + + if self.conversion_errors: + tips += f"\n- {_style('CONVERSION:', 'purple')}\t" + _style( + "originate from the conversion scheme", "italic" + ) + for k, v in update_key_name(self.conversion_errors).items(): + status = _style("CONVERSION", "purple") + _details = f"\n\n{v}\n\n" + rows.append([k, status, _details]) + + # If nothing is wrong, return None + if len(rows) == 0: + return None + + headers = ["Key", "Status"] + if term_w > 200: + headers += ["Details"] + else: + headers += ["", ""] + table = _make_table(rows, headers=headers) + report = table + tips + + return report + + +def log_state_dict_report( + model, + pretrained_model_name_or_path: str, + ignore_mismatched_sizes: bool, + loading_info: LoadStateDictInfo, + logger: logging.Logger | None = None, +): + """ + Log a readable report about state_dict loading issues. + + This version is terminal-size aware: for very small terminals it falls back to a compact + Key | Status view so output doesn't wrap badly. + """ + if logger is None: + logger = logging.getLogger(__name__) + + # Re-raise errors early if needed + if loading_info.error_msgs: + error_msg = "\n\t".join(loading_info.error_msgs) + if "size mismatch" in error_msg: + error_msg += ( + "\n\tYou may consider adding `ignore_mismatched_sizes=True` to `from_pretrained(...)` if appropriate." + ) + raise RuntimeError(f"Error(s) in loading state_dict for {model.__class__.__name__}:\n\t{error_msg}") + + # Create the report table + report = loading_info.create_loading_report() + if report is None: + return + + prelude = f"{PALETTE['bold']}{model.__class__.__name__} LOAD REPORT{PALETTE['reset']} from: {pretrained_model_name_or_path}\n" + + # Log the report as warning + logger.warning(prelude + report) + + # Re-raise in those case, after the report + if loading_info.conversion_errors: + raise RuntimeError( + "We encountered some issues during automatic conversion of the weights. For details look at the `CONVERSION` entries of " + "the above report!" + ) + if not ignore_mismatched_sizes and loading_info.mismatched_keys: + raise RuntimeError( + "You set `ignore_mismatched_sizes` to `False`, thus raising an error. For details look at the above report!" + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/logging.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..32099c4afe104d77d949d8a6946eded08999f8a2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/logging.py @@ -0,0 +1,441 @@ +# Copyright 2020 Optuna, Hugging Face +# +# 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. +"""Logging utilities.""" + +import functools +import logging +import os +import sys +import threading +from collections.abc import Callable +from logging import ( + CRITICAL, # NOQA + DEBUG, + ERROR, + FATAL, # NOQA + INFO, + NOTSET, # NOQA + WARN, # NOQA + WARNING, +) +from logging import captureWarnings as _captureWarnings +from typing import Any + +import huggingface_hub.utils as hf_hub_utils +from tqdm import auto as tqdm_lib + +from .._typing import TransformersLogger + + +_lock = threading.Lock() +_default_handler: logging.Handler | None = None + +log_levels = { + "detail": logging.DEBUG, # will also print filename and line number + "debug": logging.DEBUG, + "info": logging.INFO, + "warning": logging.WARNING, + "error": logging.ERROR, + "critical": logging.CRITICAL, +} + +_default_log_level = logging.WARNING + +_tqdm_active = not hf_hub_utils.are_progress_bars_disabled() +_tqdm_hook: Callable[[Callable[..., Any], tuple[Any, ...], dict[str, Any]], Any] | None = None + + +def _get_default_logging_level(): + """ + If TRANSFORMERS_VERBOSITY env var is set to one of the valid choices return that as the new default level. If it is + not - fall back to `_default_log_level` + """ + env_level_str = os.getenv("TRANSFORMERS_VERBOSITY", None) + if env_level_str: + if env_level_str in log_levels: + return log_levels[env_level_str] + else: + logging.getLogger().warning( + f"Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, " + f"has to be one of: {', '.join(log_levels.keys())}" + ) + return _default_log_level + + +def _get_library_name() -> str: + return __name__.split(".")[0] + + +def _get_library_root_logger() -> logging.Logger: + return logging.getLogger(_get_library_name()) + + +def _configure_library_root_logger() -> None: + global _default_handler + + with _lock: + if _default_handler: + # This library has already configured the library root logger. + return + _default_handler = logging.StreamHandler() # Set sys.stderr as stream. + # set defaults based on https://github.com/pyinstaller/pyinstaller/issues/7334#issuecomment-1357447176 + if sys.stderr is None: + sys.stderr = open(os.devnull, "w") + + _default_handler.flush = sys.stderr.flush + + # Apply our default configuration to the library root logger. + library_root_logger = _get_library_root_logger() + library_root_logger.addHandler(_default_handler) + library_root_logger.setLevel(_get_default_logging_level()) + # Always show lib when logging in non-verbose mode. Note, other libs + # use `transformers.logger` directly, so we check `lib_name` to be safe + lib_name = _get_library_name() + logging_format = f"[{lib_name}] %(message)s" + + # if logging level is debug, we add pathname and lineno to formatter for easy debugging + if os.getenv("TRANSFORMERS_VERBOSITY", None) == "detail": + logging_format = "%(levelname)s [%(name)s:%(lineno)s] %(asctime)s %(message)s" + + formatter = logging.Formatter(logging_format) + _default_handler.setFormatter(formatter) + + ci = os.getenv("CI") + is_ci = ci is not None and ci.upper() in {"1", "ON", "YES", "TRUE"} + library_root_logger.propagate = is_ci + + +def _reset_library_root_logger() -> None: + global _default_handler + + with _lock: + if not _default_handler: + return + + library_root_logger = _get_library_root_logger() + library_root_logger.removeHandler(_default_handler) + library_root_logger.setLevel(logging.NOTSET) + _default_handler = None + + +def get_log_levels_dict(): + return log_levels + + +def captureWarnings(capture): + """ + Calls the `captureWarnings` method from the logging library to enable management of the warnings emitted by the + `warnings` library. + + Read more about this method here: + https://docs.python.org/3/library/logging.html#integration-with-the-warnings-module + + All warnings will be logged through the `py.warnings` logger. + + Careful: this method also adds a handler to this logger if it does not already have one, and updates the logging + level of that logger to the library's root logger. + """ + logger = get_logger("py.warnings") + + if not logger.handlers: + logger.addHandler(_default_handler) + + logger.setLevel(_get_library_root_logger().level) + + _captureWarnings(capture) + + +def get_logger(name: str | None = None) -> TransformersLogger: + """ + Return a logger with the specified name. + + This function is not supposed to be directly accessed unless you are writing a custom transformers module. + """ + + if name is None: + name = _get_library_name() + + _configure_library_root_logger() + return logging.getLogger(name) + + +def get_verbosity() -> int: + """ + Return the current level for the 🤗 Transformers's root logger as an int. + + Returns: + `int`: The logging level. + + + + 🤗 Transformers has following logging levels: + + - 50: `transformers.logging.CRITICAL` or `transformers.logging.FATAL` + - 40: `transformers.logging.ERROR` + - 30: `transformers.logging.WARNING` or `transformers.logging.WARN` + - 20: `transformers.logging.INFO` + - 10: `transformers.logging.DEBUG` + + """ + + _configure_library_root_logger() + return _get_library_root_logger().getEffectiveLevel() + + +def set_verbosity(verbosity: int) -> None: + """ + Set the verbosity level for the 🤗 Transformers's root logger. + + Args: + verbosity (`int`): + Logging level, e.g., one of: + + - `transformers.logging.CRITICAL` or `transformers.logging.FATAL` + - `transformers.logging.ERROR` + - `transformers.logging.WARNING` or `transformers.logging.WARN` + - `transformers.logging.INFO` + - `transformers.logging.DEBUG` + """ + + _configure_library_root_logger() + _get_library_root_logger().setLevel(verbosity) + + +def set_verbosity_info(): + """Set the verbosity to the `INFO` level.""" + return set_verbosity(INFO) + + +def set_verbosity_warning(): + """Set the verbosity to the `WARNING` level.""" + return set_verbosity(WARNING) + + +def set_verbosity_debug(): + """Set the verbosity to the `DEBUG` level.""" + return set_verbosity(DEBUG) + + +def set_verbosity_error(): + """Set the verbosity to the `ERROR` level.""" + return set_verbosity(ERROR) + + +def disable_default_handler() -> None: + """Disable the default handler of the HuggingFace Transformers's root logger.""" + + _configure_library_root_logger() + + assert _default_handler is not None + _get_library_root_logger().removeHandler(_default_handler) + + +def enable_default_handler() -> None: + """Enable the default handler of the HuggingFace Transformers's root logger.""" + + _configure_library_root_logger() + + assert _default_handler is not None + _get_library_root_logger().addHandler(_default_handler) + + +def add_handler(handler: logging.Handler) -> None: + """adds a handler to the HuggingFace Transformers's root logger.""" + + _configure_library_root_logger() + + assert handler is not None + _get_library_root_logger().addHandler(handler) + + +def remove_handler(handler: logging.Handler) -> None: + """removes given handler from the HuggingFace Transformers's root logger.""" + + _configure_library_root_logger() + + assert handler is not None and handler not in _get_library_root_logger().handlers + _get_library_root_logger().removeHandler(handler) + + +def disable_propagation() -> None: + """ + Disable propagation of the library log outputs. Note that log propagation is disabled by default. + """ + + _configure_library_root_logger() + _get_library_root_logger().propagate = False + + +def enable_propagation() -> None: + """ + Enable propagation of the library log outputs. Please disable the HuggingFace Transformers's default handler to + prevent double logging if the root logger has been configured. + """ + + _configure_library_root_logger() + _get_library_root_logger().propagate = True + + +def enable_explicit_format() -> None: + """ + Enable explicit formatting for every HuggingFace Transformers's logger. The explicit formatter is as follows: + ``` + [LEVELNAME|FILENAME|LINE NUMBER] TIME >> MESSAGE + ``` + All handlers currently bound to the root logger are affected by this method. + """ + handlers = _get_library_root_logger().handlers + + for handler in handlers: + formatter = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s") + handler.setFormatter(formatter) + + +def reset_format() -> None: + """ + Resets the formatting for HuggingFace Transformers's loggers. + + All handlers currently bound to the root logger are affected by this method. + """ + handlers = _get_library_root_logger().handlers + + for handler in handlers: + handler.setFormatter(None) + + +def warning_advice(self, *args, **kwargs): + """ + This method is identical to `logger.warning()`, but if env var TRANSFORMERS_NO_ADVISORY_WARNINGS=1 is set, this + warning will not be printed + """ + no_advisory_warnings = os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS") + if no_advisory_warnings: + return + self.warning(*args, **kwargs) + + +logging.Logger.warning_advice = warning_advice # type: ignore[unresolved-attribute] + + +@functools.lru_cache(None) +def warning_once(self, *args, **kwargs): + """ + This method is identical to `logger.warning()`, but will emit the warning with the same message only once + + Note: The cache is for the function arguments, so 2 different callers using the same arguments will hit the cache. + The assumption here is that all warning messages are unique across the code. If they aren't then need to switch to + another type of cache that includes the caller frame information in the hashing function. + """ + self.warning(*args, **kwargs) + + +logging.Logger.warning_once = warning_once # type: ignore[unresolved-attribute] + + +@functools.lru_cache(None) +def info_once(self, *args, **kwargs): + """ + This method is identical to `logger.info()`, but will emit the info with the same message only once + + Note: The cache is for the function arguments, so 2 different callers using the same arguments will hit the cache. + The assumption here is that all warning messages are unique across the code. If they aren't then need to switch to + another type of cache that includes the caller frame information in the hashing function. + """ + self.info(*args, **kwargs) + + +logging.Logger.info_once = info_once # type: ignore[unresolved-attribute] + + +class EmptyTqdm: + """Dummy tqdm which doesn't do anything.""" + + def __init__(self, *args, **kwargs): # pylint: disable=unused-argument + self._iterator = args[0] if args else None + + def __iter__(self): + return iter(self._iterator) + + def __getattr__(self, _): + """Return empty function.""" + + def empty_fn(*args, **kwargs): # pylint: disable=unused-argument + return + + return empty_fn + + def __enter__(self): + return self + + def __exit__(self, type_, value, traceback): + return + + +class _tqdm_cls: + def __call__(self, *args, **kwargs): + factory = tqdm_lib.tqdm if _tqdm_active else EmptyTqdm + if _tqdm_hook is not None: + return _tqdm_hook(factory, args, kwargs) + return factory(*args, **kwargs) + + def set_lock(self, *args, **kwargs): + self._lock = None + if _tqdm_active: + return tqdm_lib.tqdm.set_lock(*args, **kwargs) + + def get_lock(self): + if _tqdm_active: + return tqdm_lib.tqdm.get_lock() + + +tqdm = _tqdm_cls() + + +def is_progress_bar_enabled() -> bool: + """Return a boolean indicating whether tqdm progress bars are enabled.""" + return bool(_tqdm_active) + + +def enable_progress_bar(): + """Enable tqdm progress bar.""" + global _tqdm_active + _tqdm_active = True + hf_hub_utils.enable_progress_bars() + + +def disable_progress_bar(): + """Disable tqdm progress bar.""" + global _tqdm_active + _tqdm_active = False + hf_hub_utils.disable_progress_bars() + + +def set_tqdm_hook(hook: Callable[[Callable[..., Any], tuple[Any, ...], dict[str, Any]], Any] | None): + """ + Set a hook that customizes tqdm creation. + + The hook is called with the tqdm factory to use (either `tqdm.auto.tqdm` or an empty shim), along with the + positional and keyword arguments that would have been passed to tqdm. The hook should return an object compatible + with tqdm (i.e. implementing the methods your code relies on, such as `update`, `close`, context manager methods, + etc.). + + Passing `None` clears the hook. + + Returns: + The previous hook, which can be restored later. + """ + global _tqdm_hook + previous_hook = _tqdm_hook + _tqdm_hook = hook + return previous_hook diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/metrics.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..e62fa846ae022b1ee287ad02752ca0ee7910387f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/metrics.py @@ -0,0 +1,405 @@ +import functools +import logging +import time +from collections.abc import Callable +from enum import Enum +from typing import Any + +from .import_utils import is_opentelemetry_available + + +class RequestStatus(Enum): + """Status of a generation request through its lifecycle.""" + + PENDING = "pending" + PREFILLING = "prefilling" + PREFILLING_SPLIT = "prefilling_split" + SPLIT_PENDING_REMAINDER = "split_pending_remainder" + DECODING = "decoding" + FINISHED = "finished" + FAILED = "failed" + + +if is_opentelemetry_available(): + from opentelemetry import metrics + from opentelemetry.trace import Status, StatusCode, get_tracer + + _has_opentelemetry = True +else: + _has_opentelemetry = False + + +def attach_tracer(tracer_name_template=None): + """ + Decorator that attaches a tracer to a class. + + This decorator should be applied to classes that need OpenTelemetry tracing. + It adds a tracer attribute to the class instance that can be used by the traced decorator. + + Args: + tracer_name_template: Optional template string for the tracer name. + If provided, it should contain {module} which will be replaced with the class's full module path + and {class_name} for the class name. + If None, a default naming scheme will be used where: + - If the module already starts with "transformers.", it will use that directly + - Otherwise, it will prepend "transformers." to the module name + + Returns: + Class decorator function + """ + if not _has_opentelemetry: + return lambda cls: cls + + def decorator(cls): + original_init = cls.__init__ + + @functools.wraps(original_init) + def init_with_tracer(self, *args, **kwargs): + original_init(self, *args, **kwargs) + + module_name = cls.__module__ + class_name = cls.__qualname__ + + if tracer_name_template is None: + if module_name.startswith("transformers."): + tracer_name = f"{module_name}.{class_name}" + else: + tracer_name = f"transformers.{module_name}.{class_name}" + else: + tracer_name = tracer_name_template.format(module=module_name, class_name=class_name) + + self.tracer = get_tracer(tracer_name) + + cls.__init__ = init_with_tracer + return cls + + return decorator + + +def traced( + func=None, + *, + span_name=None, + standalone=False, + additional_attributes: list[tuple[str, str, Any | Callable[[Any], Any]]] | None = None, +): + """ + Decorator to trace function calls with OpenTelemetry. + + Can be used as @traced or @traced(span_name="custom_name") + + Args: + func: The function to trace + span_name: Optional custom name for the span (defaults to function name) + standalone: If True, creates a parentless span + additional_attributes: Optional list of additional attributes to set on the span. + Each item is a tuple of (instance_attribute_name, span_attribute_key, value_or_transform_function) + where: + - instance_attribute_name: Name of the attribute to get from the class instance + - span_attribute_key: Key to use when setting the attribute on the span + - value_or_transform_function: Either a raw value to use directly, or a function to transform + the attribute value before setting it on the span + + Returns: + Decorated function with tracing + """ + + def decorator(func): + if not _has_opentelemetry: + return func + + @functools.wraps(func) + def wrapper(*args, **kwargs): + instance = args[0] if args and (hasattr(func, "__self__") and func.__self__ is not None) else None + is_method = instance is not None + + if is_method and hasattr(instance, "tracer"): + tracer = instance.tracer + else: + tracer = get_tracer(f"transformers.{func.__module__}.{func.__name__}") + + name = span_name or func.__name__ + span_fn = tracer.start_span if standalone else tracer.start_as_current_span + with span_fn(name) as span: + span.set_attribute("function.name", func.__name__) + span.set_attribute("function.module", func.__module__) + span.set_attribute("function.is_method", is_method) + + if args: + for i, arg in enumerate(args): + if isinstance(arg, (str, int, float, bool)) or arg is None: + span.set_attribute(f"args.{i}", str(arg)) + else: + span.set_attribute(f"args.{i}", str(type(arg))) + if kwargs: + for key, value in kwargs.items(): + if isinstance(value, (str, int, float, bool)) or value is None: + span.set_attribute(f"kwargs.{key}", str(value)) + else: + span.set_attribute(f"kwargs.{key}", str(type(value))) + + if additional_attributes and is_method: + for attr_config in additional_attributes: + instance_attribute_name, span_attribute_key, value_or_transform_function = attr_config + if hasattr(instance, instance_attribute_name): + attribute_value = getattr(instance, instance_attribute_name) + if callable(value_or_transform_function): + transformed_value = value_or_transform_function(attribute_value) + else: + transformed_value = value_or_transform_function + span.set_attribute(span_attribute_key, transformed_value) + + try: + result = func(*args, **kwargs) + return result + except Exception as e: + span.set_status(Status(StatusCode.ERROR)) + span.record_exception(e) + raise + + return wrapper + + if func is None: + return decorator + return decorator(func) + + +logger = logging.getLogger(__name__) + + +@attach_tracer() +class ContinuousBatchProcessorMetrics: + """Metrics collection for ContinuousBatchProcessor.""" + + def __init__(self, max_batch_tokens: int): + """Initialize metrics for continuous batch processor. + + Args: + max_batch_tokens: Maximum number of tokens in a batch + """ + self.max_batch_tokens = max_batch_tokens + + self._setup_metrics() + + def _setup_metrics(self): + """Initialize OpenTelemetry metrics and tracing if the library is available.""" + + if not _has_opentelemetry: + logger.info( + "OpenTelemetry is not installed. Metrics and tracing will not be recorded." + "You can install it with `pip install opentelemetry-api>=1.30.0`" + ) + return + + self.meter = metrics.get_meter("transformers.generation.continuous_batch_processor") + + # Define appropriate buckets for TTFT (typically ranges from ~50ms to several seconds) + ttft_buckets = [10, 25, 50, 75, 100, 150, 200, 300, 500, 750, 1000, 2000, 5000, 10000] + + self.ttft_histogram = self.meter.create_histogram( + name="ttft_milliseconds", + description="Time to first token in milliseconds", + unit="ms", + explicit_bucket_boundaries_advisory=ttft_buckets, + ) + + self.active_requests_gauge = self.meter.create_gauge( + name="active_requests_count", + description="Number of active requests currently being processed", + unit="requests", + ) + + self.waiting_requests_gauge = self.meter.create_gauge( + name="waiting_requests_count", + description="Number of requests waiting to be processed", + unit="requests", + ) + + # Define appropriate buckets for request latency (similar to TTFT but with higher upper bounds) + latency_buckets = [50, 100, 250, 500, 1000, 2000, 5000, 10000, 20000, 30000, 60000] + + self.request_latency_histogram = self.meter.create_histogram( + name="request_latency_milliseconds", + description="End-to-end latency for completed requests in milliseconds", + unit="ms", + explicit_bucket_boundaries_advisory=latency_buckets, + ) + + self.decode_prefill_ratio_gauge = self.meter.create_gauge( + name="decode_prefill_ratio", + description="Ratio of decode tokens to prefill tokens in a batch", + unit="ratio", + ) + + self.prefill_tokens_counter = self.meter.create_counter( + name="prefill_tokens_processed", + description="Number of prefill tokens processed", + unit="tokens", + ) + + self.decode_tokens_counter = self.meter.create_counter( + name="decode_tokens_processed", + description="Number of decode tokens processed", + unit="tokens", + ) + + # Define appropriate buckets for batch fill percentage (0-100%) + batch_fill_buckets = [5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 98, 100] + + self.batch_fill_percentage_histogram = self.meter.create_histogram( + name="batch_fill_percentage", + description="Percentage of max_batch_tokens utilized in each batch", + unit="percent", + explicit_bucket_boundaries_advisory=batch_fill_buckets, + ) + + self.kv_cache_free_memory_gauge = self.meter.create_gauge( + name="kv_cache_free_memory_bytes", + description="Free memory of the PagedAttentionCache in bytes", + unit="bytes", + ) + + self.kv_cache_memory_gauge = self.meter.create_gauge( + name="kv_cache_memory_bytes", + description="Memory usage of the PagedAttentionCache in bytes", + unit="bytes", + ) + + @traced + def record_ttft_metric(self, created_time: float, request_id: str) -> None: + """Record Time to First Token (TTFT). + + Args: + created_time: The time the request was created + request_id: The ID of the request + """ + if not _has_opentelemetry: + return + + ttft_ms = (time.time() - created_time) * 1000.0 + + try: + self.ttft_histogram.record(ttft_ms) + logger.debug(f"Recorded TTFT for request {request_id}: {ttft_ms:.2f}ms") + except Exception as e: + logger.warning(f"Failed to record TTFT metric: {e}") + + @traced + def record_batch_metrics(self, future_states: list) -> None: + """Record metrics about the batch composition including decode/prefill ratio and batch fill percentage. + + Args: + requests_in_batch: List of request states in the current batch + """ + if not _has_opentelemetry or not future_states: + return + + decode_tokens = 0 + prefill_tokens = 0 + + for future_state in future_states: + state = future_state.state + if state.status == RequestStatus.DECODING: + decode_tokens += 1 + elif state.status in [RequestStatus.PREFILLING, RequestStatus.PREFILLING_SPLIT]: + prefill_tokens += len(state.prompt_ids) + + total_batch_tokens = decode_tokens + prefill_tokens + + try: + if prefill_tokens > 0: + self.prefill_tokens_counter.add(prefill_tokens) + + if decode_tokens > 0: + self.decode_tokens_counter.add(decode_tokens) + + if prefill_tokens > 0: + ratio = decode_tokens / prefill_tokens + self.decode_prefill_ratio_gauge.set(ratio) + + fill_percentage = (total_batch_tokens / self.max_batch_tokens) * 100.0 + self.batch_fill_percentage_histogram.record(fill_percentage) + logger.debug( + f"Batch metrics: {decode_tokens} decode tokens, {prefill_tokens} prefill tokens, " + f"batch fill: {fill_percentage:.2f}% ({total_batch_tokens}/{self.max_batch_tokens})" + ) + except Exception as e: + logger.warning(f"Failed to record batch metrics: {e}") + + @traced + def record_kv_cache_memory_metrics(self, cache) -> None: + """Record memory usage of the PagedAttentionCache without GPU synchronization. + + This calculates the theoretical memory usage based on cache configuration + and the number of blocks currently in use. + + Args: + cache: The PagedAttentionCache object to measure + """ + if not _has_opentelemetry: + return + + try: + # Retrieve the memory footprint of the cache + page_size = cache.head_dim * cache.num_key_value_heads + page_mem_in_bytes = page_size * cache.dtype.itemsize + # When a block is allocated, it is for both K and V, so we multiply by 2 + # It's also allocated across all cache tensors, so we multiply by the nb of tensors: len(cache.key_cache) + block_mem_in_bytes = 2 * len(cache.key_cache) * cache.block_size * page_mem_in_bytes + + # Retrieve the number of used and free blocks + free_blocks = cache.get_num_free_blocks() + used_blocks = cache.num_blocks - free_blocks + + # Convert that into used and free memory in bytes + used_memory_bytes = used_blocks * block_mem_in_bytes + free_memory_bytes = free_blocks * block_mem_in_bytes + + # Update the telemetry gauges and add a message in the logs + self.kv_cache_memory_gauge.set(used_memory_bytes) + self.kv_cache_free_memory_gauge.set(free_memory_bytes) + logger.debug( + f"KV Cache memory: {used_memory_bytes / (1024 * 1024):.2f}MB, " + f"Used blocks: {used_blocks}/{cache.num_blocks} " + f"({used_blocks / cache.num_blocks * 100:.1f}%)" + ) + except Exception as e: + logger.warning(f"Failed to record KV cache memory metrics: {e}") + + @traced + def record_queue_metrics(self, active_requests: int, waiting_requests: int) -> None: + """Record metrics about active and waiting requests. + + Args: + active_requests: Number of active requests + waiting_requests: Number of waiting requests + """ + if not _has_opentelemetry: + return + + try: + self.active_requests_gauge.set(active_requests) + self.waiting_requests_gauge.set(waiting_requests) + logger.debug(f"Queue metrics: {active_requests} active requests, {waiting_requests} waiting requests") + except Exception as e: + logger.warning(f"Failed to record queue metrics: {e}") + + @traced + def record_request_completion(self, created_time: float, request_id: str) -> None: + """Record metrics about a completed request. + + Args: + created_time: The time the request was created + request_id: The ID of the request + """ + if not _has_opentelemetry: + return + + latency_ms = (time.time() - created_time) * 1000.0 + + try: + self.request_latency_histogram.record(latency_ms) + + logger.debug(f"Recorded request completion for {request_id}: {latency_ms:.2f}ms") + except Exception as e: + logger.warning(f"Failed to record request completion metric: {e}") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/network_logging.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/network_logging.py new file mode 100644 index 0000000000000000000000000000000000000000..92f74ccd6d181bfa8b0fcf8a6fbfd8a39a19b4b8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/network_logging.py @@ -0,0 +1,485 @@ +# Copyright 2026 The HuggingFace Team. All rights reserved. +# +# 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. + +from __future__ import annotations + +import inspect +import json +import os +import threading +import time +from collections import defaultdict +from functools import wraps +from pathlib import Path +from typing import Any + +import httpx + +from .generic import strtobool + + +class _NetworkRequestTrace: + def __init__(self, request: httpx.Request): + self.request = request + self.started_at = time.perf_counter() + self.phase_started_at = {} + self.phases_ms = defaultdict(float) + + def trace(self, name: str, info: dict[str, Any]) -> None: + parts = name.rsplit(".", 2) + if len(parts) != 3: + return + + _, phase, state = parts + now = time.perf_counter() + if state == "started": + self.phase_started_at[phase] = now + elif state in {"complete", "failed"}: + phase_started_at = self.phase_started_at.pop(phase, None) + if phase_started_at is not None: + self.phases_ms[phase] += (now - phase_started_at) * 1000 + + def build_record( + self, + *, + response: httpx.Response | None = None, + error: BaseException | None = None, + stream: bool = False, + ) -> dict[str, Any]: + total_ms = (time.perf_counter() - self.started_at) * 1000 + url = self.request.url + host = url.host or "" + port = url.port + default_port = {"http": 80, "https": 443}.get(url.scheme) + host_display = host if port in (None, default_port) else f"{host}:{port}" + + http_version = None + status_code = None + bytes_downloaded = None + response_complete = False + if response is not None: + status_code = response.status_code + response_complete = response.is_closed + raw_http_version = response.extensions.get("http_version") + if isinstance(raw_http_version, bytes): + http_version = raw_http_version.decode("ascii", errors="replace") + elif raw_http_version is not None: + http_version = str(raw_http_version) + + if response_complete: + try: + bytes_downloaded = len(response.content) + except httpx.ResponseNotRead: + pass + + return { + "method": self.request.method, + "scheme": url.scheme, + "host": host, + "host_display": host_display, + "port": port, + "path": url.path, + "has_query": bool(url.query), + "url": f"{url.scheme}://{host_display}{url.path}{'?...' if url.query else ''}", + "request_id": self.request.headers.get("x-amzn-trace-id") or self.request.headers.get("x-request-id"), + "status_code": status_code, + "http_version": http_version, + "bytes_downloaded": bytes_downloaded, + "total_ms": total_ms, + "stream": stream, + "response_complete": response_complete, + "phases_ms": dict(sorted(self.phases_ms.items())), + "error": None if error is None else f"{type(error).__name__}: {error}", + } + + +class _NetworkDebugProfiler: + def __init__(self): + self._records = [] + self._lock = threading.Lock() + self._enabled = False + self._output_path = None + self._original_client_send = None + self._original_async_client_send = None + self._shared_dir = None + + @property + def enabled(self) -> bool: + return self._enabled + + def clear(self) -> None: + with self._lock: + self._records = [] + + def enable(self, output_path: str | os.PathLike | None = None) -> None: + if self._enabled: + self._output_path = None if output_path is None else os.fspath(output_path) + self.clear() + return + + self._output_path = None if output_path is None else os.fspath(output_path) + self.clear() + + profiler = self + self._original_client_send = httpx.Client.send + self._original_async_client_send = httpx.AsyncClient.send + + @wraps(self._original_client_send) + def patched_client_send(client, request, *args, **kwargs): + return profiler._send_with_trace(profiler._original_client_send, client, request, *args, **kwargs) + + @wraps(self._original_async_client_send) + async def patched_async_client_send(client, request, *args, **kwargs): + return await profiler._async_send_with_trace( + profiler._original_async_client_send, client, request, *args, **kwargs + ) + + httpx.Client.send = patched_client_send + httpx.AsyncClient.send = patched_async_client_send + self._enabled = True + + def setup_shared_dir(self) -> str | None: + """Create a shared temp directory for xdist workers to dump records into.""" + if self._shared_dir is None: + import tempfile + + self._shared_dir = tempfile.mkdtemp(prefix="network_debug_") + return self._shared_dir + + def set_shared_dir(self, shared_dir: str) -> None: + """Set the shared directory (called in xdist workers).""" + self._shared_dir = shared_dir + + def dump_worker_records(self, worker_id: str | None = None) -> None: + """Write this process's records to a file in the shared directory (called in workers).""" + if not self._shared_dir or not self._records: + return + worker_id = worker_id or f"pid{os.getpid()}" + dump_path = os.path.join(self._shared_dir, f"records_{worker_id}.json") + with self._lock: + records = [{**record, "phases_ms": dict(record["phases_ms"])} for record in self._records] + Path(dump_path).write_text(json.dumps(records), encoding="utf-8") + + def load_worker_records(self) -> None: + """Load all worker record files from the shared directory (called in controller).""" + if not self._shared_dir or not os.path.isdir(self._shared_dir): + return + import glob as glob_module + + for record_file in glob_module.glob(os.path.join(self._shared_dir, "records_*.json")): + try: + records = json.loads(Path(record_file).read_text(encoding="utf-8")) + with self._lock: + for record in records: + record["phases_ms"] = defaultdict(float, record.get("phases_ms", {})) + self._records.append(record) + except (OSError, json.JSONDecodeError): + pass + + def cleanup_shared_dir(self) -> None: + """Remove the shared temp directory.""" + if self._shared_dir and os.path.isdir(self._shared_dir): + import shutil + + shutil.rmtree(self._shared_dir, ignore_errors=True) + self._shared_dir = None + + def disable(self) -> None: + if not self._enabled: + return + + httpx.Client.send = self._original_client_send + httpx.AsyncClient.send = self._original_async_client_send + self._enabled = False + self._original_client_send = None + self._original_async_client_send = None + self._output_path = None + self.clear() + + def _append_record(self, record: dict[str, Any]) -> None: + with self._lock: + self._records.append(record) + + def _wrap_trace_callback(self, request: httpx.Request, trace: _NetworkRequestTrace): + existing_trace = request.extensions.get("trace") + + def wrapped_trace(name: str, info: dict[str, Any]) -> Any: + trace.trace(name, info) + if existing_trace is not None: + return existing_trace(name, info) + return None + + return wrapped_trace + + async def _awrap_trace_callback(self, request: httpx.Request, trace: _NetworkRequestTrace): + existing_trace = request.extensions.get("trace") + + async def wrapped_trace(name: str, info: dict[str, Any]) -> Any: + trace.trace(name, info) + if existing_trace is not None: + result = existing_trace(name, info) + if inspect.isawaitable(result): + return await result + return result + return None + + return wrapped_trace + + def _send_with_trace(self, original_send, client, request: httpx.Request, *args, **kwargs): + trace = _NetworkRequestTrace(request) + request.extensions = dict(request.extensions) + request.extensions["trace"] = self._wrap_trace_callback(request, trace) + + try: + response = original_send(client, request, *args, **kwargs) + except Exception as error: + self._append_record(trace.build_record(error=error, stream=kwargs.get("stream", False))) + raise + + self._append_record(trace.build_record(response=response, stream=kwargs.get("stream", False))) + return response + + async def _async_send_with_trace(self, original_send, client, request: httpx.Request, *args, **kwargs): + trace = _NetworkRequestTrace(request) + request.extensions = dict(request.extensions) + request.extensions["trace"] = await self._awrap_trace_callback(request, trace) + + try: + response = await original_send(client, request, *args, **kwargs) + except Exception as error: + self._append_record(trace.build_record(error=error, stream=kwargs.get("stream", False))) + raise + + self._append_record(trace.build_record(response=response, stream=kwargs.get("stream", False))) + return response + + def build_report(self) -> dict[str, Any]: + with self._lock: + records = [ + { + **record, + "phases_ms": dict(record["phases_ms"]), + } + for record in self._records + ] + + phase_totals_ms = defaultdict(float) + route_totals = {} + for record in records: + for phase, duration_ms in record["phases_ms"].items(): + phase_totals_ms[phase] += duration_ms + + route_key = (record["method"], record["host_display"], record["path"]) + route_total = route_totals.setdefault( + route_key, + { + "method": record["method"], + "host_display": record["host_display"], + "path": record["path"], + "count": 0, + "failures": 0, + "total_ms": 0.0, + "phase_totals_ms": defaultdict(float), + }, + ) + route_total["count"] += 1 + route_total["total_ms"] += record["total_ms"] + route_total["failures"] += int(record["error"] is not None) + for phase, duration_ms in record["phases_ms"].items(): + route_total["phase_totals_ms"][phase] += duration_ms + + routes = [] + for route_total in route_totals.values(): + route_total["avg_ms"] = route_total["total_ms"] / route_total["count"] + route_total["phase_totals_ms"] = dict(sorted(route_total["phase_totals_ms"].items())) + routes.append(route_total) + + routes.sort(key=lambda route: route["total_ms"], reverse=True) + total_time_ms = sum(record["total_ms"] for record in records) + return { + "enabled": self._enabled, + "output_path": self._output_path, + "total_requests": len(records), + "failed_requests": sum(int(record["error"] is not None) for record in records), + "total_time_ms": total_time_ms, + "phase_totals_ms": dict(sorted(phase_totals_ms.items())), + "requests": records, + "routes": routes, + } + + def maybe_write_report(self) -> str | None: + if self._output_path is None: + return None + + report_path = Path(self._output_path) + report_path.parent.mkdir(parents=True, exist_ok=True) + report_path.write_text(json.dumps(self.build_report(), indent=2, sort_keys=True), encoding="utf-8") + return str(report_path) + + +_NETWORK_DEBUG_PROFILER = _NetworkDebugProfiler() + + +_DEFAULT_REPORT_PATH = "network_debug_report.json" + + +def _parse_network_debug_env() -> tuple[bool, str]: + enabled_raw = os.environ.get("NETWORK_DEBUG_REPORT", "").strip() + try: + enabled = bool(strtobool(enabled_raw)) if enabled_raw else False + except ValueError: + enabled = False + + output_path = os.environ.get("NETWORK_DEBUG_REPORT_PATH", "").strip() or _DEFAULT_REPORT_PATH + return enabled, output_path + + +def _enable_network_debug_report(output_path: str | os.PathLike | None = None) -> None: + _NETWORK_DEBUG_PROFILER.enable(output_path=output_path) + + +def _disable_network_debug_report() -> None: + _NETWORK_DEBUG_PROFILER.disable() + + +def _clear_network_debug_report() -> None: + _NETWORK_DEBUG_PROFILER.clear() + + +def _get_network_debug_report() -> dict[str, Any]: + return _NETWORK_DEBUG_PROFILER.build_report() + + +def _enable_network_debug_report_from_env() -> bool: + enabled, output_path = _parse_network_debug_env() + if not enabled: + return False + + _enable_network_debug_report(output_path=output_path) + return True + + +def _format_network_debug_report(max_requests: int = 20, max_routes: int = 10) -> str: + report = _get_network_debug_report() + if report["total_requests"] == 0: + return "Network debug report: no httpx requests captured." + + lines = [ + "Network debug report", + f"Requests captured: {report['total_requests']}", + f"Failed requests: {report['failed_requests']}", + f"Cumulative request time: {report['total_time_ms']:.1f} ms", + ] + + if report["phase_totals_ms"]: + phase_summary = ", ".join( + f"{phase}={duration_ms:.1f} ms" + for phase, duration_ms in sorted(report["phase_totals_ms"].items(), key=lambda item: item[1], reverse=True) + ) + lines.append(f"Phase totals: {phase_summary}") + + lines.append("") + lines.append("Slowest requests:") + for idx, record in enumerate( + sorted(report["requests"], key=lambda request: request["total_ms"], reverse=True)[:max_requests], + start=1, + ): + status = record["error"] or f"status={record['status_code']}" + phase_bits = [] + for phase in ("connect_tcp", "start_tls", "receive_response_headers", "receive_response_body"): + duration_ms = record["phases_ms"].get(phase) + if duration_ms is not None: + phase_bits.append(f"{phase}={duration_ms:.1f} ms") + phase_suffix = f" ({', '.join(phase_bits)})" if phase_bits else "" + incomplete_suffix = " incomplete" if record["stream"] and not record["response_complete"] else "" + lines.append( + f"{idx:>2}. {record['method']} {record['url']} {record['total_ms']:.1f} ms {status}{incomplete_suffix}{phase_suffix}" + ) + + lines.append("") + lines.append("Slowest routes:") + for idx, route in enumerate(report["routes"][:max_routes], start=1): + lines.append( + f"{idx:>2}. {route['method']} {route['host_display']}{route['path']} count={route['count']} " + f"total={route['total_ms']:.1f} ms avg={route['avg_ms']:.1f} ms failures={route['failures']}" + ) + + return "\n".join(lines) + + +class NetworkDebugPlugin: + """Pytest plugin that handles all network debug orchestration including xdist coordination.""" + + def pytest_configure(self, config): + _enable_network_debug_report_from_env() + if not _NETWORK_DEBUG_PROFILER.enabled: + return + + # xdist controller: create shared dir for workers to dump network records + if not hasattr(config, "workerinput"): + shared_dir = _NETWORK_DEBUG_PROFILER.setup_shared_dir() + if shared_dir: + config._network_debug_shared_dir = shared_dir + else: + # xdist worker: receive shared dir from controller + shared_dir = config.workerinput.get("network_debug_shared_dir") + if shared_dir: + _NETWORK_DEBUG_PROFILER.set_shared_dir(shared_dir) + + def pytest_configure_node(self, node): + """xdist hook: called on the controller to configure each worker node.""" + shared_dir = getattr(node.config, "_network_debug_shared_dir", None) + if shared_dir: + node.workerinput["network_debug_shared_dir"] = shared_dir + + def pytest_sessionfinish(self, session, exitstatus): + # xdist worker: dump network debug records for the controller to aggregate + if hasattr(session.config, "workerinput"): + worker_id = session.config.workerinput.get("workerid", f"pid{os.getpid()}") + _NETWORK_DEBUG_PROFILER.dump_worker_records(worker_id=worker_id) + + def pytest_terminal_summary(self, terminalreporter): + if not _NETWORK_DEBUG_PROFILER.enabled: + return + + # Skip report generation in xdist worker processes; only the controller should aggregate and report. + if hasattr(terminalreporter.config, "workerinput"): + return + + # Aggregate worker records if running under xdist. + _NETWORK_DEBUG_PROFILER.load_worker_records() + + report_path = None + try: + report_path = _NETWORK_DEBUG_PROFILER.maybe_write_report() + except OSError as error: + report_path = f"Failed to write JSON report: {error}" + + terminalreporter.section("Network debug", sep="=") + for line in _format_network_debug_report().splitlines(): + terminalreporter.write_line(line) + if report_path is not None: + terminalreporter.write_line(f"JSON report: {report_path}") + + _NETWORK_DEBUG_PROFILER.cleanup_shared_dir() + + +def register_network_debug_plugin(config) -> None: + """Register the network debug pytest plugin. Single entry point for conftest.py.""" + config.pluginmanager.register(NetworkDebugPlugin(), "network_debug") + + +__all__ = [ + "register_network_debug_plugin", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/notebook.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/notebook.py new file mode 100644 index 0000000000000000000000000000000000000000..1c7fb7a77bea87d90c51f7823247f6318ca3d3b0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/notebook.py @@ -0,0 +1,408 @@ +# Copyright 2020 Hugging Face +# +# 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. + +import os +import re +import time +from typing import Optional, TypeVar + +import IPython.display as disp + +from ..trainer_callback import TrainerCallback +from ..trainer_utils import IntervalStrategy, has_length + + +_T = TypeVar("_T") + + +def _require(x: _T | None, msg: str) -> _T: + if x is None: + raise RuntimeError(msg) + return x + + +def format_time(t): + "Format `t` (in seconds) to (h):mm:ss" + t = int(t) + h, m, s = t // 3600, (t // 60) % 60, t % 60 + return f"{h}:{m:02d}:{s:02d}" if h != 0 else f"{m:02d}:{s:02d}" + + +def html_progress_bar(value, total, prefix, label, width=300): + # docstyle-ignore + return f""" +
+ {prefix} + + {label} +
+ """ + + +def text_to_html_table(items): + "Put the texts in `items` in an HTML table." + html_code = """\n""" + html_code += """ \n \n""" + for i in items[0]: + html_code += f" \n" + html_code += " \n \n \n" + for line in items[1:]: + html_code += " \n" + for elt in line: + elt = f"{elt:.6f}" if isinstance(elt, float) else str(elt) + html_code += f" \n" + html_code += " \n" + html_code += " \n
{i}
{elt}

" + return html_code + + +class NotebookProgressBar: + """ + A progress par for display in a notebook. + + Class attributes (overridden by derived classes) + + - **warmup** (`int`) -- The number of iterations to do at the beginning while ignoring `update_every`. + - **update_every** (`float`) -- Since calling the time takes some time, we only do it every presumed + `update_every` seconds. The progress bar uses the average time passed up until now to guess the next value + for which it will call the update. + + Args: + total (`int`): + The total number of iterations to reach. + prefix (`str`, *optional*): + A prefix to add before the progress bar. + leave (`bool`, *optional*, defaults to `True`): + Whether or not to leave the progress bar once it's completed. You can always call the + [`~utils.notebook.NotebookProgressBar.close`] method to make the bar disappear. + parent ([`~notebook.NotebookTrainingTracker`], *optional*): + A parent object (like [`~utils.notebook.NotebookTrainingTracker`]) that spawns progress bars and handle + their display. If set, the object passed must have a `display()` method. + width (`int`, *optional*, defaults to 300): + The width (in pixels) that the bar will take. + + Example: + + ```python + import time + + pbar = NotebookProgressBar(100) + for val in range(100): + pbar.update(val) + time.sleep(0.07) + pbar.update(100) + ```""" + + warmup = 5 + update_every = 0.2 + + def __init__( + self, + total: int, + prefix: str | None = None, + leave: bool = True, + parent: Optional["NotebookTrainingTracker"] = None, + width: int = 300, + ): + self.total = total + self.prefix = "" if prefix is None else prefix + self.leave = leave + self.parent = parent + self.width = width + self.last_value = None + self.comment = None + self.output = None + self.value = None + self.label = None + if "VSCODE_PID" in os.environ: + self.update_every = 0.5 # Adjusted for smooth updated as html rending is slow on VS Code + # This is the only adjustment required to optimize training html rending + + def update(self, value: int, force_update: bool = False, comment: str | None = None): + """ + The main method to update the progress bar to `value`. + + Args: + value (`int`): + The value to use. Must be between 0 and `total`. + force_update (`bool`, *optional*, defaults to `False`): + Whether or not to force and update of the internal state and display (by default, the bar will wait for + `value` to reach the value it predicted corresponds to a time of more than the `update_every` attribute + since the last update to avoid adding boilerplate). + comment (`str`, *optional*): + A comment to add on the left of the progress bar. + """ + self.value = value + if comment is not None: + self.comment = comment + if self.last_value is None: + self.start_time = self.last_time = time.time() + self.start_value = self.last_value = value + self.elapsed_time = self.predicted_remaining = None + self.first_calls = self.warmup + self.wait_for = 1 + self.update_bar(value) + elif value <= self.last_value and not force_update: + return + elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for, self.total): + if self.first_calls > 0: + self.first_calls -= 1 + current_time = time.time() + self.elapsed_time = current_time - self.start_time + # We could have value = self.start_value if the update is called twixe with the same start value. + if value > self.start_value: + self.average_time_per_item = self.elapsed_time / (value - self.start_value) + else: + self.average_time_per_item = None + if value >= self.total: + value = self.total + self.predicted_remaining = None + if not self.leave: + self.close() + elif self.average_time_per_item is not None: + self.predicted_remaining = self.average_time_per_item * (self.total - value) + self.update_bar(value) + self.last_value = value + self.last_time = current_time + if (self.average_time_per_item is None) or (self.average_time_per_item == 0): + self.wait_for = 1 + else: + self.wait_for = max(int(self.update_every / self.average_time_per_item), 1) + + def update_bar(self, value, comment=None): + spaced_value = " " * (len(str(self.total)) - len(str(value))) + str(value) + if self.elapsed_time is None: + self.label = f"[{spaced_value}/{self.total} : < :" + elif self.predicted_remaining is None: + self.label = f"[{spaced_value}/{self.total} {format_time(self.elapsed_time)}" + else: + self.label = ( + f"[{spaced_value}/{self.total} {format_time(self.elapsed_time)} <" + f" {format_time(self.predicted_remaining)}" + ) + if self.average_time_per_item == 0: + self.label += ", +inf it/s" + else: + self.label += f", {1 / self.average_time_per_item:.2f} it/s" + + self.label += "]" if self.comment is None or len(self.comment) == 0 else f", {self.comment}]" + self.display() + + def display(self): + self.html_code = html_progress_bar(self.value, self.total, self.prefix, self.label, self.width) + if self.parent is not None: + # If this is a child bar, the parent will take care of the display. + self.parent.display() + return + if self.output is None: + self.output = disp.display(disp.HTML(self.html_code), display_id=True) + else: + self.output.update(disp.HTML(self.html_code)) + + def close(self): + "Closes the progress bar." + if self.parent is None and self.output is not None: + self.output.update(disp.HTML("")) + + +class NotebookTrainingTracker(NotebookProgressBar): + """ + An object tracking the updates of an ongoing training with progress bars and a nice table reporting metrics. + + Args: + num_steps (`int`): The number of steps during training. column_names (`list[str]`, *optional*): + The list of column names for the metrics table (will be inferred from the first call to + [`~utils.notebook.NotebookTrainingTracker.write_line`] if not set). + """ + + def __init__(self, num_steps, column_names=None): + super().__init__(num_steps) + self.inner_table = None if column_names is None else [column_names] + self.child_bar = None + + def display(self): + self.html_code = html_progress_bar(self.value, self.total, self.prefix, self.label, self.width) + if self.inner_table is not None: + self.html_code += text_to_html_table(self.inner_table) + if self.child_bar is not None: + self.html_code += self.child_bar.html_code + if self.output is None: + self.output = disp.display(disp.HTML(self.html_code), display_id=True) + else: + self.output.update(disp.HTML(self.html_code)) + + def write_line(self, values): + """ + Write the values in the inner table. + + Args: + values (`dict[str, float]`): The values to display. + """ + if self.inner_table is None: + self.inner_table = [list(values.keys()), list(values.values())] + else: + columns = self.inner_table[0] + for key in values: + if key not in columns: + columns.append(key) + self.inner_table[0] = columns + if len(self.inner_table) > 1: + last_values = self.inner_table[-1] + first_column = self.inner_table[0][0] + if last_values[0] != values[first_column]: + # write new line + self.inner_table.append([values.get(c, "No Log") for c in columns]) + else: + # update last line + new_values = values + for c in columns: + if c not in new_values: + new_values[c] = last_values[columns.index(c)] + self.inner_table[-1] = [new_values[c] for c in columns] + else: + self.inner_table.append([values[c] for c in columns]) + + def add_child(self, total, prefix=None, width=300): + """ + Add a child progress bar displayed under the table of metrics. The child progress bar is returned (so it can be + easily updated). + + Args: + total (`int`): The number of iterations for the child progress bar. + prefix (`str`, *optional*): A prefix to write on the left of the progress bar. + width (`int`, *optional*, defaults to 300): The width (in pixels) of the progress bar. + """ + self.child_bar = NotebookProgressBar(total, prefix=prefix, parent=self, width=width) + return self.child_bar + + def remove_child(self): + """ + Closes the child progress bar. + """ + self.child_bar = None + self.display() + + +class NotebookProgressCallback(TrainerCallback): + """ + A [`TrainerCallback`] that displays the progress of training or evaluation, optimized for Jupyter Notebooks or + Google colab. + """ + + def __init__(self): + self.training_tracker = None + self.prediction_bar = None + self._force_next_update = False + + def on_train_begin(self, args, state, control, **kwargs): + self.first_column = "Epoch" if args.eval_strategy == IntervalStrategy.EPOCH else "Step" + self.training_loss = 0 + self.last_log = 0 + column_names = [self.first_column] + ["Training Loss"] + if args.eval_strategy != IntervalStrategy.NO: + column_names.append("Validation Loss") + self.training_tracker = NotebookTrainingTracker(state.max_steps, column_names) + + def on_step_end(self, args, state, control, **kwargs): + epoch = int(state.epoch) if int(state.epoch) == state.epoch else f"{state.epoch:.2f}" + tt = _require(self.training_tracker, "on_train_begin must be called before on_step_end") + tt.update( + state.global_step + 1, + comment=f"Epoch {epoch}/{state.num_train_epochs}", + force_update=self._force_next_update, + ) + self._force_next_update = False + + def on_prediction_step(self, args, state, control, eval_dataloader=None, **kwargs): + if not has_length(eval_dataloader): + return + if self.prediction_bar is None: + if self.training_tracker is not None: + self.prediction_bar = self.training_tracker.add_child(len(eval_dataloader)) + else: + self.prediction_bar = NotebookProgressBar(len(eval_dataloader)) + self.prediction_bar.update(1) + else: + self.prediction_bar.update(self.prediction_bar.value + 1) + + def on_predict(self, args, state, control, **kwargs): + if self.prediction_bar is not None: + self.prediction_bar.close() + self.prediction_bar = None + + def on_log(self, args, state, control, logs=None, **kwargs): + # Only for when there is no evaluation + if args.eval_strategy == IntervalStrategy.NO and "loss" in logs: + tt = _require(self.training_tracker, "on_train_begin must be called before on_log") + values = {"Training Loss": logs["loss"]} + # First column is necessarily Step sine we're not in epoch eval strategy + values["Step"] = state.global_step + tt.write_line(values) + + def on_evaluate(self, args, state, control, metrics=None, **kwargs): + # Recompute first_column here since on_evaluate can be called before on_train_begin, + # where it is normally initialized. + self.first_column = "Epoch" if args.eval_strategy == IntervalStrategy.EPOCH else "Step" + + values = {"Training Loss": "No log", "Validation Loss": "No log"} + for log in reversed(state.log_history): + if "loss" in log: + values["Training Loss"] = log["loss"] + break + + if self.first_column == "Epoch": + values["Epoch"] = int(state.epoch) + else: + values["Step"] = state.global_step + if metrics is None: + metrics = {} + metric_key_prefix = "eval" + for k in metrics: + if k.endswith("_loss"): + metric_key_prefix = re.sub(r"\_loss$", "", k) + _ = metrics.pop("total_flos", None) + _ = metrics.pop("epoch", None) + _ = metrics.pop(f"{metric_key_prefix}_runtime", None) + _ = metrics.pop(f"{metric_key_prefix}_samples_per_second", None) + _ = metrics.pop(f"{metric_key_prefix}_steps_per_second", None) + _ = metrics.pop(f"{metric_key_prefix}_model_preparation_time", None) + + for k, v in metrics.items(): + splits = k.split("_") + name = " ".join([part.capitalize() for part in splits[1:]]) + if name == "Loss": + # Single dataset + name = "Validation Loss" + values[name] = v + + if self.training_tracker is not None: + tt = self.training_tracker + tt.write_line(values) + tt.remove_child() + # Evaluation takes a long time so we should force the next update. + self._force_next_update = True + else: + # No training tracker, but still show the metrics + disp.display(disp.HTML(text_to_html_table([list(values.keys()), list(values.values())]))) + + self.prediction_bar = None + + def on_train_end(self, args, state, control, **kwargs): + tt = _require(self.training_tracker, "on_train_begin must be called before on_train_end") + tt.update( + state.global_step, + comment=f"Epoch {int(state.epoch)}/{state.num_train_epochs}", + force_update=True, + ) + self.training_tracker = None diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/output_capturing.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/output_capturing.py new file mode 100644 index 0000000000000000000000000000000000000000..5af880eaa1d2f37933edf80ecce0934e4d383e6c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/output_capturing.py @@ -0,0 +1,285 @@ +# Copyright 2026 The HuggingFace Team. All rights reserved. +# +# 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. +""" +Contains the logic for automatic additional output capture with our forward decorators. +This mostly describe the hooks used and the logic to make capture thread/context safe. +""" + +from __future__ import annotations + +import threading +from contextvars import ContextVar +from dataclasses import dataclass +from functools import wraps +from typing import TYPE_CHECKING + +from .import_utils import is_torchdynamo_compiling, requires + + +if TYPE_CHECKING: + from torch import nn + + from ..modeling_utils import PreTrainedModel + + +_CAN_RECORD_REGISTRY = {} + + +@dataclass +@requires(backends=("torch",)) +class OutputRecorder: + """ + Configuration for recording outputs from a model via hooks. + + Attributes: + target_class (Type): The class (e.g., nn.Module) to which the hook will be attached. + index (Optional[int]): If the output is a tuple/list, optionally record only at a specific index. + layer_name (Optional[str]): Name of the submodule to target (if needed), e.g., "transformer.layer.3.attn". + class_name (Optional[str]): Name of the class to which the hook will be attached. Could be the suffix of class name in some cases. + """ + + target_class: type[nn.Module] + index: int = 0 + layer_name: str | None = None + class_name: str | None = None + + +class CompileableContextVar: + """ + Convenience wrapper around a ContextVar for usage with `torch.compile`. + This behaves exactly as a `ContextVar`, except when compilation is triggered in which case it behaves as a simple + global variable. This is useful as `torch.compile` cannot trace the `get` method of `ContextVar`. This however means + that the access to the underlying variable is not thread-safe when compilation is triggered. + """ + + def __init__(self, name): + self.context_var = ContextVar(name, default=None) + self.global_var = None + self.compiling = False + + def get(self): + # Set was called before and compilation was already detected + if self.compiling: + return self.global_var + else: + return self.context_var.get() + + def set(self, value): + if is_torchdynamo_compiling(): + self.global_var = value + self.compiling = True + return None + else: + return self.context_var.set(value) + + def reset(self, token): + if self.compiling or token is None: + self.global_var = None + self.compiling = False + else: + self.context_var.reset(token) + + +# Thread/context-safe global variable +_active_collector = CompileableContextVar("output_collector") + + +def install_output_capturing_hook(module: nn.Module, key: str, index: int) -> None: + """Install the forward hook needed to capture the output described by `key` and `index` in `module`.""" + + def output_capturing_hook(module, args, output): + # Get the current thread-local collector + collected_outputs = _active_collector.get() + # If it's None or not a key we want to capture, simply return, the hook is inactive + if collected_outputs is None or key not in collected_outputs.keys(): + return + + if key == "hidden_states" and len(collected_outputs[key]) == 0: + collected_outputs[key].append(args[0]) + if not isinstance(output, tuple): + collected_outputs[key].append(output) + elif output[index] is not None: + collected_outputs[key].append(output[index]) + + module.register_forward_hook(output_capturing_hook) + + +def recursively_install_hooks( + parent_module: nn.Module, module_name: str, capture_tasks: list[tuple[str, OutputRecorder]] +) -> None: + """ + Recursively install all output capturing hooks on all submodules of `parent_module`. + Note that we need to use this recursive approach instead of simply iterating over all modules, because we want + to respect the `capture_tasks` of all individual submodels (`PreTrainedModel` instances) in the graph. That is, once + we reach a submodel in the graph, its children should use this submodel's `capture_tasks`, but other parts of the graph + should not. + """ + from ..modeling_utils import PreTrainedModel + + # First dispatch to children if needed + for name, module in parent_module.named_children(): + # Keep dispatching the same `capture_tasks` + if not isinstance(module, PreTrainedModel): + recursively_install_hooks(module, f"{module_name}.{name}", capture_tasks) + # New Submodel: we need to dispatch its own `capture_tasks` + else: + install_all_output_capturing_hooks(module, prefix=f"{module_name}.{name}") + + # Potentially install the hook on current `parent_module` + for key, specs in capture_tasks: + # The second check is for multimodals where only backbone layer suffix is available + if (specs.target_class is not None and isinstance(parent_module, specs.target_class)) or ( + specs.class_name is not None and module_name.endswith(specs.class_name) + ): + if specs.layer_name is not None and specs.layer_name not in module_name: + continue + install_output_capturing_hook(parent_module, key, specs.index) + + +def install_all_output_capturing_hooks(model: PreTrainedModel, prefix: str | None = None) -> None: + """ + Install the output recording hooks on all the modules in `model`. This will take care of correctly dispatching + the `_can_record_outputs` property of each individual submodels in case of composite models. + """ + # _can_record_outputs is None by default + capture_flags = _CAN_RECORD_REGISTRY.get(str(model.__class__)) or {} # there is a weak ref for executorch + + capture_tasks = [] + for key, layer_specs in capture_flags.items(): + if not isinstance(layer_specs, list): + layer_specs = [layer_specs] + for specs in layer_specs: + if not isinstance(specs, OutputRecorder): + index = 0 if "hidden_states" in key else 1 + class_name = None if not isinstance(specs, str) else specs + target_class = specs if not isinstance(specs, str) else None + specs = OutputRecorder(target_class=target_class, index=index, class_name=class_name) + capture_tasks.append((key, specs)) + + # Install the hooks + prefix = prefix if prefix is not None else "" + recursively_install_hooks(model, prefix, capture_tasks) + # Mark the model as already hooked + setattr(model, "_output_capturing_hooks_installed", True) + + +# We need this to make sure we don't have race conditions when installing hooks, resulting in them being installed +# several times +_hook_installation_lock = threading.Lock() + + +def maybe_install_capturing_hooks(model: PreTrainedModel) -> None: + """ + Check if the model already has output capturing hooks installed, and install them if it is not already the + case. + Note that this is thread-safe, in case 2 (or more) threads want to install them concurrently. + """ + # First check + if getattr(model, "_output_capturing_hooks_installed", False): + return + + with _hook_installation_lock: + # Second check, in case several threads entered this function concurrently and did not return on the + # previous check + if getattr(model, "_output_capturing_hooks_installed", False): + return + # This will install the hooks and mark the model as hooked + install_all_output_capturing_hooks(model) + + +def capture_outputs(func=None, *, tie_last_hidden_states=True): + """ + Decorator to intercept specific layer outputs through hooks. The hooks are installed only once and lazily, + the first time output capture is requested with the `output_xxx` kwargs/config. + The implementation is fully context/thread safe, except when using `torch.compile`, as dynamo is unable to trace + through `ContextVar` methods. + + Args: + tie_last_hidden_states (`bool`, *optional*, defaults to `True`): + Whether to overwrite `out.hidden_states[-1]` with the `out.last_hidden_state`. + This is true for all language models and should be toggled off only if + `out.hidden_states[-1]` has to be the hidden state before last layer norm, which + is needed for some vision models (e.g. CLIP, SigLIP) + """ + + def wrapped_fn(func): + @wraps(func) + def wrapper(self, *args, **kwargs): + # Pop it so that internal modules always return a dict even if False is requested + return_dict = kwargs.pop("return_dict", getattr(self.config, "return_dict", True)) + + # _can_record_outputs is None by default + capturable_flags = _CAN_RECORD_REGISTRY.get(str(self.__class__)) or {} + recordable_keys = { + f"output_{k}": kwargs.get(f"output_{k}", getattr(self.config, f"output_{k}", False)) + for k in capturable_flags + } + # For BC as cross-attentions used to be captured with `output_attentions` + if "cross_attentions" in capturable_flags: + recordable_keys["output_cross_attentions"] = kwargs.get( + "output_attentions", getattr(self.config, "output_attentions", False) + ) + # The sam model variants need this annoying exception as well... + if "mask_decoder_attentions" in capturable_flags: + recordable_keys["output_mask_decoder_attentions"] = kwargs.get( + "output_attentions", getattr(self.config, "output_attentions", False) + ) + + collected_outputs = {k.replace("output_", ""): [] for k, v in recordable_keys.items() if v} + # Make sure hooks are installed if we need to collect outputs + if len(collected_outputs) > 0: + maybe_install_capturing_hooks(self) + # Let's activate the output collector hooks if needed! + output_token = _active_collector.set(collected_outputs) + + # Run the forward + try: + outputs = func(self, *args, **kwargs) + # Reset the states + finally: + _active_collector.reset(output_token) + + # Inject collected outputs into model output (return everything as tuples for BC) + for key in collected_outputs: + if key == "hidden_states": + if not tie_last_hidden_states: + pass + elif hasattr(outputs, "vision_hidden_states"): + collected_outputs[key] = collected_outputs[key][:-1] + collected_outputs[key].append(outputs.vision_hidden_states) + elif hasattr(outputs, "last_hidden_state"): + collected_outputs[key] = collected_outputs[key][:-1] + collected_outputs[key].append(outputs.last_hidden_state) + + outputs[key] = tuple(collected_outputs[key]) + elif key == "attentions": + # In this case, the second item are cross attentions + if isinstance(capturable_flags[key], list) and len(capturable_flags[key]) == 2: + outputs[key] = tuple(collected_outputs[key][0::2]) + outputs["cross_" + key] = tuple(collected_outputs[key][1::2]) + else: + outputs[key] = tuple(collected_outputs[key]) + else: + outputs[key] = tuple(collected_outputs[key]) + + if return_dict is False: + outputs = outputs.to_tuple() + + return outputs + + return wrapper + + if func is not None: + return wrapped_fn(func) + return wrapped_fn diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/peft_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/peft_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a1ec093b4e672c362e9fcaecd4363d29339d4b6e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/peft_utils.py @@ -0,0 +1,117 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# 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. +import importlib +import importlib.metadata +import os + +from packaging import version + +from .hub import cached_file +from .import_utils import is_peft_available + + +ADAPTER_CONFIG_NAME = "adapter_config.json" +ADAPTER_WEIGHTS_NAME = "adapter_model.bin" +ADAPTER_SAFE_WEIGHTS_NAME = "adapter_model.safetensors" + + +def find_adapter_config_file( + model_id: str, + cache_dir: str | os.PathLike | None = None, + force_download: bool = False, + proxies: dict[str, str] | None = None, + token: bool | str | None = None, + revision: str | None = None, + local_files_only: bool = False, + subfolder: str = "", + _commit_hash: str | None = None, +) -> str | None: + r""" + Simply checks if the model stored on the Hub or locally is an adapter model or not, return the path of the adapter + config file if it is, None otherwise. + + Args: + model_id (`str`): + The identifier of the model to look for, can be either a local path or an id to the repository on the Hub. + cache_dir (`str` or `os.PathLike`, *optional*): + Path to a directory in which a downloaded pretrained model configuration should be cached if the standard + cache should not be used. + force_download (`bool`, *optional*, defaults to `False`): + Whether or not to force to (re-)download the configuration files and override the cached versions if they + exist. + proxies (`dict[str, str]`, *optional*): + A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', + 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request. + token (`str` or *bool*, *optional*): + The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated + when running `hf auth login` (stored in `~/.huggingface`). + revision (`str`, *optional*, defaults to `"main"`): + The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a + git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any + identifier allowed by git. + + + + To test a pull request you made on the Hub, you can pass `revision="refs/pr/". + + + + local_files_only (`bool`, *optional*, defaults to `False`): + If `True`, will only try to load the tokenizer configuration from local files. + subfolder (`str`, *optional*, defaults to `""`): + In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can + specify the folder name here. + """ + adapter_cached_filename = None + if model_id is None: + return None + elif os.path.isdir(model_id): + list_remote_files = os.listdir(model_id) + if ADAPTER_CONFIG_NAME in list_remote_files: + adapter_cached_filename = os.path.join(model_id, ADAPTER_CONFIG_NAME) + else: + adapter_cached_filename = cached_file( + model_id, + ADAPTER_CONFIG_NAME, + cache_dir=cache_dir, + force_download=force_download, + proxies=proxies, + token=token, + revision=revision, + local_files_only=local_files_only, + subfolder=subfolder, + _commit_hash=_commit_hash, + _raise_exceptions_for_gated_repo=False, + _raise_exceptions_for_missing_entries=False, + _raise_exceptions_for_connection_errors=False, + ) + + return adapter_cached_filename + + +def check_peft_version(min_version: str) -> None: + r""" + Checks if the version of PEFT is compatible. + + Args: + version (`str`): + The version of PEFT to check against. + """ + if not is_peft_available(): + raise ValueError("PEFT is not installed. Please install it with `pip install peft`") + + is_peft_version_compatible = version.parse(importlib.metadata.version("peft")) >= version.parse(min_version) + + if not is_peft_version_compatible: + raise ValueError(f"The version of PEFT you are using is not compatible, please use a version >= {min_version}") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/pytest_helpers.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/pytest_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..5f22e01ba5081318e38f591d15f29ad833a7aa2d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/pytest_helpers.py @@ -0,0 +1,111 @@ +import argparse +import json +import re +from collections import Counter +from pathlib import Path + + +def _base_test_name(nodeid: str) -> str: + # Strip parameters like [param=..] from the last component + name = nodeid.split("::")[-1] + return re.sub(r"\[.*\]$", "", name) + + +def _class_name(nodeid: str) -> str | None: + parts = nodeid.split("::") + # nodeid can be: file::Class::test or file::test + if len(parts) >= 3: + return parts[-2] + return None + + +def _file_path(nodeid: str) -> str: + return nodeid.split("::")[0] + + +def _modeling_key(file_path: str) -> str | None: + # Extract "xxx" from test_modeling_xxx.py + m = re.search(r"test_modeling_([A-Za-z0-9_]+)\.py$", file_path) + if m: + return m.group(1) + return None + + +def summarize(report_path: str): + p = Path(report_path) + if not p.exists(): + raise FileNotFoundError(f"Report file not found: {p.resolve()}") + + data = json.loads(p.read_text()) + tests = data.get("tests", []) + + # Overall counts + outcomes = Counter(t.get("outcome", "unknown") for t in tests) + + # Filter failures (pytest-json-report uses "failed" and may have "error") + failed = [t for t in tests if t.get("outcome") in ("failed", "error")] + + # 1) Failures per test file + failures_per_file = Counter(_file_path(t.get("nodeid", "")) for t in failed) + + # 2) Failures per class (if any; otherwise "NO_CLASS") + failures_per_class = Counter((_class_name(t.get("nodeid", "")) or "NO_CLASS") for t in failed) + + # 3) Failures per base test name (function), aggregating parametrized cases + failures_per_testname = Counter(_base_test_name(t.get("nodeid", "")) for t in failed) + + # 4) Failures per test_modeling_xxx (derived from filename) + failures_per_modeling_key = Counter() + for t in failed: + key = _modeling_key(_file_path(t.get("nodeid", ""))) + if key: + failures_per_modeling_key[key] += 1 + + return { + "outcomes": outcomes, + "failures_per_file": failures_per_file, + "failures_per_class": failures_per_class, + "failures_per_testname": failures_per_testname, + "failures_per_modeling_key": failures_per_modeling_key, + } + + +def main(): + parser = argparse.ArgumentParser(description="Summarize pytest JSON report failures") + parser.add_argument( + "--report", default="report.json", help="Path to pytest JSON report file (default: report.json)" + ) + args = parser.parse_args() + + try: + summary = summarize(args.report) + except FileNotFoundError as e: + print(str(e)) + return + + outcomes = summary["outcomes"] + print("=== Overall ===") + total = sum(outcomes.values()) + print(f"Total tests: {total}") + for k in sorted(outcomes): + print(f"{k:>10}: {outcomes[k]}") + + def _print_counter(title, counter: Counter, label=""): + print(f"\n=== {title} ===") + if not counter: + print("None") + return + for key, cnt in sorted(counter.items(), key=lambda x: (x[1], x[0])): + if label: + print(f"{cnt:4d} {label}{key}") + else: + print(f"{cnt:4d} {key}") + + _print_counter("Failures per test class", summary["failures_per_class"], label="class ") + _print_counter("Failures per test_modeling_xxx", summary["failures_per_modeling_key"], label="model ") + _print_counter("Failures per test file", summary["failures_per_file"]) + _print_counter("Failures per test name (base)", summary["failures_per_testname"]) + + +if __name__ == "__main__": + main() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/quantization_config.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/quantization_config.py new file mode 100644 index 0000000000000000000000000000000000000000..a6c1f5334516843ba6bb2eb72dff5a39b243e06b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/quantization_config.py @@ -0,0 +1,2002 @@ +#!/usr/bin/env python + +# Copyright 2023 The HuggingFace Inc. team. All rights reserved. +# Modifications Copyright (C) 2025, Advanced Micro Devices, Inc. All rights reserved. +# +# 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. +import copy +import importlib.metadata +import json +import os +from dataclasses import dataclass +from enum import Enum +from typing import Any, Optional, Union + +from packaging import version + +from ..utils import ( + is_compressed_tensors_available, + is_hqq_available, + is_quark_available, + is_torch_available, + is_torchao_available, + logging, +) + + +if is_torch_available(): + import torch + +logger = logging.get_logger(__name__) + + +class QuantizationMethod(str, Enum): + BITS_AND_BYTES = "bitsandbytes" + GPTQ = "gptq" + AWQ = "awq" + AQLM = "aqlm" + VPTQ = "vptq" + QUANTO = "quanto" + EETQ = "eetq" + HIGGS = "higgs" + HQQ = "hqq" + COMPRESSED_TENSORS = "compressed-tensors" + FBGEMM_FP8 = "fbgemm_fp8" + TORCHAO = "torchao" + BITNET = "bitnet" + SPQR = "spqr" + FP8 = "fp8" + QUARK = "quark" + FPQUANT = "fp_quant" + AUTOROUND = "auto-round" + MXFP4 = "mxfp4" + METAL = "metal" + FOUR_OVER_SIX = "fouroversix" + SINQ = "sinq" + + +class AwqFormat(str, Enum): + GEMM = "gemm" + GEMV = "gemv" + GEMV_FAST = "gemv_fast" + LLM_AWQ = "llm-awq" + + +class AwqBackend(str, Enum): + LEGACY_AWQ = "autoawq" + AUTO = "auto" + AUTO_TRAINABLE = "auto_trainable" + MACHETE = "machete" + MARLIN = "marlin" + EXLLAMA_V2 = "exllama_v2" + EXLLAMA_V1 = "exllama_v1" + GEMM = "gemm" + GEMM_TRITON = "gemm_triton" + GEMV = "gemv" + GEMV_FAST = "gemv_fast" + TORCH_AWQ = "torch_awq" + TORCH_FUSED_AWQ = "torch_fused_awq" + + +@dataclass +class QuantizationConfigMixin: + """ + Mixin class for quantization config + """ + + quant_method: QuantizationMethod + + @classmethod + def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs): + """ + Instantiates a [`QuantizationConfigMixin`] from a Python dictionary of parameters. + + Args: + config_dict (`dict[str, Any]`): + Dictionary that will be used to instantiate the configuration object. + return_unused_kwargs (`bool`,*optional*, defaults to `False`): + Whether or not to return a list of unused keyword arguments. Used for `from_pretrained` method in + `PreTrainedModel`. + kwargs (`dict[str, Any]`): + Additional parameters from which to initialize the configuration object. + + Returns: + [`QuantizationConfigMixin`]: The configuration object instantiated from those parameters. + """ + config = cls(**config_dict) + + to_remove = [] + for key, value in kwargs.items(): + if hasattr(config, key): + setattr(config, key, value) + to_remove.append(key) + for key in to_remove: + kwargs.pop(key, None) + + if return_unused_kwargs: + return config, kwargs + else: + return config + + def to_json_file(self, json_file_path: str | os.PathLike): + """ + Save this instance to a JSON file. + + Args: + json_file_path (`str` or `os.PathLike`): + Path to the JSON file in which this configuration instance's parameters will be saved. + use_diff (`bool`, *optional*, defaults to `True`): + If set to `True`, only the difference between the config instance and the default + `QuantizationConfig()` is serialized to JSON file. + """ + with open(json_file_path, "w", encoding="utf-8") as writer: + config_dict = self.to_dict() + json_string = json.dumps(config_dict, indent=2, sort_keys=True) + "\n" + + writer.write(json_string) + + def to_dict(self) -> dict[str, Any]: + """ + Serializes this instance to a Python dictionary. Returns: + `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance. + """ + return copy.deepcopy(self.__dict__) + + def __iter__(self): + """allows `dict(obj)` for situations where obj may be a dict or QuantizationConfigMixin""" + yield from copy.deepcopy(self.__dict__).items() + + def __repr__(self): + return f"{self.__class__.__name__} {self.to_json_string()}" + + def to_diff_dict(self) -> dict[str, Any]: + """ + Default behavior: no diffing implemented for this config. + """ + return self.to_dict() + + def to_json_string(self, use_diff: bool = True) -> str: + """ + Serializes this instance to a JSON string. + + Args: + use_diff (`bool`, *optional*, defaults to `True`): + If set to `True`, only the difference between the config instance and the default `PreTrainedConfig()` + is serialized to JSON string. + + Returns: + `str`: String containing all the attributes that make up this configuration instance in JSON format. + """ + config_dict = self.to_diff_dict() if use_diff else self.to_dict() + return json.dumps(config_dict, indent=2, sort_keys=True) + "\n" + + def update(self, **kwargs): + """ + Updates attributes of this class instance with attributes from `kwargs` if they match existing attributes, + returning all the unused kwargs. + + Args: + kwargs (`dict[str, Any]`): + Dictionary of attributes to tentatively update this class. + + Returns: + `dict[str, Any]`: Dictionary containing all the key-value pairs that were not used to update the instance. + """ + to_remove = [] + for key, value in kwargs.items(): + if hasattr(self, key): + setattr(self, key, value) + to_remove.append(key) + + # Remove all the attributes that were updated, without modifying the input dict + unused_kwargs = {key: value for key, value in kwargs.items() if key not in to_remove} + return unused_kwargs + + +@dataclass +class AutoRoundConfig(QuantizationConfigMixin): + """This is a wrapper class about all possible attributes and features that you can play with a model that has been + loaded AutoRound quantization. + + Args: + bits (`int`, *optional*, defaults to 4): + The number of bits to quantize to, supported numbers are (2, 3, 4, 8). + group_size (`int`, *optional*, defaults to 128): Group-size value + sym (`bool`, *optional*, defaults to `True`): Symmetric quantization or not + backend (`str`, *optional*, defaults to `"auto"`): The kernel to use, e.g., ipex,marlin, exllamav2, triton, etc. Ref. https://github.com/intel/auto-round?tab=readme-ov-file#specify-backend + """ + + def __init__( + self, + bits: int = 4, + group_size: int = 128, + sym: bool = True, + backend: str = "auto", + **kwargs, + ): + self.bits = bits + self.group_size = group_size + self.sym = sym + self.backend = backend + self.packing_format = "auto_round:gptq" + if kwargs is not None: + for key, value in kwargs.items(): + setattr(self, key, value) + self.quant_method = QuantizationMethod.AUTOROUND + self.post_init() + + def post_init(self): + r"""Safety checker that arguments are correct.""" + if self.bits not in [2, 3, 4, 8]: + raise ValueError(f"Only support quantization to [2,3,4,8] bits but found {self.bits}") + if self.group_size != -1 and self.group_size <= 0: + raise ValueError("group_size must be greater than 0 or equal to -1") + + def get_loading_attributes(self): + loading_attributes_dict = {"backend": self.backend} + return loading_attributes_dict + + def to_dict(self): + config_dict = super().to_dict() + return config_dict + + @classmethod + def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs): + quant_method = config_dict["quant_method"] + if "auto-round" not in quant_method and "gptq" not in quant_method and "awq" not in quant_method: + raise NotImplementedError( + "Failed to convert to auto_round format. Only `gptqv1`, `awq`, and `auto-round` formats are supported." + ) + + if "gptq" in quant_method and "meta" in config_dict: + raise NotImplementedError("Failed to convert gptq format to auto_round format. Only supports `gptqv1`") + + if "awq" in quant_method and config_dict.get("version", "gemm") != "gemm": + raise NotImplementedError( + "Failed to convert awq format to auto_round format. Only supports awq format with gemm version" + ) + + if "auto-round" not in quant_method: + config_dict["packing_format"] = f"auto_round:{quant_method}" + + return super().from_dict(config_dict, return_unused_kwargs=return_unused_kwargs, **kwargs) + + +@dataclass +class HqqConfig(QuantizationConfigMixin): + """ + This is wrapper around hqq's BaseQuantizeConfig. + + Args: + nbits (`int`, *optional*, defaults to 4): + Number of bits. Supported values are (8, 4, 3, 2, 1). + group_size (`int`, *optional*, defaults to 64): + Group-size value. Supported values are any value that is divisible by weight.shape[axis]). + view_as_float (`bool`, *optional*, defaults to `False`): + View the quantized weight as float (used in distributed training) if set to `True`. + axis (`Optional[int]`, *optional*): + Axis along which grouping is performed. Supported values are 0 or 1. + dynamic_config (dict, *optional*): + Parameters for dynamic configuration. The key is the name tag of the layer and the value is a quantization config. + If set, each layer specified by its id will use its dedicated quantization configuration. + skip_modules (`list[str]`, *optional*, defaults to `['lm_head']`): + List of `nn.Linear` layers to skip. + kwargs (`dict[str, Any]`, *optional*): + Additional parameters from which to initialize the configuration object. + """ + + def __init__( + self, + nbits: int = 4, + group_size: int = 64, + view_as_float: bool = False, + axis: int | None = None, + dynamic_config: dict | None = None, + skip_modules: list[str] = ["lm_head"], + **kwargs, + ): + if is_hqq_available(): + from hqq.core.quantize import BaseQuantizeConfig as HQQBaseQuantizeConfig + else: + raise ImportError( + "A valid HQQ version (>=0.2.1) is not available. Please follow the instructions to install it: `https://github.com/mobiusml/hqq/`." + ) + + if axis is None: + axis = 1 + logger.info("Setting axis=1 as faster backends such as TorchAO or BitBlas are only compatible with it.") + + if axis not in [0, 1]: + raise ValueError("Invalid axis value. Only 0 and 1 are allowed.") + + if dynamic_config is not None: + self.quant_config = {} + for key in dynamic_config: + self.quant_config[key] = HQQBaseQuantizeConfig(**dynamic_config[key]) + else: + self.quant_config = HQQBaseQuantizeConfig( + nbits=nbits, group_size=group_size, view_as_float=view_as_float, axis=axis + ) + + self.quant_method = QuantizationMethod.HQQ + self.skip_modules = skip_modules + + self.post_init() + + def post_init(self): + r""" + Safety checker that arguments are correct - also replaces some NoneType arguments with their default values. + """ + + @classmethod + def from_dict(cls, config: dict[str, Any]): + """ + Override from_dict, used in AutoQuantizationConfig.from_dict in quantizers/auto.py + """ + instance = cls() + instance.quant_config = config["quant_config"] + instance.skip_modules = config["skip_modules"] + return instance + + def to_dict(self) -> dict[str, Any]: + """ + Serializes this instance to a Python dictionary. Returns: + `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance. + """ + return { + "quant_config": self.quant_config, + "quant_method": self.quant_method, + "skip_modules": self.skip_modules, + } + + def __repr__(self): + config_dict = self.to_dict() + return f"{self.__class__.__name__} {json.dumps(config_dict, indent=2, sort_keys=True)}\n" + + def to_diff_dict(self) -> dict[str, Any]: + """ + Removes all attributes from config which correspond to the default config attributes for better readability and + serializes to a Python dictionary. + Returns: + `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance, + """ + config_dict = self.to_dict() + + # get the default config dict + default_config_dict = HqqConfig().to_dict() + + serializable_config_dict = {} + + # only serialize values that differ from the default config + for key, value in config_dict.items(): + if value != default_config_dict[key]: + serializable_config_dict[key] = value + + return serializable_config_dict + + +@dataclass +class BitsAndBytesConfig(QuantizationConfigMixin): + """ + This is a wrapper class about all possible attributes and features that you can play with a model that has been + loaded using `bitsandbytes`. + + Currently only supports `LLM.int8()`, `FP4`, and `NF4` quantization. If more methods are added to `bitsandbytes`, + then more arguments will be added to this class. + + Args: + load_in_8bit (`bool`, *optional*, defaults to `False`): + This flag is used to enable 8-bit quantization with LLM.int8(). + load_in_4bit (`bool`, *optional*, defaults to `False`): + This flag is used to enable 4-bit quantization by replacing the Linear layers with FP4/NF4 layers from + `bitsandbytes`. + llm_int8_threshold (`float`, *optional*, defaults to 6.0): + This corresponds to the outlier threshold for outlier detection as described in `LLM.int8() : 8-bit Matrix + Multiplication for Transformers at Scale` paper: https://huggingface.co/papers/2208.07339 Any hidden states value + that is above this threshold will be considered an outlier and the operation on those values will be done + in fp16. Values are usually normally distributed, that is, most values are in the range [-3.5, 3.5], but + there are some exceptional systematic outliers that are very differently distributed for large models. + These outliers are often in the interval [-60, -6] or [6, 60]. Int8 quantization works well for values of + magnitude ~5, but beyond that, there is a significant performance penalty. A good default threshold is 6, + but a lower threshold might be needed for more unstable models (small models, fine-tuning). + llm_int8_skip_modules (`list[str]`, *optional*): + An explicit list of the modules that we do not want to convert in 8-bit. This is useful for models such as + Jukebox that has several heads in different places and not necessarily at the last position. For example + for `CausalLM` models, the last `lm_head` is kept in its original `dtype`. + llm_int8_enable_fp32_cpu_offload (`bool`, *optional*, defaults to `False`): + This flag is used for advanced use cases and users that are aware of this feature. If you want to split + your model in different parts and run some parts in int8 on GPU and some parts in fp32 on CPU, you can use + this flag. This is useful for offloading large models such as `google/flan-t5-xxl`. Note that the int8 + operations will not be run on CPU. + llm_int8_has_fp16_weight (`bool`, *optional*, defaults to `False`): + This flag runs LLM.int8() with 16-bit main weights. This is useful for fine-tuning as the weights do not + have to be converted back and forth for the backward pass. + bnb_4bit_compute_dtype (`torch.dtype` or str, *optional*, defaults to `torch.float32`): + This sets the computational type which might be different than the input type. For example, inputs might be + fp32, but computation can be set to bf16 for speedups. + bnb_4bit_quant_type (`str`, *optional*, defaults to `"fp4"`): + This sets the quantization data type in the bnb.nn.Linear4Bit layers. Options are FP4 and NF4 data types + which are specified by `fp4` or `nf4`. + bnb_4bit_use_double_quant (`bool`, *optional*, defaults to `False`): + This flag is used for nested quantization where the quantization constants from the first quantization are + quantized again. + bnb_4bit_quant_storage (`torch.dtype` or str, *optional*, defaults to `torch.uint8`): + This sets the storage type to pack the quantized 4-bit params. + kwargs (`dict[str, Any]`, *optional*): + Additional parameters from which to initialize the configuration object. + """ + + def __init__( + self, + load_in_8bit=False, + load_in_4bit=False, + llm_int8_threshold=6.0, + llm_int8_skip_modules=None, + llm_int8_enable_fp32_cpu_offload=False, + llm_int8_has_fp16_weight=False, + bnb_4bit_compute_dtype=None, + bnb_4bit_quant_type="fp4", + bnb_4bit_use_double_quant=False, + bnb_4bit_quant_storage=None, + **kwargs, + ): + self.quant_method = QuantizationMethod.BITS_AND_BYTES + + if load_in_4bit and load_in_8bit: + raise ValueError("load_in_4bit and load_in_8bit are both True, but only one can be used at the same time") + + self._load_in_8bit = load_in_8bit + self._load_in_4bit = load_in_4bit + self.llm_int8_threshold = llm_int8_threshold + self.llm_int8_skip_modules = llm_int8_skip_modules + self.llm_int8_enable_fp32_cpu_offload = llm_int8_enable_fp32_cpu_offload + self.llm_int8_has_fp16_weight = llm_int8_has_fp16_weight + self.bnb_4bit_quant_type = bnb_4bit_quant_type + self.bnb_4bit_use_double_quant = bnb_4bit_use_double_quant + + if bnb_4bit_compute_dtype is None: + self.bnb_4bit_compute_dtype = torch.float32 + elif isinstance(bnb_4bit_compute_dtype, str): + self.bnb_4bit_compute_dtype = getattr(torch, bnb_4bit_compute_dtype) + elif isinstance(bnb_4bit_compute_dtype, torch.dtype): + self.bnb_4bit_compute_dtype = bnb_4bit_compute_dtype + else: + raise ValueError("bnb_4bit_compute_dtype must be a string or a torch.dtype") + + if bnb_4bit_quant_storage is None: + self.bnb_4bit_quant_storage = torch.uint8 + elif isinstance(bnb_4bit_quant_storage, str): + if bnb_4bit_quant_storage not in ["float16", "float32", "int8", "uint8", "float64", "bfloat16"]: + raise ValueError( + "`bnb_4bit_quant_storage` must be a valid string (one of 'float16', 'float32', 'int8', 'uint8', 'float64', 'bfloat16') " + ) + self.bnb_4bit_quant_storage = getattr(torch, bnb_4bit_quant_storage) + elif isinstance(bnb_4bit_quant_storage, torch.dtype): + self.bnb_4bit_quant_storage = bnb_4bit_quant_storage + else: + raise ValueError("bnb_4bit_quant_storage must be a string or a torch.dtype") + + if kwargs: + logger.info(f"Unused kwargs: {list(kwargs.keys())}. These kwargs are not used in {self.__class__}.") + + self.post_init() + + @property + def load_in_4bit(self): + return self._load_in_4bit + + @load_in_4bit.setter + def load_in_4bit(self, value: bool): + if not isinstance(value, bool): + raise TypeError("load_in_4bit must be a boolean") + + if self.load_in_8bit and value: + raise ValueError("load_in_4bit and load_in_8bit are both True, but only one can be used at the same time") + self._load_in_4bit = value + + @property + def load_in_8bit(self): + return self._load_in_8bit + + @load_in_8bit.setter + def load_in_8bit(self, value: bool): + if not isinstance(value, bool): + raise TypeError("load_in_8bit must be a boolean") + + if self.load_in_4bit and value: + raise ValueError("load_in_4bit and load_in_8bit are both True, but only one can be used at the same time") + self._load_in_8bit = value + + def post_init(self): + r""" + Safety checker that arguments are correct - also replaces some NoneType arguments with their default values. + """ + if not isinstance(self.load_in_4bit, bool): + raise TypeError("load_in_4bit must be a boolean") + + if not isinstance(self.load_in_8bit, bool): + raise TypeError("load_in_8bit must be a boolean") + + if not isinstance(self.llm_int8_threshold, float): + raise TypeError("llm_int8_threshold must be a float") + + if self.llm_int8_skip_modules is not None and not isinstance(self.llm_int8_skip_modules, list): + raise TypeError("llm_int8_skip_modules must be a list of strings") + if not isinstance(self.llm_int8_enable_fp32_cpu_offload, bool): + raise TypeError("llm_int8_enable_fp32_cpu_offload must be a boolean") + + if not isinstance(self.llm_int8_has_fp16_weight, bool): + raise TypeError("llm_int8_has_fp16_weight must be a boolean") + + if self.bnb_4bit_compute_dtype is not None and not isinstance(self.bnb_4bit_compute_dtype, torch.dtype): + raise TypeError("bnb_4bit_compute_dtype must be torch.dtype") + + if not isinstance(self.bnb_4bit_quant_type, str): + raise TypeError("bnb_4bit_quant_type must be a string") + + if not isinstance(self.bnb_4bit_use_double_quant, bool): + raise TypeError("bnb_4bit_use_double_quant must be a boolean") + + def is_quantizable(self): + r""" + Returns `True` if the model is quantizable, `False` otherwise. + """ + return self.load_in_8bit or self.load_in_4bit + + def quantization_method(self): + r""" + This method returns the quantization method used for the model. If the model is not quantizable, it returns + `None`. + """ + if self.load_in_8bit: + return "llm_int8" + elif self.load_in_4bit and self.bnb_4bit_quant_type == "fp4": + return "fp4" + elif self.load_in_4bit and self.bnb_4bit_quant_type == "nf4": + return "nf4" + else: + return None + + def to_dict(self) -> dict[str, Any]: + """ + Serializes this instance to a Python dictionary. Returns: + `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance. + """ + output = copy.deepcopy(self.__dict__) + output["bnb_4bit_compute_dtype"] = str(output["bnb_4bit_compute_dtype"]).split(".")[1] + output["bnb_4bit_quant_storage"] = str(output["bnb_4bit_quant_storage"]).split(".")[1] + output["load_in_4bit"] = self.load_in_4bit + output["load_in_8bit"] = self.load_in_8bit + + return output + + def __repr__(self): + config_dict = self.to_dict() + return f"{self.__class__.__name__} {json.dumps(config_dict, indent=2, sort_keys=True)}\n" + + def to_diff_dict(self) -> dict[str, Any]: + """ + Removes all attributes from config which correspond to the default config attributes for better readability and + serializes to a Python dictionary. + + Returns: + `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance, + """ + config_dict = self.to_dict() + + # get the default config dict + default_config_dict = BitsAndBytesConfig().to_dict() + + serializable_config_dict = {} + + # only serialize values that differ from the default config + for key, value in config_dict.items(): + if value != default_config_dict[key]: + serializable_config_dict[key] = value + + return serializable_config_dict + + +class ExllamaVersion(int, Enum): + ONE = 1 + TWO = 2 + + +@dataclass +class GPTQConfig(QuantizationConfigMixin): + """ + This is a wrapper class about all possible attributes and features that you can play with a model that has been + loaded using `optimum` api for GPTQ quantization relying on the gptqmodel backend. + + Args: + bits (`int`): + The number of bits to quantize to, supported numbers are (2, 3, 4, 8). + tokenizer (`str` or `PreTrainedTokenizerBase`, *optional*): + The tokenizer used to process the dataset. You can pass either: + - A custom tokenizer object. + - A string, the *model id* of a predefined tokenizer hosted inside a model repo on huggingface.co. + - A path to a *directory* containing vocabulary files required by the tokenizer, for instance saved + using the [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`. + dataset (`Union[list[str]]`, *optional*): + The dataset used for quantization. You can provide your own dataset in a list of string or just use the + original datasets used in GPTQ paper ['wikitext2','c4','c4-new'] + group_size (`int`, *optional*, defaults to 128): + The group size to use for quantization. Recommended value is 128 and -1 uses per-column quantization. + damp_percent (`float`, *optional*, defaults to 0.1): + The percent of the average Hessian diagonal to use for dampening. Recommended value is 0.1. + desc_act (`bool`, *optional*, defaults to `False`): + Whether to quantize columns in order of decreasing activation size. Setting it to False can significantly + speed up inference but the perplexity may become slightly worse. Also known as act-order. + act_group_aware (`bool`, *optional*, defaults to `True`): + Use GAR (group aware activation order) during quantization. Has measurable positive impact on quantization + quality. Only applicable when `desc_act = False`. Will forced to be `False` when `desc_act = True`. + sym (`bool`, *optional*, defaults to `True`): + Whether to use symmetric quantization. + true_sequential (`bool`, *optional*, defaults to `True`): + Whether to perform sequential quantization even within a single Transformer block. Instead of quantizing + the entire block at once, we perform layer-wise quantization. As a result, each layer undergoes + quantization using inputs that have passed through the previously quantized layers. + format (`str`, *optional*, defaults to `"gptq"`): + GPTQ weight format. `gptq` (v1) is supported by gptqmodel. `gptq_v2` is gptqmodel only. + meta (`dict[str, any]`, *optional*): + Properties, such as tooling:version, that do not directly contributes to quantization or quant inference are stored in meta. + i.e. `meta.quantizer`: ["optimum:_version_", "gptqmodel:_version_"] + backend (`str`, *optional*): + Controls which kernel to use. Valid values for gptqmodel are `auto`, `auto_trainable` and more. Ref gptqmodel backends: + https://github.com/ModelCloud/GPTQModel/blob/main/gptqmodel/utils/backend.py + model_seqlen (`int`, *optional*): + The maximum sequence length that the model can take. + block_name_to_quantize (`str`, *optional*): + The transformers block name to quantize. If None, we will infer the block name using common patterns (e.g. model.layers) + module_name_preceding_first_block (`list[str]`, *optional*): + The layers that are preceding the first Transformer block. + batch_size (`int`, *optional*, defaults to 1): + The batch size used when processing the dataset + pad_token_id (`int`, *optional*): + The pad token id. Needed to prepare the dataset when `batch_size` > 1. + max_input_length (`int`, *optional*): + The maximum input length. This is needed to initialize a buffer that depends on the maximum expected input + length. It is specific to the exllama backend with act-order. + cache_block_outputs (`bool`, *optional*, defaults to `True`): + Whether to cache block outputs to reuse as inputs for the succeeding block. + modules_in_block_to_quantize (`list[list[str]]`, *optional*): + List of list of module names to quantize in the specified block. This argument is useful to exclude certain linear modules from being quantized. + The block to quantize can be specified by setting `block_name_to_quantize`. We will quantize each list sequentially. If not set, we will quantize all linear layers. + Example: `modules_in_block_to_quantize =[["self_attn.k_proj", "self_attn.v_proj", "self_attn.q_proj"], ["self_attn.o_proj"]]`. + In this example, we will first quantize the q,k,v layers simultaneously since they are independent. + Then, we will quantize `self_attn.o_proj` layer with the q,k,v layers quantized. This way, we will get + better results since it reflects the real input `self_attn.o_proj` will get when the model is quantized. + """ + + def __init__( + self, + bits: int, + tokenizer: Any = None, + dataset: list[str] | str | None = None, + group_size: int = 128, + damp_percent: float = 0.1, + desc_act: bool = False, + act_group_aware: bool = True, + sym: bool = True, + true_sequential: bool = True, + format: str = "gptq", + meta: dict[str, Any] | None = None, + backend: str | None = None, + model_seqlen: int | None = None, + block_name_to_quantize: str | None = None, + module_name_preceding_first_block: list[str] | None = None, + batch_size: int = 1, + pad_token_id: int | None = None, + max_input_length: int | None = None, + cache_block_outputs: bool = True, + modules_in_block_to_quantize: list[list[str]] | None = None, + **kwargs, + ): + self.quant_method = QuantizationMethod.GPTQ + self.bits = bits + self.tokenizer = tokenizer + self.dataset = dataset + self.group_size = group_size + self.damp_percent = damp_percent + self.desc_act = desc_act + self.act_group_aware = act_group_aware + self.sym = sym + self.true_sequential = true_sequential + self.format = format.lower() + # Compatible with legacy field: checkpoint_format + if kwargs.get("checkpoint_format") is not None: + self.format = kwargs.pop("checkpoint_format").lower() + self.meta = meta + self.backend = backend.lower() if isinstance(backend, str) else backend + self.model_seqlen = model_seqlen + self.block_name_to_quantize = block_name_to_quantize + self.module_name_preceding_first_block = module_name_preceding_first_block + self.batch_size = batch_size + self.pad_token_id = pad_token_id + self.max_input_length = max_input_length + self.cache_block_outputs = cache_block_outputs + self.modules_in_block_to_quantize = modules_in_block_to_quantize + self.post_init() + + def get_loading_attributes(self): + attributes_dict = copy.deepcopy(self.__dict__) + loading_attributes = ["max_input_length", "backend"] + loading_attributes_dict = {i: j for i, j in attributes_dict.items() if i in loading_attributes} + return loading_attributes_dict + + def post_init(self): + r""" + Safety checker that arguments are correct + """ + if self.bits not in [2, 3, 4, 8]: + raise ValueError(f"Only support quantization to [2,3,4,8] bits but found {self.bits}") + if self.group_size != -1 and self.group_size <= 0: + raise ValueError("group_size must be greater than 0 or equal to -1") + if not (0 < self.damp_percent < 1): + raise ValueError("damp_percent must between 0 and 1.") + if self.dataset is not None: + if isinstance(self.dataset, str): + if self.dataset not in ["wikitext2", "c4", "c4-new"]: + raise ValueError( + f"""You have entered a string value for dataset. You can only choose between + ['wikitext2','c4','c4-new'], but we found {self.dataset}""" + ) + elif not isinstance(self.dataset, list): + raise ValueError( + f"""dataset needs to be either a list of string or a value in + ['wikitext2','c4','c4-new'], but we found {self.dataset}""" + ) + + # act_group_order is only applicable when `desc_act = False` + if self.desc_act and self.act_group_aware: + self.act_group_aware = False + logger.warning("`act_group_aware` has been auto-disabled as it is not compatible with `desc_act = True`.") + + # make sure backend default stays consistent with gptqmodel expectations + if self.backend is None: + self.backend = "auto" + if self.modules_in_block_to_quantize is not None: + optimum_version = version.parse(importlib.metadata.version("optimum")) + if optimum_version < version.parse("1.15.0"): + raise ValueError( + "You current version of `optimum` does not support `modules_in_block_to_quantize` quantization argument, please upgrade `optimum` package to a version superior than 1.15.0 ." + ) + + def to_dict(self) -> dict[str, Any]: + config_dict = super().to_dict() + # Compatible with legacy field: checkpoint_format + config_dict["checkpoint_format"] = self.format + return config_dict + + def to_dict_optimum(self): + """ + Get compatible dict for optimum gptq config + """ + return self.to_dict() + + @classmethod + def from_dict_optimum(cls, config_dict): + """ + Get compatible class with optimum gptq config dict + """ + + config = cls(**config_dict) + return config + + +@dataclass +class AwqConfig(GPTQConfig): + """ + This is a wrapper class about all possible attributes and features that you can play with a model that has been + loaded using `auto-awq` library awq quantization relying on auto_awq backend. + + Args: + bits (`int`, *optional*, defaults to 4): + The number of bits to quantize to. + group_size (`int`, *optional*, defaults to 128): + The group size to use for quantization. Recommended value is 128 and -1 uses per-column quantization. + zero_point (`bool`, *optional*, defaults to `True`): + Whether to use zero point quantization. + backend (`AwqBackend`, *optional*, defaults to `AwqBackend.AUTO`): + The quantization backend. + modules_to_not_convert (`list`, *optional*, default to `None`): + The list of modules to not quantize, useful for quantizing models that explicitly require to have + some modules left in their original precision (e.g. Whisper encoder, Llava encoder, Mixtral gate layers). + Note you cannot quantize directly with transformers, please refer to `AutoAWQ` documentation for quantizing HF models. + """ + + def __init__( + self, + bits: int = 4, + group_size: int = 128, + zero_point: bool = True, + backend: AwqBackend = AwqBackend.AUTO, + modules_to_not_convert: list | None = None, + **kwargs, + ): + format = kwargs.pop("format", AwqFormat.GEMM) + # Compatible with legacy field: version + if kwargs.get("version") is not None: + format = kwargs.pop("version").lower() + # Compatible with legacy backend + if backend == AwqBackend.LEGACY_AWQ: + backend = AwqBackend.AUTO + self.zero_point = zero_point + self.modules_to_not_convert = modules_to_not_convert + + super().__init__(bits=bits, group_size=group_size, backend=backend, format=format, **kwargs) + self.quant_method = QuantizationMethod.AWQ + + def post_init(self): + r""" + Safety checker that arguments are correct + """ + + if self.backend == "llm-awq": + self.format = AwqFormat.LLM_AWQ + self.backend = AwqBackend.AUTO + + if self.format not in AwqFormat.__members__.values(): + raise ValueError(f"Invalid format '{self.format}'. Must be one of: {[b.value for b in AwqFormat]}") + + if self.backend not in AwqBackend.__members__.values(): + raise ValueError(f"Invalid backend '{self.backend}'. Must be one of: {[b.value for b in AwqBackend]}") + + def to_dict(self) -> dict[str, Any]: + config_dict = super().to_dict() + config_dict.pop("checkpoint_format") + # Compatible with legacy field: version + config_dict["version"] = self.format + return config_dict + + +@dataclass +class AqlmConfig(QuantizationConfigMixin): + """ + This is a wrapper class about `aqlm` parameters. + + Args: + in_group_size (`int`, *optional*, defaults to 8): + The group size along the input dimension. + out_group_size (`int`, *optional*, defaults to 1): + The group size along the output dimension. It's recommended to always use 1. + num_codebooks (`int`, *optional*, defaults to 1): + Number of codebooks for the Additive Quantization procedure. + nbits_per_codebook (`int`, *optional*, defaults to 16): + Number of bits encoding a single codebook vector. Codebooks size is 2**nbits_per_codebook. + linear_weights_not_to_quantize (`Optional[list[str]]`, *optional*): + List of full paths of `nn.Linear` weight parameters that shall not be quantized. + kwargs (`dict[str, Any]`, *optional*): + Additional parameters from which to initialize the configuration object. + """ + + def __init__( + self, + in_group_size: int = 8, + out_group_size: int = 1, + num_codebooks: int = 1, + nbits_per_codebook: int = 16, + linear_weights_not_to_quantize: list[str] | None = None, + **kwargs, + ): + self.quant_method = QuantizationMethod.AQLM + self.in_group_size = in_group_size + self.out_group_size = out_group_size + self.num_codebooks = num_codebooks + self.nbits_per_codebook = nbits_per_codebook + self.linear_weights_not_to_quantize = linear_weights_not_to_quantize + + self.post_init() + + def post_init(self): + r""" + Safety checker that arguments are correct - also replaces some NoneType arguments with their default values. + """ + if not isinstance(self.in_group_size, int): + raise TypeError("in_group_size must be a float") + if not isinstance(self.out_group_size, int): + raise TypeError("out_group_size must be a float") + if not isinstance(self.num_codebooks, int): + raise TypeError("num_codebooks must be a float") + if not isinstance(self.nbits_per_codebook, int): + raise TypeError("nbits_per_codebook must be a float") + + if self.linear_weights_not_to_quantize is not None and not isinstance( + self.linear_weights_not_to_quantize, list + ): + raise ValueError("linear_weights_not_to_quantize must be a list of strings") + + if self.linear_weights_not_to_quantize is None: + self.linear_weights_not_to_quantize = [] + + +@dataclass +class VptqLayerConfig(QuantizationConfigMixin): + """ + This is used to explain vptq config params for each layer + Args: + enable_norm (`bool`, *optional*, defaults to `True`): to control if we have scale/bias for fp-weight + enable_perm (`bool`, *optional*, defaults to `True`): to perm input_channel or not + group_num (`int`, *optional*, defaults to `1`): how many single groups for vector-quantization + group_size (`int`, *optional*, defaults to `-1`): depends on out-features + indices_as_float (`bool`, *optional*, defaults to `False`): for Finetuning + is_indice_packed (`bool`, *optional*, defaults to `True`): should always be True + num_centroids (`list`, *optional*, defaults to `[-1, -1]`): centroid numbers of clusters + num_res_centroids (`list`, *optional*, defaults to `[-1, -1]`): ditto for residual + outlier_size (`int`, *optional*, defaults to `1`): outliers + vector_lens (`list`, *optional*, defaults to `[-1, -1]`): centroid vector length in quantization + """ + + def __init__( + self, + enable_norm: bool = True, + enable_perm: bool = True, + group_num: int = 1, + group_size: int = -1, + in_features: int = -1, + indices_as_float: bool = False, + is_indice_packed: bool = True, + num_centroids: list = [-1, -1], + num_res_centroids: list = [-1, -1], + out_features: int = -1, + outlier_size: int = 0, + vector_lens: list = [-1, -1], + **kwargs, + ): + self.enable_norm = enable_norm + self.enable_perm = enable_perm + self.group_num = group_num + self.group_size = group_size + self.in_features = in_features + self.indices_as_float = indices_as_float + self.is_indice_packed = is_indice_packed + self.num_centroids = num_centroids + self.num_res_centroids = num_res_centroids + self.out_features = out_features + self.outlier_size = outlier_size + self.vector_lens = vector_lens + self.post_init() + + def post_init(self): + r""" + Safety checker that arguments are correct + """ + if self.is_indice_packed is False: + raise ValueError("is_indice_packed should always be True") + + +@dataclass +class VptqConfig(QuantizationConfigMixin): + """ + This is a wrapper class about `vptq` parameters. + + Args: + enable_proxy_error (`bool`, *optional*, defaults to `False`): calculate proxy error for each layer + config_for_layers (`Dict`, *optional*, defaults to `{}`): quantization params for each layer + shared_layer_config (`Dict`, *optional*, defaults to `{}`): shared quantization params among layers + modules_to_not_convert (`list`, *optional*, default to `None`): + The list of modules to not quantize, useful for quantizing models that explicitly require to have + some modules left in their original precision (e.g. Whisper encoder, Llava encoder, Mixtral gate layers). + kwargs (`dict[str, Any]`, *optional*): + Additional parameters from which to initialize the configuration object. + """ + + def __init__( + self, + enable_proxy_error: bool = False, + config_for_layers: dict[str, Any] = {}, + shared_layer_config: dict[str, Any] = {}, + modules_to_not_convert: list | None = None, + **kwargs, + ): + self.quant_method = QuantizationMethod.VPTQ + self.enable_proxy_error = enable_proxy_error + self.config_for_layers: dict[str, Any] = config_for_layers + self.shared_layer_config: dict[str, Any] = shared_layer_config + self.modules_to_not_convert = modules_to_not_convert + self.post_init() + + def post_init(self): + r""" + Safety checker that arguments are correct + """ + for layer_param in self.config_for_layers.values(): + VptqLayerConfig(**layer_param) + if self.enable_proxy_error is True: + raise ValueError("enable_proxy_error should always be False until we support training") + + +@dataclass +class QuantoConfig(QuantizationConfigMixin): + """ + This is a wrapper class about all possible attributes and features that you can play with a model that has been + loaded using `quanto`. + + Args: + weights (`str`, *optional*, defaults to `"int8"`): + The target dtype for the weights after quantization. Supported values are ("float8","int8","int4","int2") + activations (`str`, *optional*): + The target dtype for the activations after quantization. Supported values are (None,"int8","float8") + modules_to_not_convert (`list`, *optional*, default to `None`): + The list of modules to not quantize, useful for quantizing models that explicitly require to have + some modules left in their original precision (e.g. Whisper encoder, Llava encoder, Mixtral gate layers). + """ + + def __init__( + self, + weights="int8", + activations=None, + modules_to_not_convert: list | None = None, + **kwargs, + ): + self.quant_method = QuantizationMethod.QUANTO + self.weights = weights + self.activations = activations + self.modules_to_not_convert = modules_to_not_convert + self.post_init() + + def post_init(self): + r""" + Safety checker that arguments are correct + """ + accepted_weights = ["float8", "int8", "int4", "int2"] + accepted_activations = [None, "int8", "float8"] + if self.weights not in accepted_weights: + raise ValueError(f"Only support weights in {accepted_weights} but found {self.weights}") + if self.activations not in accepted_activations: + raise ValueError(f"Only support weights in {accepted_activations} but found {self.activations}") + + +@dataclass +class EetqConfig(QuantizationConfigMixin): + """ + This is a wrapper class about all possible attributes and features that you can play with a model that has been + loaded using `eetq`. + + Args: + weights (`str`, *optional*, defaults to `"int8"`): + The target dtype for the weights. Supported value is only "int8" + modules_to_not_convert (`list`, *optional*, default to `None`): + The list of modules to not quantize, useful for quantizing models that explicitly require to have + some modules left in their original precision. + """ + + def __init__( + self, + weights: str = "int8", + modules_to_not_convert: list | None = None, + **kwargs, + ): + self.quant_method = QuantizationMethod.EETQ + self.weights = weights + self.modules_to_not_convert = modules_to_not_convert + self.post_init() + + def post_init(self): + r""" + Safety checker that arguments are correct + """ + accepted_weights = ["int8"] + if self.weights not in accepted_weights: + raise ValueError(f"Only support weights in {accepted_weights} but found {self.weights}") + + +class CompressedTensorsConfig(QuantizationConfigMixin): + """ + This is a wrapper class that handles compressed-tensors quantization config options. + It is a wrapper around `compressed_tensors.QuantizationConfig` + Args: + config_groups (`typing.dict[str, typing.Union[ForwardRef('QuantizationScheme'), typing.list[str]]]`, *optional*): + dictionary mapping group name to a quantization scheme definition + format (`str`, *optional*, defaults to `"dense"`): + format the model is represented as. Set `run_compressed` True to execute model as the + compressed format if not `dense` + quantization_status (`QuantizationStatus`, *optional*, defaults to `"initialized"`): + status of model in the quantization lifecycle, ie 'initialized', 'calibration', 'frozen' + kv_cache_scheme (`typing.Union[QuantizationArgs, NoneType]`, *optional*): + specifies quantization of the kv cache. If None, kv cache is not quantized. + global_compression_ratio (`typing.Union[float, NoneType]`, *optional*): + 0-1 float percentage of model compression + ignore (`typing.Union[typing.list[str], NoneType]`, *optional*): + layer names or types to not quantize, supports regex prefixed by 're:' + sparsity_config (`typing.dict[str, typing.Any]`, *optional*): + configuration for sparsity compression + quant_method (`str`, *optional*, defaults to `"compressed-tensors"`): + do not override, should be compressed-tensors + run_compressed (`bool`, *optional*, defaults to `True`): alter submodules (usually linear) in order to + emulate compressed model execution if True, otherwise use default submodule + """ + + def __init__( + self, + config_groups: dict[str, Union["QuantizationScheme", list[str]]] | None = None, # noqa: F821 + format: str = "dense", + quantization_status: "QuantizationStatus" = "initialized", # noqa: F821 + kv_cache_scheme: Optional["QuantizationArgs"] = None, # noqa: F821 + global_compression_ratio: float | None = None, + ignore: list[str] | None = None, + sparsity_config: dict[str, Any] | None = None, + quant_method: str = "compressed-tensors", + run_compressed: bool = True, + **kwargs, + ): + if is_compressed_tensors_available(): + from compressed_tensors.config import SparsityCompressionConfig + from compressed_tensors.quantization import QuantizationConfig + else: + raise ImportError( + "compressed_tensors is not installed and is required for compressed-tensors quantization. Please install it with `pip install compressed-tensors`." + ) + self.quantization_config = None + self.sparsity_config = None + + self.run_compressed = run_compressed + + # parse from dict to load nested QuantizationScheme objects + if config_groups or kv_cache_scheme: + self.quantization_config = QuantizationConfig.model_validate( + { + "config_groups": config_groups, + "quant_method": quant_method, + "format": format, + "quantization_status": quantization_status, + "kv_cache_scheme": kv_cache_scheme, + "global_compression_ratio": global_compression_ratio, + "ignore": ignore, + **kwargs, + } + ) + + if sparsity_config: + self.sparsity_config = SparsityCompressionConfig.load_from_registry( + sparsity_config.get("format"), **sparsity_config + ) + + self.quant_method = QuantizationMethod.COMPRESSED_TENSORS + + def post_init(self): + if self.run_compressed: + if self.is_sparsification_compressed: + logger.warning( + "`run_compressed` is only supported for quantized_compressed models" + " and not for sparsified models. Setting `run_compressed=False`" + ) + self.run_compressed = False + elif not self.is_quantization_compressed: + logger.warning( + "`run_compressed` is only supported for compressed models. Setting `run_compressed=False`" + ) + self.run_compressed = False + + @classmethod + def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs): + """ + Instantiates a [`CompressedTensorsConfig`] from a Python dictionary of parameters. + Optionally unwraps any args from the nested quantization_config + + Args: + config_dict (`dict[str, Any]`): + Dictionary that will be used to instantiate the configuration object. + return_unused_kwargs (`bool`,*optional*, defaults to `False`): + Whether or not to return a list of unused keyword arguments. Used for `from_pretrained` method in + `PreTrainedModel`. + kwargs (`dict[str, Any]`): + Additional parameters from which to initialize the configuration object. + + Returns: + [`QuantizationConfigMixin`]: The configuration object instantiated from those parameters. + + """ + + if "quantization_config" in config_dict: + config_dict = dict( + sparsity_config=config_dict.get("sparsity_config"), + **config_dict["quantization_config"], + ) + + return super().from_dict(config_dict, return_unused_kwargs=return_unused_kwargs, **kwargs) + + def to_dict(self) -> dict[str, Any]: + """ + Quantization config to be added to config.json + + Serializes this instance to a Python dictionary. Returns: + `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance. + """ + quantization_config = {} + if self.quantization_config is not None: + quantization_config = self.quantization_config.model_dump() + else: + quantization_config["quant_method"] = QuantizationMethod.COMPRESSED_TENSORS + + if self.sparsity_config is not None: + quantization_config["sparsity_config"] = self.sparsity_config.model_dump() + else: + quantization_config["sparsity_config"] = {} + + return quantization_config + + def to_diff_dict(self) -> dict[str, Any]: + """ + Removes all attributes from config which correspond to the default config attributes for better readability and + serializes to a Python dictionary. + Returns: + `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance, + """ + config_dict = self.to_dict() + + # get the default config dict + default_config_dict = CompressedTensorsConfig().to_dict() + + serializable_config_dict = {} + + # only serialize values that differ from the default config + for key, value in config_dict.items(): + if key not in default_config_dict or value != default_config_dict[key]: + serializable_config_dict[key] = value + + return serializable_config_dict + + def get_loading_attributes(self): + return {"run_compressed": self.run_compressed} + + @property + def is_quantized(self): + return bool(self.quantization_config) and bool(self.quantization_config.config_groups) + + @property + def is_quantization_compressed(self): + from compressed_tensors.quantization import QuantizationStatus + + qc = self.quantization_config + return self.is_quantized and (qc is not None and qc.quantization_status == QuantizationStatus.COMPRESSED) + + @property + def is_sparsification_compressed(self): + from compressed_tensors.config import ( + CompressionFormat, + SparsityCompressionConfig, + ) + + return ( + isinstance(self.sparsity_config, SparsityCompressionConfig) + and self.sparsity_config.format != CompressionFormat.dense.value + ) + + +@dataclass +class FbgemmFp8Config(QuantizationConfigMixin): + """ + This is a wrapper class about all possible attributes and features that you can play with a model that has been + loaded using fbgemm fp8 quantization. + + Args: + activation_scale_ub (`float`, *optional*, defaults to 1200.0): + The activation scale upper bound. This is used when quantizing the input activation. + modules_to_not_convert (`list`, *optional*, default to `None`): + The list of modules to not quantize, useful for quantizing models that explicitly require to have + some modules left in their original precision. + """ + + def __init__( + self, + activation_scale_ub: float = 1200.0, + modules_to_not_convert: list | None = None, + **kwargs, + ): + self.quant_method = QuantizationMethod.FBGEMM_FP8 + self.activation_scale_ub = activation_scale_ub + self.modules_to_not_convert = modules_to_not_convert + + def get_loading_attributes(self): + attributes_dict = copy.deepcopy(self.__dict__) + loading_attributes = ["activation_scale_ub"] + loading_attributes_dict = {i: j for i, j in attributes_dict.items() if i in loading_attributes} + return loading_attributes_dict + + +@dataclass +class HiggsConfig(QuantizationConfigMixin): + """ + HiggsConfig is a configuration class for quantization using the HIGGS method. + + Args: + bits (int, *optional*, defaults to 4): + Number of bits to use for quantization. Can be 2, 3 or 4. Default is 4. + p (int, *optional*, defaults to 2): + Quantization grid dimension. 1 and 2 are supported. 2 is always better in practice. Default is 2. + modules_to_not_convert (`list`, *optional*, default to ["lm_head"]): + List of linear layers that should not be quantized. + hadamard_size (int, *optional*, defaults to 512): + Hadamard size for the HIGGS method. Default is 512. Input dimension of matrices is padded to this value. Decreasing this below 512 will reduce the quality of the quantization. + group_size (int, *optional*, defaults to 256): + Group size for the HIGGS method. Can be 64, 128 or 256. Decreasing it barely affects the performance. Default is 256. Must be a divisor of hadamard_size. + tune_metadata ('dict', *optional*, defaults to {}): + Module-wise metadata (gemm block shapes, GPU metadata, etc.) for saving the kernel tuning results. Default is an empty dictionary. Is set automatically during tuning. + """ + + def __init__( + self, + bits: int = 4, + p: int = 2, + modules_to_not_convert: list[str] | None = None, + hadamard_size: int = 512, + group_size: int = 256, + tune_metadata: dict[str, Any] | None = None, + **kwargs, + ): + if tune_metadata is None: + tune_metadata = {} + self.quant_method = QuantizationMethod.HIGGS + self.bits = bits + self.p = p + self.modules_to_not_convert = modules_to_not_convert + self.hadamard_size = hadamard_size + self.group_size = group_size + self.tune_metadata = tune_metadata + + self.post_init() + + def post_init(self): + r""" + Safety checker that arguments are correct - also replaces some NoneType arguments with their default values. + """ + if self.bits not in [2, 3, 4]: + raise ValueError("bits must be 2, 3, or 4") + if self.p not in [1, 2]: + raise ValueError("p must be 1 or 2. 2 is always better in practice") + if self.group_size not in [64, 128, 256]: + raise ValueError("group_size must be 64, 128, or 256") + if self.hadamard_size % self.group_size != 0: + raise ValueError("hadamard_size must be divisible by group_size") + + +@dataclass +class FPQuantConfig(QuantizationConfigMixin): + """ + FPQuantConfig is a configuration class for quantization using the FPQuant method. + + Args: + forward_dtype (`str`, *optional*, defaults to `"nvfp4"`): + The dtype to use for the forward pass. + forward_method (`str`, *optional*, defaults to `"abs_max"`): + The scaling to use for the forward pass. Can be `"abs_max"` or `"quest"`. `"abs_max"` is better for PTQ, `"quest"` is better for QAT. + backward_dtype (`str`, *optional*, defaults to `"bf16"`): + The dtype to use for the backward pass. + store_master_weights (`bool`, *optional*, defaults to `False`): + Whether to store the master weights. Needed for QAT over layer weights. + hadamard_group_size (`int`, *optional*): + The group size for the hadamard transform before quantization for `"quest"` it matches the MXFP4 group size (32). If `None`, it will be set to 16 for `"nvfp4"` and 32 for `"mxfp4"`. + pseudoquantization (`bool`, *optional*, defaults to `False`): + Whether to use Triton-based pseudo-quantization. Is mandatory for non-Blackwell GPUs. Doesn't provide any speedup. For debugging purposes. + transform_init (`str`, *optional*, defaults to `"hadamard"`): a method to initialize the pre-processing matrix with. Can be `"hadamard"`, `"identity"` or `"gsr"`. + modules_to_not_convert (`list`, *optional*): + The list of modules to not quantize, useful for quantizing models that explicitly require to have + some modules left in their original precision. + """ + + def __init__( + self, + forward_dtype: str = "nvfp4", + forward_method: str = "abs_max", + backward_dtype: str = "bf16", + store_master_weights: bool = False, + hadamard_group_size: int | None = None, + pseudoquantization: bool = False, + transform_init: str = "hadamard", + modules_to_not_convert: list[str] | None = None, + **kwargs, + ): + self.forward_dtype = forward_dtype + self.forward_method = forward_method + self.backward_dtype = backward_dtype + self.store_master_weights = store_master_weights + self.hadamard_group_size = hadamard_group_size + self.pseudoquantization = pseudoquantization + self.transform_init = transform_init + self.modules_to_not_convert = modules_to_not_convert + + self.quant_method = QuantizationMethod.FPQUANT + self.post_init() + + def post_init(self): + r""" + Safety checker that arguments are correct - also replaces some NoneType arguments with their default values. + """ + + if self.hadamard_group_size is None: + if self.forward_dtype == "nvfp4": + self.hadamard_group_size = 16 + else: + self.hadamard_group_size = 32 + + if self.forward_dtype == "mxfp4": + if self.forward_method not in ["abs_max", "quest"]: + raise ValueError("Only 'abs_max' and 'quest' are supported for forward_method for 'mxfp4'.") + if self.hadamard_group_size is None: + self.hadamard_group_size = 32 + if self.hadamard_group_size not in [32, 64, 128]: + raise ValueError("Only a `hadamard_group_size` of [32, 64, 128] is supported for 'mxfp4'.") + elif self.forward_dtype == "nvfp4": + if self.forward_method != "abs_max": + raise ValueError("Only 'abs_max' is supported for forward_method for 'nvfp4'.") + if self.hadamard_group_size is None: + self.hadamard_group_size = 16 + if self.hadamard_group_size not in [16, 32, 64, 128]: + raise ValueError("Only a `hadamard_group_size` of [16, 32, 64, 128] is supported for 'nvfp4'.") + else: + raise ValueError("Only 'mxfp4' and 'nvfp4' are supported for forward_dtype for now.") + + if self.backward_dtype not in ["bf16", "mxfp8", "mxfp4"]: + raise ValueError("Only 'bf16', 'mxfp8' and 'mxfp4' are supported for backward_dtype for now.") + + if self.backward_dtype != "bf16" and self.forward_dtype != "mxfp4": + raise ValueError("Only 'mxfp4' forward is compatible with non-bf16 backwards for now.") + + if self.transform_init not in ["hadamard", "identity", "gsr"]: + raise ValueError("Only 'hadamard', 'identity' and 'gsr' are supported for transform_init.") + + if self.modules_to_not_convert is None: + self.modules_to_not_convert = ["lm_head"] + + +@dataclass +class TorchAoConfig(QuantizationConfigMixin): + """Config class for torchao quantization/sparsity techniques. + + Args: + quant_type (`AOBaseConfig`): + A torchao `AOBaseConfig` instance specifying the quantization type, e.g. + `Int4WeightOnlyConfig(group_size=32)`, `Int8WeightOnlyConfig()`, + `Int8DynamicActivationInt8WeightConfig()`, `Float8WeightOnlyConfig()`, etc. + modules_to_not_convert (`list`, *optional*, default to `None`): + The list of modules to not quantize, useful for quantizing models that explicitly require to have + some modules left in their original precision. + include_input_output_embeddings (`bool`, *optional*, defaults to `False`): + Whether to include embedding in quantization or not, input embedding will be removed from + the module_not_to_convert list as well if this flag is set. + untie_embedding_weights (`bool`, *optional*, defaults to `False`): + Whether to untie the weights when we are quantizing input embedding weights that is tied + to other weights. + + Example: + + ```python + from torchao.quantization import Int4WeightOnlyConfig + + quantization_config = TorchAoConfig(Int4WeightOnlyConfig(group_size=32)) + model = AutoModelForCausalLM.from_pretrained( + model_id, device_map="cuda", torch_dtype=torch.bfloat16, quantization_config=quantization_config + ) + ``` + """ + + quant_method: QuantizationMethod + quant_type: "AOBaseConfig" # noqa: F821 + modules_to_not_convert: list | None + include_input_output_embeddings: bool + untie_embedding_weights: bool + + def __init__( + self, + quant_type: "AOBaseConfig", # noqa: F821 + modules_to_not_convert: list | None = None, + include_input_output_embeddings: bool = False, + untie_embedding_weights: bool = False, + **kwargs, + ): + self.quant_method = QuantizationMethod.TORCHAO + self.quant_type = quant_type + self.modules_to_not_convert = modules_to_not_convert + self.include_input_output_embeddings = include_input_output_embeddings + self.untie_embedding_weights = untie_embedding_weights + self.post_init() + + def post_init(self): + """Validate configuration and set defaults.""" + if not is_torchao_available(): + raise ValueError("TorchAoConfig requires torchao to be installed. Install with `pip install torchao`") + + if isinstance(self.quant_type, str): + raise ValueError( + f"String-based quantization type '{self.quant_type}' is no longer supported. " + f"Please use the corresponding Config object directly, e.g. " + f"TorchAoConfig(Int4WeightOnlyConfig(group_size=32)) instead of " + f"TorchAoConfig('int4_weight_only', group_size=32)." + ) + + from torchao.quantization.quant_api import AOBaseConfig + + if not isinstance(self.quant_type, AOBaseConfig): + raise TypeError(f"quant_type must be an AOBaseConfig instance, got {type(self.quant_type)}") + + def get_apply_tensor_subclass(self): + """Return the quantization config to apply.""" + return self.quant_type + + def to_dict(self): + """Convert configuration to a dictionary.""" + d = super().to_dict() + + from torchao.core.config import config_to_dict + + d["quant_type"] = {"default": config_to_dict(self.quant_type)} + + return d + + @classmethod + def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs): + """Create configuration from a dictionary.""" + from torchao.core.config import config_from_dict + + config_dict = config_dict.copy() + quant_type = config_dict.pop("quant_type") + + # Check if we only have one key which is "default" + # In the future we may update this + assert len(quant_type) == 1 and "default" in quant_type, ( + "Expected only one key 'default' in quant_type dictionary" + ) + quant_type = quant_type["default"] + quant_type = config_from_dict(quant_type) + + return cls(quant_type=quant_type, **config_dict) + + +@dataclass +class BitNetQuantConfig(QuantizationConfigMixin): + """ + Configuration class for applying BitNet quantization. + + Args: + modules_to_not_convert (`Optional[List]`, *optional*): + Optionally, provides a list of full paths of `nn.Linear` weight parameters + that shall not be quantized. Defaults to None. + linear_class (`str`, *optional*, defaults to `"bitlinear"`): + The type of linear class to use. Can be either `bitlinear` or `autobitlinear`. + quantization_mode (`str`, *optional*, defaults to `"offline"`): + The quantization mode to use. Can be either `online` or `offline`. + In `online` mode, the weight quantization parameters are calculated dynamically + during each forward pass (e.g., based on the current weight values). This can + adapt to weight changes during training (Quantization-Aware Training - QAT). + In `offline` mode, quantization parameters are pre-calculated *before* inference. + These parameters are then fixed and loaded into the quantized model. This + generally results in lower runtime overhead compared to online quantization. + use_rms_norm (`bool`, *optional*, defaults to `False`): + Whether to apply RMSNorm on the activations before quantization. This matches the original BitNet paper's approach + of normalizing activations before quantization/packing. + rms_norm_eps (`float`, *optional*, defaults to 1e-06): + The epsilon value used in the RMSNorm layer for numerical stability. + kwargs (`dict[str, Any]`, *optional*): + Additional keyword arguments that may be used by specific quantization + backends or future versions. + """ + + def __init__( + self, + modules_to_not_convert: list | None = None, + linear_class: str = "bitlinear", + quantization_mode: str = "offline", + use_rms_norm: bool = False, + rms_norm_eps: float | None = 1e-6, + **kwargs, + ): + if linear_class not in ["bitlinear", "autobitlinear"]: + raise ValueError(f"linear_class must be either 'bitlinear' or 'autobitlinear', but got {linear_class}") + if quantization_mode not in ["online", "offline"]: + raise ValueError(f"quantization_mode must be either 'online' or 'offline', but got {quantization_mode}") + self.quant_method = QuantizationMethod.BITNET + self.modules_to_not_convert = modules_to_not_convert + self.linear_class = linear_class + self.quantization_mode = quantization_mode + self.use_rms_norm = use_rms_norm + self.rms_norm_eps = rms_norm_eps + self.post_init() + + def post_init(self): + r""" + Safety checker that arguments are correct + """ + + +@dataclass +class SpQRConfig(QuantizationConfigMixin): + """ + This is a wrapper class about `spqr` parameters. Refer to the original publication for more details. + + Args: + bits (`int`, *optional*, defaults to 3): + Specifies the bit count for the weights and first order zero-points and scales. + Currently only bits = 3 is supported. + beta1 (`int`, *optional*, defaults to 16): + SpQR tile width. Currently only beta1 = 16 is supported. + beta2 (`int`, *optional*, defaults to 16): + SpQR tile height. Currently only beta2 = 16 is supported. + shapes (`Optional`, *optional*): + A dictionary holding the shape of each object. We need this because it's impossible + to deduce the exact size of the parameters just from bits, beta1, beta2. + modules_to_not_convert (`Optional[list[str]]`, *optional*): + Optionally, provides a list of full paths of `nn.Linear` weight parameters that shall not be quantized. + Defaults to None. + kwargs (`dict[str, Any]`, *optional*): + Additional parameters from which to initialize the configuration object. + """ + + def __init__( + self, + bits: int = 3, + beta1: int = 16, + beta2: int = 16, + shapes: dict[str, int] | None = None, + modules_to_not_convert: list[str] | None = None, + **kwargs, + ): + if shapes is None: + shapes = {} + self.shapes = shapes + self.quant_method = QuantizationMethod.SPQR + self.bits = bits + self.beta1 = beta1 + self.beta2 = beta2 + self.modules_to_not_convert = modules_to_not_convert + self.post_init() + + def post_init(self): + r""" + Safety checker that arguments are correct - also replaces some NoneType arguments with their default values. + """ + if not isinstance(self.bits, int): + raise TypeError("bits must be an int") + if not isinstance(self.beta1, int): + raise TypeError("beta1 must be an int") + if not isinstance(self.beta2, int): + raise TypeError("beta2 must be an int") + + if self.bits != 3: + raise ValueError("SpQR currently only supports bits = 3") + if self.beta1 != 16: + raise ValueError("SpQR currently only supports beta1 = 16") + if self.beta2 != 16: + raise ValueError("SpQR currently only supports beta2 = 16") + if not isinstance(self.shapes, dict): + raise TypeError("shapes must be a dict") + + +@dataclass +class FineGrainedFP8Config(QuantizationConfigMixin): + """ + FineGrainedFP8Config is a configuration class for fine-grained FP8 quantization used mainly for deepseek models. + + Args: + activation_scheme (`str`, *optional*, defaults to `"dynamic"`): + The scheme used for activation, the defaults and only support scheme for now is "dynamic". + weight_block_size (`typing.tuple[int, int]`, *optional*, defaults to `(128, 128)`): + The size of the weight blocks for quantization, default is (128, 128). + dequantize (`bool`, *optional*, defaults to `False`): + Whether to dequantize the model during loading. + modules_to_not_convert (`list`, *optional*): + A list of module names that should not be converted during quantization. + """ + + def __init__( + self, + activation_scheme: str = "dynamic", + weight_block_size: tuple[int, int] = (128, 128), + dequantize: bool = False, + modules_to_not_convert: list | None = None, + **kwargs, + ): + self.quant_method = QuantizationMethod.FP8 + self.modules_to_not_convert = modules_to_not_convert + self.activation_scheme = activation_scheme + self.weight_block_size = weight_block_size + self.dequantize = dequantize + self.post_init() + + def post_init(self): + r""" + Safety checker that arguments are correct + """ + self.activation_scheme = self.activation_scheme.lower() + if self.activation_scheme not in ["dynamic", "static"]: + raise ValueError(f"Activation scheme {self.activation_scheme} not supported") + if self.weight_block_size is not None and len(self.weight_block_size) != 2: + raise ValueError("weight_block_size must be a tuple of two integers") + if self.weight_block_size is not None and (self.weight_block_size[0] <= 0 or self.weight_block_size[1] <= 0): + raise ValueError("weight_block_size must be a tuple of two positive integers") + + def get_loading_attributes(self): + return {"dequantize": self.dequantize, "modules_to_not_convert": self.modules_to_not_convert} + + +class QuarkConfig(QuantizationConfigMixin): + def __init__( + self, + **kwargs, + ): + if is_torch_available() and is_quark_available(): + from quark import __version__ as quark_version + from quark.torch.export.config.config import JsonExporterConfig + from quark.torch.export.main_export.quant_config_parser import QuantConfigParser + from quark.torch.quantization.config.config import Config + else: + raise ImportError( + "Quark is not installed. Please refer to https://quark.docs.amd.com/latest/install.html." + ) + # This might be e.g. `"fp8"` or `"awq"`. + self.custom_mode = kwargs["quant_method"] + self.legacy = "export" not in kwargs + + if self.custom_mode in ["awq", "fp8"]: + # Legacy (quark<1.0) or custom export. + self.quant_config = QuantConfigParser.from_custom_config(kwargs, is_bias_quantized=False) + self.json_export_config = JsonExporterConfig() + else: + self.quant_config = Config.from_dict(kwargs) + + if "export" in kwargs: + # TODO: Remove this check once configuration version is handled natively by Quark. + if "min_kv_scale" in kwargs["export"] and version.parse(quark_version) < version.parse("0.8"): + min_kv_scale = kwargs["export"].pop("min_kv_scale") + logger.warning( + f"The parameter `min_kv_scale={min_kv_scale}` was found in the model config.json's `quantization_config.export` configuration, but this parameter is supported only for quark>=0.8. Ignoring this configuration parameter. Please update the `amd-quark` package." + ) + + self.json_export_config = JsonExporterConfig(**kwargs["export"]) + else: + # Legacy (quark<1.0) or custom export. + self.json_export_config = JsonExporterConfig() + + self.quant_method = QuantizationMethod.QUARK + + +@dataclass +class Mxfp4Config(QuantizationConfigMixin): + """ + This is a wrapper class about all possible attributes and features that you can play with a model that has been + loaded using mxfp4 quantization. + + Args: + modules_to_not_convert (`list`, *optional*, default to `None`): + The list of modules to not quantize, useful for quantizing models that explicitly require to have + some modules left in their original precision. + dequantize (`bool`, *optional*, default to `False`): + Whether we dequantize the model to bf16 precision or not + """ + + def __init__( + self, + modules_to_not_convert: list | None = None, + dequantize: bool = False, + **kwargs, + ): + self.quant_method = QuantizationMethod.MXFP4 + self.modules_to_not_convert = modules_to_not_convert + self.dequantize = dequantize + + def get_loading_attributes(self): + return {"dequantize": self.dequantize} + + def to_dict(self) -> dict[str, Any]: + """ + Serializes this instance to a Python dictionary. Returns: + `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance. + """ + return {"quant_method": self.quant_method, "modules_to_not_convert": self.modules_to_not_convert} + + +class MetalConfig(QuantizationConfigMixin): + """ + Configuration class for Metal affine quantization targeting Apple Silicon (MPS) devices. + + This quantization method uses the ``mlx-quantization-metal-kernels`` Metal kernels from the Hugging Face Hub + to perform affine quantization (scales + qbiases) with configurable bit-width and group size. + The quantized weights are packed into ``uint32`` tensors and the forward pass uses fused + dequantization + matmul Metal kernels. + """ + + def __init__( + self, + bits: int = 4, + group_size: int = 64, + modules_to_not_convert: list | None = None, + dequantize: bool = False, + **kwargs, + ): + self.quant_method = QuantizationMethod.METAL + self.bits = bits + self.group_size = group_size + self.modules_to_not_convert = modules_to_not_convert + self.dequantize = dequantize + self.post_init() + + def post_init(self): + if self.bits not in (2, 4, 8): + raise ValueError(f"Metal quantization only supports bits in {{2, 4, 8}}, got {self.bits}") + if self.group_size <= 0: + raise ValueError(f"group_size must be positive, got {self.group_size}") + + def get_loading_attributes(self): + return {"dequantize": self.dequantize} + + def to_dict(self) -> dict[str, Any]: + return { + "quant_method": self.quant_method, + "bits": self.bits, + "group_size": self.group_size, + "modules_to_not_convert": self.modules_to_not_convert, + } + + +@dataclass +class FourOverSixConfig(QuantizationConfigMixin): + """ + This is a wrapper class containing all options for quantization with `fouroversix`. In brief, + Four Over Six is a modification to NVFP4 quantization which adaptively scales the largest value + in each block of 16 FP4 values to either 4 or 6. Selecting a scale of 6 uses the full range of + FP4 values, but selecting a scale of 4 allows for a more uniform distribution of quantization + error. Refer to the original publication for more details: https://arxiv.org/abs/2512.02010. + + Args: + activation_dtype (`str`, *optional*): + Data type to use when quantizing activation tensors. If not provided, `dtype` is used. + activation_scale_rule (`str`, *optional*): + Scaling rule to use when selecting a scale for blocks in activation tensors. If not + provided, `scale_rule` is used. + dtype (`str`, default "nvfp4", *optional*, defaults to `"nvfp4"`): + The data type to use for the layer's weights, activations, and tensors. Can be + `"nvfp4"` or `"mxfp4"`. + gradient_dtype (`str`, *optional*): + Data type to use when quantizing gradient tensors. If not provided, `dtype` is used. + gradient_scale_rule (`str`, *optional*): + Scaling rule to use when selecting a scale for blocks in gradient tensors. If not + provided, `scale_rule` is used. + keep_master_weights (`bool`, default False, *optional*, defaults to `False`): + Whether to keep the master weights. If `True`, high-precision weights are kept at all + times and weights are quantized online in each forward pass. This is useful for + quantized training. + matmul_backend (`str`, *optional*): + The backend to use for matrix multiplications. Can be `"cutlass"` or `"pytorch"`. If + not provided, CUTLASS will be used if available and PyTorch will be used otherwise. + output_dtype (`str`, *optional*, defaults to `"bfloat16"`): + The data type to use for the output of the layer. Can be `"bfloat16"` or `"float16"`. + quantize_backend (`str`, *optional*): + The backend to use for quantization. Can be `"cuda"`, `"triton"`, or `"pytorch"`. If + not provided, the fastest backend will be selected based on your environment, and based + on the options supported by each backend. Typically, `"cuda"` will be used for + inference, `"triton"` will be used for training, and `"pytorch"` will be used on + non-CUDA devices. + scale_rule (`str`, default "mse", *optional*, defaults to `"mse"`): + Rule to use when selecting block scales. Can be `"mse"`, `"mae"`, or `"abs_max"` for + Four Over Six, `"static_6"` for default NVFP4 quantization, or `"static_4"` to scale + all blocks to a maximum value of 4. + weight_dtype (`str`, *optional*): + Data type to use when quantizing weight tensors. If not provided, `dtype` is used. + weight_scale_2d (`bool`, default False, *optional*, defaults to `False`): + Whether to compute scale factors on weight tensors in 2D blocks. This should be done + during training. + weight_scale_rule (`str`, *optional*): + Scaling rule to use when selecting a scale for blocks in weight tensors. If not + provided, `scale_rule` is used. + module_config_overrides (`dict[str, dict[str, Any]]`, *optional*): + A dictionary of module-specific configuration overrides. Keys should be module names, and + values should be dictionaries containing the quantization configuration for that module. + This can be used to override the default configuration for specific modules. + modules_to_not_convert (`list[str]`, *optional*, defaults to `['lm_head']`): + The list of modules to exclude from quantization. By default, the `lm_head` is excluded. + """ + + def __init__( + self, + activation_dtype: str | None = None, + activation_scale_rule: str | None = None, + dtype: str = "nvfp4", + gradient_dtype: str | None = None, + gradient_scale_rule: str | None = None, + keep_master_weights: bool = False, + matmul_backend: str | None = None, + output_dtype: str | None = "bfloat16", + quantize_backend: str | None = None, + scale_rule: str = "mse", + weight_dtype: str | None = None, + weight_scale_2d: bool = False, + weight_scale_rule: str | None = None, + module_config_overrides: dict[str, dict[str, Any]] | None = None, + modules_to_not_convert: list[str] | None = ["lm_head"], + **kwargs, + ): + self.quant_method = QuantizationMethod.FOUR_OVER_SIX + + self.activation_dtype = activation_dtype + self.activation_scale_rule = activation_scale_rule + self.dtype = dtype + self.gradient_dtype = gradient_dtype + self.gradient_scale_rule = gradient_scale_rule + self.keep_master_weights = keep_master_weights + self.matmul_backend = matmul_backend + self.quantize_backend = quantize_backend + self.output_dtype = output_dtype + self.scale_rule = scale_rule + self.weight_dtype = weight_dtype + self.weight_scale_2d = weight_scale_2d + self.weight_scale_rule = weight_scale_rule + self.module_config_overrides = module_config_overrides + self.modules_to_not_convert = modules_to_not_convert + + +class SinqConfig(QuantizationConfigMixin): + """ + Quantization config for SINQ / A-SINQ. + + Pass this to: + + AutoModel.from_pretrained(..., quantization_config=SinqConfig(...)) + + Args: + nbits (`int`, default 4): + Quantization bits for weights. + group_size (`int`, default 64): + Group size used in SINQ weight quantization (must be multiple of 8). + tiling_mode (`str`, default "1D"): + Tiling mode for SINQ (typically "1D"; "2D" if supported in your backend). + method (`str`, default "sinq"): + "sinq" – calibration-free weight-only SINQ + "asinq" – A-SINQ (activation-aware), not supported in Hugging Face. Please refer to the official SINQ repository. + modules_to_not_convert (`list[str]`, *optional*): + List of module names/prefixes to keep in full precision. + + **kwargs: + Extra user arguments (kept in `_extra_kwargs` for round-tripping). + """ + + def __init__( + self, + nbits: int = 4, + group_size: int = 64, + tiling_mode: str = "1D", + method: str = "sinq", # "sinq" | "asinq" + modules_to_not_convert: list[str] | None = None, + **kwargs: Any, + ): + self.quant_method = QuantizationMethod.SINQ + + self.nbits = nbits + self.group_size = group_size + self.tiling_mode = tiling_mode + self.method = method + + self.modules_to_not_convert = modules_to_not_convert + + self._extra_kwargs: dict[str, Any] = dict(kwargs) + + self.post_init() + + def post_init(self): + self.nbits = int(self.nbits) + self.group_size = int(self.group_size) + self.tiling_mode = str(self.tiling_mode) + self.method = str(self.method).lower() + + # Validation + if not isinstance(self.nbits, int): + raise TypeError("`nbits` must be convertible to an int") + if not isinstance(self.group_size, int): + raise TypeError("`group_size` must be convertible to an int") + if not isinstance(self.tiling_mode, str): + raise TypeError("`tiling_mode` must be convertible to a string") + if self.method not in {"sinq", "asinq"}: + raise ValueError(f"`method` must be either 'sinq' or 'asinq', got {self.method}") + if self.group_size is not None and self.group_size % 8 != 0: + logger.warning( + f"SINQ: group_size={self.group_size} is not a multiple of 8; this may be rejected by the backend." + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/sentencepiece_model_pb2.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/sentencepiece_model_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..8f063575fd7af2ae65d3d55b054b856ca8b77fe8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/sentencepiece_model_pb2.py @@ -0,0 +1,1511 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: sentencepiece_model.proto + +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# 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. +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database + + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor.FileDescriptor( + name="sentencepiece_model.proto", + package="sentencepiece", + syntax="proto2", + serialized_options=b"H\003", + create_key=_descriptor._internal_create_key, + serialized_pb=( + b'\n\x19sentencepiece_model.proto\x12\rsentencepiece"\xa1\n\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01' + b" \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02" + b" \x01(\t\x12\x41\n\nmodel_type\x18\x03" + b" \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04" + b" \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12" + b' \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12"\n\x12\x63haracter_coverage\x18\n' + b" \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b" + b" \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12" + b' \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12"\n\x16training_sentence_size\x18\r' + b" \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e" + b" \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f" + b" \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12" + b" \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10" + b" \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11" + b" \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14" + b" \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15" + b" \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17" + b" \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16" + b" \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18" + b" \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19" + b" \x01(\x08:\x05\x66\x61lse\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e" + b" \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$" + b" \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18" + b' \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18"' + b" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18)" + b" \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+" + b" \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05\x12\x16\n\tbos_piece\x18." + b" \x01(\t:\x03\x12\x17\n\teos_piece\x18/ \x01(\t:\x04\x12\x18\n\tpad_piece\x18\x30" + b" \x01(\t:\x05\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87" + b" \x12+\n\x1ctrain_extremely_large_corpus\x18\x31" + b' \x01(\x08:\x05\x66\x61lse"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01' + b" \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03" + b" \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12" + b" \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06" + b' \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01' + b' \x03(\x0b\x32".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01' + b" \x01(\t\x12\x10\n\x08\x65xpected\x18\x02" + b' \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01' + b" \x03(\x0b\x32'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02" + b" \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03" + b" \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04" + b" \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05" + b" \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01" + b" \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03" + b' \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03' + ), +) + + +_TRAINERSPEC_MODELTYPE = _descriptor.EnumDescriptor( + name="ModelType", + full_name="sentencepiece.TrainerSpec.ModelType", + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name="UNIGRAM", + index=0, + number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key, + ), + _descriptor.EnumValueDescriptor( + name="BPE", + index=1, + number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key, + ), + _descriptor.EnumValueDescriptor( + name="WORD", + index=2, + number=3, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key, + ), + _descriptor.EnumValueDescriptor( + name="CHAR", + index=3, + number=4, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key, + ), + ], + containing_type=None, + serialized_options=None, + serialized_start=1294, + serialized_end=1347, +) +_sym_db.RegisterEnumDescriptor(_TRAINERSPEC_MODELTYPE) + +_MODELPROTO_SENTENCEPIECE_TYPE = _descriptor.EnumDescriptor( + name="Type", + full_name="sentencepiece.ModelProto.SentencePiece.Type", + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name="NORMAL", + index=0, + number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key, + ), + _descriptor.EnumValueDescriptor( + name="UNKNOWN", + index=1, + number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key, + ), + _descriptor.EnumValueDescriptor( + name="CONTROL", + index=2, + number=3, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key, + ), + _descriptor.EnumValueDescriptor( + name="USER_DEFINED", + index=3, + number=4, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key, + ), + _descriptor.EnumValueDescriptor( + name="BYTE", + index=4, + number=6, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key, + ), + _descriptor.EnumValueDescriptor( + name="UNUSED", + index=5, + number=5, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key, + ), + ], + containing_type=None, + serialized_options=None, + serialized_start=2100, + serialized_end=2184, +) +_sym_db.RegisterEnumDescriptor(_MODELPROTO_SENTENCEPIECE_TYPE) + + +_TRAINERSPEC = _descriptor.Descriptor( + name="TrainerSpec", + full_name="sentencepiece.TrainerSpec", + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name="input", + full_name="sentencepiece.TrainerSpec.input", + index=0, + number=1, + type=9, + cpp_type=9, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="input_format", + full_name="sentencepiece.TrainerSpec.input_format", + index=1, + number=7, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=b"".decode("utf-8"), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="model_prefix", + full_name="sentencepiece.TrainerSpec.model_prefix", + index=2, + number=2, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=b"".decode("utf-8"), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="model_type", + full_name="sentencepiece.TrainerSpec.model_type", + index=3, + number=3, + type=14, + cpp_type=8, + label=1, + has_default_value=True, + default_value=1, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="vocab_size", + full_name="sentencepiece.TrainerSpec.vocab_size", + index=4, + number=4, + type=5, + cpp_type=1, + label=1, + has_default_value=True, + default_value=8000, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="accept_language", + full_name="sentencepiece.TrainerSpec.accept_language", + index=5, + number=5, + type=9, + cpp_type=9, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="self_test_sample_size", + full_name="sentencepiece.TrainerSpec.self_test_sample_size", + index=6, + number=6, + type=5, + cpp_type=1, + label=1, + has_default_value=True, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="character_coverage", + full_name="sentencepiece.TrainerSpec.character_coverage", + index=7, + number=10, + type=2, + cpp_type=6, + label=1, + has_default_value=True, + default_value=0.9995, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="input_sentence_size", + full_name="sentencepiece.TrainerSpec.input_sentence_size", + index=8, + number=11, + type=4, + cpp_type=4, + label=1, + has_default_value=True, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="shuffle_input_sentence", + full_name="sentencepiece.TrainerSpec.shuffle_input_sentence", + index=9, + number=19, + type=8, + cpp_type=7, + label=1, + has_default_value=True, + default_value=True, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="mining_sentence_size", + full_name="sentencepiece.TrainerSpec.mining_sentence_size", + index=10, + number=12, + type=5, + cpp_type=1, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=b"\030\001", + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="training_sentence_size", + full_name="sentencepiece.TrainerSpec.training_sentence_size", + index=11, + number=13, + type=5, + cpp_type=1, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=b"\030\001", + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="seed_sentencepiece_size", + full_name="sentencepiece.TrainerSpec.seed_sentencepiece_size", + index=12, + number=14, + type=5, + cpp_type=1, + label=1, + has_default_value=True, + default_value=1000000, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="shrinking_factor", + full_name="sentencepiece.TrainerSpec.shrinking_factor", + index=13, + number=15, + type=2, + cpp_type=6, + label=1, + has_default_value=True, + default_value=0.75, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="max_sentence_length", + full_name="sentencepiece.TrainerSpec.max_sentence_length", + index=14, + number=18, + type=5, + cpp_type=1, + label=1, + has_default_value=True, + default_value=4192, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="num_threads", + full_name="sentencepiece.TrainerSpec.num_threads", + index=15, + number=16, + type=5, + cpp_type=1, + label=1, + has_default_value=True, + default_value=16, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="num_sub_iterations", + full_name="sentencepiece.TrainerSpec.num_sub_iterations", + index=16, + number=17, + type=5, + cpp_type=1, + label=1, + has_default_value=True, + default_value=2, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="max_sentencepiece_length", + full_name="sentencepiece.TrainerSpec.max_sentencepiece_length", + index=17, + number=20, + type=5, + cpp_type=1, + label=1, + has_default_value=True, + default_value=16, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="split_by_unicode_script", + full_name="sentencepiece.TrainerSpec.split_by_unicode_script", + index=18, + number=21, + type=8, + cpp_type=7, + label=1, + has_default_value=True, + default_value=True, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="split_by_number", + full_name="sentencepiece.TrainerSpec.split_by_number", + index=19, + number=23, + type=8, + cpp_type=7, + label=1, + has_default_value=True, + default_value=True, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="split_by_whitespace", + full_name="sentencepiece.TrainerSpec.split_by_whitespace", + index=20, + number=22, + type=8, + cpp_type=7, + label=1, + has_default_value=True, + default_value=True, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="treat_whitespace_as_suffix", + full_name="sentencepiece.TrainerSpec.treat_whitespace_as_suffix", + index=21, + number=24, + type=8, + cpp_type=7, + label=1, + has_default_value=True, + default_value=False, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="split_digits", + full_name="sentencepiece.TrainerSpec.split_digits", + index=22, + number=25, + type=8, + cpp_type=7, + label=1, + has_default_value=True, + default_value=False, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="control_symbols", + full_name="sentencepiece.TrainerSpec.control_symbols", + index=23, + number=30, + type=9, + cpp_type=9, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="user_defined_symbols", + full_name="sentencepiece.TrainerSpec.user_defined_symbols", + index=24, + number=31, + type=9, + cpp_type=9, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="required_chars", + full_name="sentencepiece.TrainerSpec.required_chars", + index=25, + number=36, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=b"".decode("utf-8"), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="byte_fallback", + full_name="sentencepiece.TrainerSpec.byte_fallback", + index=26, + number=35, + type=8, + cpp_type=7, + label=1, + has_default_value=True, + default_value=False, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="vocabulary_output_piece_score", + full_name="sentencepiece.TrainerSpec.vocabulary_output_piece_score", + index=27, + number=32, + type=8, + cpp_type=7, + label=1, + has_default_value=True, + default_value=True, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="hard_vocab_limit", + full_name="sentencepiece.TrainerSpec.hard_vocab_limit", + index=28, + number=33, + type=8, + cpp_type=7, + label=1, + has_default_value=True, + default_value=True, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="use_all_vocab", + full_name="sentencepiece.TrainerSpec.use_all_vocab", + index=29, + number=34, + type=8, + cpp_type=7, + label=1, + has_default_value=True, + default_value=False, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="unk_id", + full_name="sentencepiece.TrainerSpec.unk_id", + index=30, + number=40, + type=5, + cpp_type=1, + label=1, + has_default_value=True, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="bos_id", + full_name="sentencepiece.TrainerSpec.bos_id", + index=31, + number=41, + type=5, + cpp_type=1, + label=1, + has_default_value=True, + default_value=1, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="eos_id", + full_name="sentencepiece.TrainerSpec.eos_id", + index=32, + number=42, + type=5, + cpp_type=1, + label=1, + has_default_value=True, + default_value=2, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="pad_id", + full_name="sentencepiece.TrainerSpec.pad_id", + index=33, + number=43, + type=5, + cpp_type=1, + label=1, + has_default_value=True, + default_value=-1, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="unk_piece", + full_name="sentencepiece.TrainerSpec.unk_piece", + index=34, + number=45, + type=9, + cpp_type=9, + label=1, + has_default_value=True, + default_value=b"".decode("utf-8"), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="bos_piece", + full_name="sentencepiece.TrainerSpec.bos_piece", + index=35, + number=46, + type=9, + cpp_type=9, + label=1, + has_default_value=True, + default_value=b"".decode("utf-8"), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="eos_piece", + full_name="sentencepiece.TrainerSpec.eos_piece", + index=36, + number=47, + type=9, + cpp_type=9, + label=1, + has_default_value=True, + default_value=b"".decode("utf-8"), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="pad_piece", + full_name="sentencepiece.TrainerSpec.pad_piece", + index=37, + number=48, + type=9, + cpp_type=9, + label=1, + has_default_value=True, + default_value=b"".decode("utf-8"), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="unk_surface", + full_name="sentencepiece.TrainerSpec.unk_surface", + index=38, + number=44, + type=9, + cpp_type=9, + label=1, + has_default_value=True, + default_value=b" \342\201\207 ".decode("utf-8"), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="train_extremely_large_corpus", + full_name="sentencepiece.TrainerSpec.train_extremely_large_corpus", + index=39, + number=49, + type=8, + cpp_type=7, + label=1, + has_default_value=True, + default_value=False, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + ], + extensions=[], + nested_types=[], + enum_types=[ + _TRAINERSPEC_MODELTYPE, + ], + serialized_options=None, + is_extendable=True, + syntax="proto2", + extension_ranges=[ + (200, 536870912), + ], + oneofs=[], + serialized_start=45, + serialized_end=1358, +) + + +_NORMALIZERSPEC = _descriptor.Descriptor( + name="NormalizerSpec", + full_name="sentencepiece.NormalizerSpec", + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name="name", + full_name="sentencepiece.NormalizerSpec.name", + index=0, + number=1, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=b"".decode("utf-8"), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="precompiled_charsmap", + full_name="sentencepiece.NormalizerSpec.precompiled_charsmap", + index=1, + number=2, + type=12, + cpp_type=9, + label=1, + has_default_value=False, + default_value=b"", + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="add_dummy_prefix", + full_name="sentencepiece.NormalizerSpec.add_dummy_prefix", + index=2, + number=3, + type=8, + cpp_type=7, + label=1, + has_default_value=True, + default_value=True, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="remove_extra_whitespaces", + full_name="sentencepiece.NormalizerSpec.remove_extra_whitespaces", + index=3, + number=4, + type=8, + cpp_type=7, + label=1, + has_default_value=True, + default_value=True, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="escape_whitespaces", + full_name="sentencepiece.NormalizerSpec.escape_whitespaces", + index=4, + number=5, + type=8, + cpp_type=7, + label=1, + has_default_value=True, + default_value=True, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="normalization_rule_tsv", + full_name="sentencepiece.NormalizerSpec.normalization_rule_tsv", + index=5, + number=6, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=b"".decode("utf-8"), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + ], + extensions=[], + nested_types=[], + enum_types=[], + serialized_options=None, + is_extendable=True, + syntax="proto2", + extension_ranges=[ + (200, 536870912), + ], + oneofs=[], + serialized_start=1361, + serialized_end=1570, +) + + +_SELFTESTDATA_SAMPLE = _descriptor.Descriptor( + name="Sample", + full_name="sentencepiece.SelfTestData.Sample", + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name="input", + full_name="sentencepiece.SelfTestData.Sample.input", + index=0, + number=1, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=b"".decode("utf-8"), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="expected", + full_name="sentencepiece.SelfTestData.Sample.expected", + index=1, + number=2, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=b"".decode("utf-8"), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + ], + extensions=[], + nested_types=[], + enum_types=[], + serialized_options=None, + is_extendable=False, + syntax="proto2", + extension_ranges=[], + oneofs=[], + serialized_start=1641, + serialized_end=1682, +) + +_SELFTESTDATA = _descriptor.Descriptor( + name="SelfTestData", + full_name="sentencepiece.SelfTestData", + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name="samples", + full_name="sentencepiece.SelfTestData.samples", + index=0, + number=1, + type=11, + cpp_type=10, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + ], + extensions=[], + nested_types=[ + _SELFTESTDATA_SAMPLE, + ], + enum_types=[], + serialized_options=None, + is_extendable=True, + syntax="proto2", + extension_ranges=[ + (200, 536870912), + ], + oneofs=[], + serialized_start=1572, + serialized_end=1693, +) + + +_MODELPROTO_SENTENCEPIECE = _descriptor.Descriptor( + name="SentencePiece", + full_name="sentencepiece.ModelProto.SentencePiece", + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name="piece", + full_name="sentencepiece.ModelProto.SentencePiece.piece", + index=0, + number=1, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=b"".decode("utf-8"), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="score", + full_name="sentencepiece.ModelProto.SentencePiece.score", + index=1, + number=2, + type=2, + cpp_type=6, + label=1, + has_default_value=False, + default_value=float(0), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="type", + full_name="sentencepiece.ModelProto.SentencePiece.type", + index=2, + number=3, + type=14, + cpp_type=8, + label=1, + has_default_value=True, + default_value=1, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + ], + extensions=[], + nested_types=[], + enum_types=[ + _MODELPROTO_SENTENCEPIECE_TYPE, + ], + serialized_options=None, + is_extendable=True, + syntax="proto2", + extension_ranges=[ + (200, 536870912), + ], + oneofs=[], + serialized_start=1985, + serialized_end=2195, +) + +_MODELPROTO = _descriptor.Descriptor( + name="ModelProto", + full_name="sentencepiece.ModelProto", + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name="pieces", + full_name="sentencepiece.ModelProto.pieces", + index=0, + number=1, + type=11, + cpp_type=10, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="trainer_spec", + full_name="sentencepiece.ModelProto.trainer_spec", + index=1, + number=2, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="normalizer_spec", + full_name="sentencepiece.ModelProto.normalizer_spec", + index=2, + number=3, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="self_test_data", + full_name="sentencepiece.ModelProto.self_test_data", + index=3, + number=4, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + _descriptor.FieldDescriptor( + name="denormalizer_spec", + full_name="sentencepiece.ModelProto.denormalizer_spec", + index=4, + number=5, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), + ], + extensions=[], + nested_types=[ + _MODELPROTO_SENTENCEPIECE, + ], + enum_types=[], + serialized_options=None, + is_extendable=True, + syntax="proto2", + extension_ranges=[ + (200, 536870912), + ], + oneofs=[], + serialized_start=1696, + serialized_end=2206, +) + +_TRAINERSPEC.fields_by_name["model_type"].enum_type = _TRAINERSPEC_MODELTYPE +_TRAINERSPEC_MODELTYPE.containing_type = _TRAINERSPEC +_SELFTESTDATA_SAMPLE.containing_type = _SELFTESTDATA +_SELFTESTDATA.fields_by_name["samples"].message_type = _SELFTESTDATA_SAMPLE +_MODELPROTO_SENTENCEPIECE.fields_by_name["type"].enum_type = _MODELPROTO_SENTENCEPIECE_TYPE +_MODELPROTO_SENTENCEPIECE.containing_type = _MODELPROTO +_MODELPROTO_SENTENCEPIECE_TYPE.containing_type = _MODELPROTO_SENTENCEPIECE +_MODELPROTO.fields_by_name["pieces"].message_type = _MODELPROTO_SENTENCEPIECE +_MODELPROTO.fields_by_name["trainer_spec"].message_type = _TRAINERSPEC +_MODELPROTO.fields_by_name["normalizer_spec"].message_type = _NORMALIZERSPEC +_MODELPROTO.fields_by_name["self_test_data"].message_type = _SELFTESTDATA +_MODELPROTO.fields_by_name["denormalizer_spec"].message_type = _NORMALIZERSPEC +DESCRIPTOR.message_types_by_name["TrainerSpec"] = _TRAINERSPEC +DESCRIPTOR.message_types_by_name["NormalizerSpec"] = _NORMALIZERSPEC +DESCRIPTOR.message_types_by_name["SelfTestData"] = _SELFTESTDATA +DESCRIPTOR.message_types_by_name["ModelProto"] = _MODELPROTO +_sym_db.RegisterFileDescriptor(DESCRIPTOR) + +TrainerSpec = _reflection.GeneratedProtocolMessageType( + "TrainerSpec", + (_message.Message,), + { + "DESCRIPTOR": _TRAINERSPEC, + "__module__": "sentencepiece_model_pb2", + # @@protoc_insertion_point(class_scope:sentencepiece.TrainerSpec) + }, +) +_sym_db.RegisterMessage(TrainerSpec) + +NormalizerSpec = _reflection.GeneratedProtocolMessageType( + "NormalizerSpec", + (_message.Message,), + { + "DESCRIPTOR": _NORMALIZERSPEC, + "__module__": "sentencepiece_model_pb2", + # @@protoc_insertion_point(class_scope:sentencepiece.NormalizerSpec) + }, +) +_sym_db.RegisterMessage(NormalizerSpec) + +SelfTestData = _reflection.GeneratedProtocolMessageType( + "SelfTestData", + (_message.Message,), + { + "Sample": _reflection.GeneratedProtocolMessageType( + "Sample", + (_message.Message,), + { + "DESCRIPTOR": _SELFTESTDATA_SAMPLE, + "__module__": "sentencepiece_model_pb2", + # @@protoc_insertion_point(class_scope:sentencepiece.SelfTestData.Sample) + }, + ), + "DESCRIPTOR": _SELFTESTDATA, + "__module__": "sentencepiece_model_pb2", + # @@protoc_insertion_point(class_scope:sentencepiece.SelfTestData) + }, +) +_sym_db.RegisterMessage(SelfTestData) +_sym_db.RegisterMessage(SelfTestData.Sample) + +ModelProto = _reflection.GeneratedProtocolMessageType( + "ModelProto", + (_message.Message,), + { + "SentencePiece": _reflection.GeneratedProtocolMessageType( + "SentencePiece", + (_message.Message,), + { + "DESCRIPTOR": _MODELPROTO_SENTENCEPIECE, + "__module__": "sentencepiece_model_pb2", + # @@protoc_insertion_point(class_scope:sentencepiece.ModelProto.SentencePiece) + }, + ), + "DESCRIPTOR": _MODELPROTO, + "__module__": "sentencepiece_model_pb2", + # @@protoc_insertion_point(class_scope:sentencepiece.ModelProto) + }, +) +_sym_db.RegisterMessage(ModelProto) +_sym_db.RegisterMessage(ModelProto.SentencePiece) + + +DESCRIPTOR._options = None +_TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None +_TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None +# @@protoc_insertion_point(module_scope) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/sentencepiece_model_pb2_new.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/sentencepiece_model_pb2_new.py new file mode 100644 index 0000000000000000000000000000000000000000..2ea4f4d64ce660b3d59d60c0650f5849e4fd2251 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/sentencepiece_model_pb2_new.py @@ -0,0 +1,47 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: sentencepiece_model.proto +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n\x19sentencepiece_model.proto\x12\rsentencepiece"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18 \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05\x12\x16\n\tbos_piece\x18. \x01(\t:\x03\x12\x17\n\teos_piece\x18/ \x01(\t:\x04\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "sentencepiece_model_pb2", _globals) +if _descriptor._USE_C_DESCRIPTORS is False: + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b"H\003" + # (generated by protobuf compiler, but `_TRAINERSPEC` is not defined) + # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None + # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._serialized_options = b"\030\001" + # _TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None + # _TRAINERSPEC.fields_by_name["training_sentence_size"]._serialized_options = b"\030\001" + _globals["_TRAINERSPEC"]._serialized_start = 45 + _globals["_TRAINERSPEC"]._serialized_end = 1581 + _globals["_TRAINERSPEC_MODELTYPE"]._serialized_start = 1517 + _globals["_TRAINERSPEC_MODELTYPE"]._serialized_end = 1570 + _globals["_NORMALIZERSPEC"]._serialized_start = 1584 + _globals["_NORMALIZERSPEC"]._serialized_end = 1793 + _globals["_SELFTESTDATA"]._serialized_start = 1795 + _globals["_SELFTESTDATA"]._serialized_end = 1916 + _globals["_SELFTESTDATA_SAMPLE"]._serialized_start = 1864 + _globals["_SELFTESTDATA_SAMPLE"]._serialized_end = 1905 + _globals["_MODELPROTO"]._serialized_start = 1919 + _globals["_MODELPROTO"]._serialized_end = 2429 + _globals["_MODELPROTO_SENTENCEPIECE"]._serialized_start = 2208 + _globals["_MODELPROTO_SENTENCEPIECE"]._serialized_end = 2418 + _globals["_MODELPROTO_SENTENCEPIECE_TYPE"]._serialized_start = 2323 + _globals["_MODELPROTO_SENTENCEPIECE_TYPE"]._serialized_end = 2407 +# @@protoc_insertion_point(module_scope) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/type_validators.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/type_validators.py new file mode 100644 index 0000000000000000000000000000000000000000..08d4697683b2eea80cda1f80e4a4a84ffbf694d0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/type_validators.py @@ -0,0 +1,252 @@ +from collections.abc import Callable, Sequence +from functools import partial +from typing import Any, Union, cast + +from huggingface_hub.dataclasses import as_validated_field + +from ..tokenization_utils_base import PaddingStrategy, TruncationStrategy +from ..video_utils import VideoMetadataType +from .generic import TensorType +from .import_utils import is_torch_available, is_vision_available + + +if is_vision_available(): + from ..image_utils import PILImageResampling + +if is_torch_available(): + import torch + + from ..activations import ACT2FN +else: + ACT2FN = {} + + +def positive_any_number(value: int | float | None = None): + if value is not None and (not isinstance(value, (int, float)) or not value >= 0): + raise ValueError(f"Value must be a positive integer or floating number, got {value}") + + +def positive_int(value: int | None = None): + if value is not None and (not isinstance(value, int) or not value >= 0): + raise ValueError(f"Value must be a positive integer, got {value}") + + +def padding_validator(value: bool | str | PaddingStrategy | None = None): + possible_names = ["longest", "max_length", "do_not_pad"] + if value is None: + pass + elif not isinstance(value, (bool, str, PaddingStrategy)): + raise ValueError("Value for padding must be either a boolean, a string or a `PaddingStrategy`") + elif isinstance(value, str) and value not in possible_names: + raise ValueError(f"If padding is a string, the value must be one of {possible_names}") + + +def truncation_validator(value: bool | str | TruncationStrategy | None = None): + possible_names = ["only_first", "only_second", "longest_first", "do_not_truncate"] + if value is None: + pass + elif not isinstance(value, (bool, str, TruncationStrategy)): + raise ValueError("Value for truncation must be either a boolean, a string or a `TruncationStrategy`") + elif isinstance(value, str) and value not in possible_names: + raise ValueError(f"If truncation is a string, value must be one of {possible_names}") + + +def image_size_validator(value: int | Sequence[int] | dict[str, int] | None = None): + possible_keys = ["height", "width", "longest_edge", "shortest_edge", "max_height", "max_width"] + if value is None: + pass + elif isinstance(value, dict) and any(k not in possible_keys for k in value.keys()): + raise ValueError(f"Value for size must be a dict with keys {possible_keys} but got size={value}") + + +def device_validator(value: str | int | None = None): + possible_names = ["cpu", "cuda", "xla", "xpu", "mps", "meta"] + if value is None: + pass + elif is_torch_available() and isinstance(value, torch.device): + # Convert torch.device to string for validation + device_str = str(value) + if device_str.split(":")[0] not in possible_names: + raise ValueError( + f"If device is a torch.device, the value must be one of {possible_names} but got device={value}" + ) + elif isinstance(value, int) and value < 0: + raise ValueError( + f"If device is an integer, the value must be a strictly positive integer but got device={value}" + ) + elif isinstance(value, str) and value.split(":")[0] not in possible_names: + raise ValueError(f"If device is an string, the value must be one of {possible_names} but got device={value}") + elif not isinstance(value, (int, str)): + raise ValueError( + f"Device must be either an integer device ID, a string (e.g., 'cpu', 'cuda:0'), or a torch.device object, but got device={value}" + ) + + +def resampling_validator(value: Union[int, "PILImageResampling"] | None = None): + if value is None: + pass + elif isinstance(value, int) and value not in list(range(6)): + raise ValueError( + f"The resampling should be one of {list(range(6))} when provided as integer, but got resampling={value}" + ) + elif is_vision_available() and not isinstance(value, (PILImageResampling, int)): + raise ValueError(f"The resampling should an integer or `PIL.Image.Resampling`, but got resampling={value}") + + +def video_metadata_validator(value: VideoMetadataType | None = None): + if value is None: + return + + valid_keys = ["total_num_frames", "fps", "width", "height", "duration", "video_backend", "frames_indices"] + + def check_dict_keys(d: dict[str, Any]) -> bool: + return all(key in valid_keys for key in d.keys()) + + if isinstance(value, Sequence) and isinstance(value[0], Sequence) and isinstance(value[0][0], dict): + for sublist in value: + for item in sublist: + if not check_dict_keys(item): + raise ValueError( + f"Invalid keys found in video metadata. Valid keys: {valid_keys} got: {list(item.keys())}" + ) + + elif isinstance(value, Sequence) and isinstance(value[0], dict): + for item in value: + if not check_dict_keys(item): + raise ValueError( + f"Invalid keys found in video metadata. Valid keys: {valid_keys} got: {list(cast(dict, item).keys())}" + ) + + elif isinstance(value, dict): + if not check_dict_keys(value): + raise ValueError( + f"Invalid keys found in video metadata. Valid keys: {valid_keys}, got: {list(value.keys())}" + ) + + +def tensor_type_validator(value: str | TensorType | None = None): + possible_names = ["pt", "np", "mlx"] + if value is None: + pass + elif not isinstance(value, str) or value not in possible_names: + raise ValueError(f"The tensor type should be one of {possible_names} but got tensor_type={value}") + + +@as_validated_field +def label_to_id_validation(value: str | TensorType | None = None): + possible_names = ["pt", "np", "mlx"] + if value is None: + pass + elif not isinstance(value, str) or value not in possible_names: + raise ValueError(f"The tensor type should be one of {possible_names} but got tensor_type={value}") + + +def interval( + min: int | float | None = None, + max: int | float | None = None, + exclude_min: bool = False, + exclude_max: bool = False, +) -> Callable: + """ + Parameterized validator that ensures that `value` is within the defined interval. Optionally, the interval can be + open on either side. Expected usage: `interval(min=0)(default=8)` + + Args: + min (`int` or `float`, *optional*): + Minimum value of the interval. + max (`int` or `float`, *optional*): + Maximum value of the interval. + exclude_min (`bool`, *optional*, defaults to `False`): + If True, the minimum value is excluded from the interval. + exclude_max (`bool`, *optional*, defaults to `False`): + If True, the maximum value is excluded from the interval. + """ + error_message = "Value must be" + if min is not None: + if exclude_min: + error_message += f" greater than {min}" + else: + error_message += f" greater or equal to {min}" + if min is not None and max is not None: + error_message += " and" + if max is not None: + if exclude_max: + error_message += f" smaller than {max}" + else: + error_message += f" smaller or equal to {max}" + error_message += ", got {value}." + + min = min or float("-inf") + max = max or float("inf") + + @as_validated_field + def _inner(value: int | float): + min_valid = min <= value if not exclude_min else min < value + max_valid = value <= max if not exclude_max else value < max + if not (min_valid and max_valid): + raise ValueError(error_message.format(value=value)) + + return _inner + + +@as_validated_field +def probability(value: float): + """Ensures that `value` is a valid probability number, i.e. [0,1].""" + if not 0 <= value <= 1: + raise ValueError(f"Value must be a probability between 0.0 and 1.0, got {value}.") + + +def is_divisible_by(divisor: int | float): + @as_validated_field + def _inner(value: int | float): + if value % divisor != 0: + raise ValueError(f"Value has to be divisble by {divisor} but got value={value}") + + return _inner + + +@as_validated_field +def activation_fn_key(value: str): + """Ensures that `value` is a string corresponding to an activation function.""" + # TODO (joao): in python 3.11+, we can build a Literal type from the keys of ACT2FN + if len(ACT2FN) > 0: # don't validate if we can't import ACT2FN + if value not in ACT2FN: + raise ValueError( + f"Value must be one of {list(ACT2FN.keys())}, got {value}. " + "Make sure to use a string that corresponds to an activation function." + ) + + +def tensor_shape(shape: tuple[int | str], length: int | None = None): + @as_validated_field + def validator(value: Union[Sequence["torch.Tensor"], "torch.Tensor"]): + if value is None: + return + elif not isinstance(value, (list, tuple)): + value = [value] + elif isinstance(length, int) and len(value) != length: + raise ValueError(f"Value has to be a list of length={length} but got {len(value)}") + + dimensions = {} + for tensor in value: + # Ensures that `value` is a floating point tensor in any device (cpu, cuda, xpu, ...). + # Using `torch.FloatTensor` as a type hint is discouraged if the dataclass has a `strict` + # decorator, because it enforces floating tensors only on CPU. + if not (isinstance(tensor, torch.Tensor) and tensor.is_floating_point()): + raise ValueError(f"Value has to be a floating point tensor but got value={tensor}") + + if len(tensor.shape) != len(shape): + raise ValueError(f"Expected shape {shape}, but got {tensor.shape}") + for dim, expected in zip(tensor.shape, shape): + if isinstance(expected, int) and dim != expected: + raise ValueError(f"Expected dimension {expected}, but got {dim}") + elif isinstance(expected, str): + if expected not in dimensions: + dimensions[expected] = dim + elif dimensions[expected] != dim: + raise ValueError( + f"Dimension '{expected}' takes different values: {dimensions[expected]} and {dim}." + " Please check your tensors shapes." + ) + + return partial(validator, metadata={"shape": shape, "length": length}) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/versions.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/versions.py new file mode 100644 index 0000000000000000000000000000000000000000..452f0d48a8e279c6e16fba74d9d565b59da1cfc5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/versions.py @@ -0,0 +1,116 @@ +# Copyright 2020 The HuggingFace Team. All rights reserved. +# +# 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. +""" +Utilities for working with package versions +""" + +import importlib.metadata +import operator +import re +import sys + +from packaging import version + + +ops = { + "<": operator.lt, + "<=": operator.le, + "==": operator.eq, + "!=": operator.ne, + ">=": operator.ge, + ">": operator.gt, +} + + +def _compare_versions(op, got_ver, want_ver, requirement, pkg, hint): + if got_ver is None or want_ver is None: + raise ValueError( + f"Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider" + f" reinstalling {pkg}." + ) + if not ops[op](version.parse(got_ver), version.parse(want_ver)): + raise ImportError( + f"{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}" + ) + + +def require_version(requirement: str, hint: str | None = None) -> None: + """ + Perform a runtime check of the dependency versions, using the exact same syntax used by pip. + + The installed module version comes from the *site-packages* dir via *importlib.metadata*. + + Args: + requirement (`str`): pip style definition, e.g., "tokenizers==0.9.4", "tqdm>=4.27", "numpy" + hint (`str`, *optional*): what suggestion to print in case of requirements not being met + + Example: + + ```python + require_version("pandas>1.1.2") + require_version("numpy>1.18.5", "this is important to have for whatever reason") + ```""" + + hint = f"\n{hint}" if hint is not None else "" + + # non-versioned check + if re.match(r"^[\w_\-\d]+$", requirement): + pkg, op, want_ver = requirement, None, None + else: + match = re.findall(r"^([^!=<>\s]+)([\s!=<>]{1,2}.+)", requirement) + if not match: + raise ValueError( + "requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but" + f" got {requirement}" + ) + pkg, want_full = match[0] + want_range = want_full.split(",") # there could be multiple requirements + wanted = {} + for w in want_range: + match = re.findall(r"^([\s!=<>]{1,2})(.+)", w) + if not match: + raise ValueError( + "requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23," + f" but got {requirement}" + ) + op, want_ver = match[0] + wanted[op] = want_ver + if op not in ops: + raise ValueError(f"{requirement}: need one of {list(ops.keys())}, but got {op}") + + # special case + if pkg == "python": + got_ver = ".".join([str(x) for x in sys.version_info[:3]]) + for op, want_ver in wanted.items(): + _compare_versions(op, got_ver, want_ver, requirement, pkg, hint) + return + + # check if any version is installed + try: + got_ver = importlib.metadata.version(pkg) + except importlib.metadata.PackageNotFoundError: + raise importlib.metadata.PackageNotFoundError( + f"The '{requirement}' distribution was not found and is required by this application. {hint}" + ) + + # check that the right version is installed if version number or a range was provided + if want_ver is not None: + for op, want_ver in wanted.items(): + _compare_versions(op, got_ver, want_ver, requirement, pkg, hint) + + +def require_version_core(requirement): + """require_version wrapper which emits a core-specific hint on failure""" + hint = "Try: `pip install transformers -U` or `pip install -e '.[dev]'` if you're working with git main" + return require_version(requirement, hint) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/typer-0.25.1.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer-0.25.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a7694736cf37716aafec14b24aa8d6316ebe07a3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer-0.25.1.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2019 Sebastián Ramírez + +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/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/.agents/skills/typer/SKILL.md b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/.agents/skills/typer/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..19b63c491f8b77605231fccb3b1f7a3ce7a7d882 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/.agents/skills/typer/SKILL.md @@ -0,0 +1,266 @@ +--- +name: typer +description: Typer best practices and conventions. Use when working with Typer CLIs. Keeps Typer code clean and up to date with the latest features and patterns, updated with new versions. Write new code or refactor and update old code. +--- + +# Typer + +Official Typer skill to write code with best practices, keeping up to date with new versions and features. + +## Installing typer + +In a virtual environment, `pip install typer` (with pip) or `uv pip install typer` (with uv). For your library/project, add `typer` to the dependencies in `pyproject.toml`. + +Do not install `typer-slim` or `typer-cli`, they are both deprecated and will now simply install `typer`. + +Typer supports Python 3.10 and above. + +## Use an explicit `Typer` app + +For maximum generalizability, create an explicit Typer app and register subcommand(s), instead of using `typer.run`: + +```python +import typer + +app = typer.Typer() + + +@app.command() +def hello(): + print(f"Hello World") + + +if __name__ == "__main__": + app() +``` + +instead of: + +```python +# DO NOT DO THIS: Not extensible. Use Typer() instead. +import typer + + +def main(): + print(f"Hello World") + + +if __name__ == "__main__": + typer.run(main) +``` + +## Execute the app + +To execute the app in the terminal, run + +```bash +python main.py +``` + +When multiple commands are registered to the Typer app, you have to add the command name: + +```bash +python main.py hello +``` + +To see the automatically generated help documentation, run + +```bash +python main.py --help +``` + +or set `no_args_is_help` to `True` when creating the `Typer()` add to automatically show the help when running a command without any arguments. + +## Use `Annotated` + +Always prefer the `Annotated` style for declarations of CLI arguments and options. + +It allows us to pass additional metadata that can be used by Typer. + +```python +from typing import Annotated + +import typer + +app = typer.Typer() + + +@app.command() +def hello(name: Annotated[str, typer.Argument()] = "World"): + # Note that name is an optional Argument, as a default is provided + print(f"Hello {name}") + + +if __name__ == "__main__": + app() +``` + +This program can be run as-is, or can provide a specific name: + +```bash +python main.py +python main.py Rick +``` + +An older way of setting a default value is this: +```python +# DO NOT DO THIS: old style. Use Annotated instead. + +@app.command() +def main(name: str = typer.Argument(default="World")): + # Note that name is an optional Argument, as a default is provided + print(f"Hello {name}") +``` + +Similarly, the old style could use ellipsis (...) to explicitely mark an argument as required. + +```python +# DO NOT DO THIS: old style. Use Annotated without a default value instead. + +@app.command() +def main(name: str = typer.Argument(default=...)): + # Note that name is now a required Argument + print(f"Hello {name}") +``` + +## CLI Options + +CLI options are declared in a similar fashion as arguments, but will be called on the CLI with a single dash (single letter) or 2 dashes (full name): + +```python +from typing import Annotated + +import typer + +app = typer.Typer() + + +@app.command() +def main(user_name: Annotated[str, typer.Option("--name", "-n")]): + # On the CLI, the required user name can be specified with -n or --name + print(f"Hello {user_name}") + + +if __name__ == "__main__": + app() +``` + +You can run this program as such: + +```bash +python main.py -n "Rick" +python main.py --name "Morty" +``` + +### CLI options with multiple values + +By declaring a CLI option as a list, it can receive multiple values: + +```python +from typing import Annotated + +import typer + +app = typer.Typer() + + +@app.command() +def main(user: Annotated[list[str] | None, typer.Option()] = None): + if not user: + print(f"No users provided!") + raise typer.Abort() + for u in user: + print(f"Processing user: {u}") + + +if __name__ == "__main__": + app() +``` + +This can be executed like so: + +```bash +python main.py --user Rick --user Morty --user Summer +``` + +## Rich + +By default, Rich can be used with its custom markup syntax to set colors and styles, e.g. + +```python +from rich import print + +print("[bold red]Alert![/bold red] [green]Portal gun[/green] shooting! :boom:") +``` + +Typer supports using Rich formatting in the docstrings and the help messages of CLI arguments and CLI options. + + +```python +from typing import Annotated + +import typer + +app = typer.Typer(rich_markup_mode="rich") + + +@app.command() +def create( + username: Annotated[ + str, typer.Argument(help="The username to be [green]created[/green]") + ], +): + """ + [bold green]Create[/bold green] a new [italic]shiny[/italic] user. :sparkles: + + This requires a [underline]username[/underline]. + """ + print(f"Creating user: {username}") + + +@app.command(help="[bold red]Delete[/bold red] a user with [italic]USERNAME[/italic].") +def delete( + username: Annotated[ + str, typer.Argument(help="The username to be [red]deleted[/red]") + ], +): + """ + Some internal utility function to delete. + """ + print(f"Deleting user: {username}") + + +if __name__ == "__main__": + app() +``` + +To disable Rich formatting, set `rich_markup_mode` to `None` when creating a `Typer()` app. By default (when no value is given), Rich formatting is enabled. + +### Rich markdown + +You can also set `rich_markup_mode` to `"markdown"` to use Markdown in the docstring: + +```python +from typing import Annotated + +import typer + +app = typer.Typer(rich_markup_mode="markdown") + +@app.command(help="**Delete** a user with *USERNAME*.") +def delete( + username: Annotated[str, typer.Argument(help="The username to be **deleted** :boom:")] +): + print(f"Deleting user: {username}") + +if __name__ == "__main__": + app() +``` + +## Click + +Originally, Typer was built on Click. However, going forward Typer will vendor Click. As such, Click extensions should not be used anymore. + +Other settings of `Option` and `Argument` that came from Click but shouldn't be used in Typer anymore, include: `expose_value`, `shell_complete`, `show_choices`, `errors`, `prompt_required`, `is_flag`, `flag_value` and `allow_from_autoenv`. + +Code bases using these should be refactored to use pure Typer functionality. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8cb69b902a8edb6500aed3960aa32e853ac1fed2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/__main__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/__main__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25a1b039e125807d6e64d92fc64025c7ac46f428 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/__main__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/_completion_classes.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/_completion_classes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48c45fa7c5c2c469309e8b19d623bfc1d3f31a3e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/_completion_classes.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/_completion_shared.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/_completion_shared.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c47e8acc603592e9a53f6b0262bec4d4c7777b24 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/_completion_shared.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/_types.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/_types.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cf50ab3432059c2123417fd70c2811fdd9052b1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/_types.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/_typing.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/_typing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf30fa0bce2bb1ad899723fd7a88a9762dc1a216 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/_typing.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/cli.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/cli.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..295fe953d59d890210381b16635415320f21241e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/cli.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/colors.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/colors.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48425e1c25f66bb55f3869261b09c05224a8618d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/colors.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/completion.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/completion.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed76ce2bf6b7c7631e5b9be9e5058d2380b6e4d0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/completion.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/core.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/core.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44061d755d7ff9072a3252d8ee1e84df7a29fd4f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/core.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/main.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/main.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c7135d601f3122ed4aae5fc5f7f3b6dff50c4c1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/main.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/models.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/models.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f05218f7a53655a6eda3e722b17fe6dc56a4c822 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/models.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/params.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/params.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56352d4cae3abcf7f30822e6595180327a4b8b5b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/params.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/rich_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/rich_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71ebb1b8ac3c6541652b79fa25216e81047de90b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/rich_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/testing.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/testing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b59ab9de49ec16ed9882de7ce948b1e2a66407d0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/testing.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22a1212b71be527a004ffd96c551f7cfe64159ad Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/typer/__pycache__/utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/typing_extensions-4.15.0.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/typing_extensions-4.15.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f26bcf4d2de6eb136e31006ca3ab447d5e488adf --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/typing_extensions-4.15.0.dist-info/licenses/LICENSE @@ -0,0 +1,279 @@ +A. HISTORY OF THE SOFTWARE +========================== + +Python was created in the early 1990s by Guido van Rossum at Stichting +Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands +as a successor of a language called ABC. Guido remains Python's +principal author, although it includes many contributions from others. + +In 1995, Guido continued his work on Python at the Corporation for +National Research Initiatives (CNRI, see https://www.cnri.reston.va.us) +in Reston, Virginia where he released several versions of the +software. + +In May 2000, Guido and the Python core development team moved to +BeOpen.com to form the BeOpen PythonLabs team. In October of the same +year, the PythonLabs team moved to Digital Creations, which became +Zope Corporation. In 2001, the Python Software Foundation (PSF, see +https://www.python.org/psf/) was formed, a non-profit organization +created specifically to own Python-related Intellectual Property. +Zope Corporation was a sponsoring member of the PSF. + +All Python releases are Open Source (see https://opensource.org for +the Open Source Definition). Historically, most, but not all, Python +releases have also been GPL-compatible; the table below summarizes +the various releases. + + Release Derived Year Owner GPL- + from compatible? (1) + + 0.9.0 thru 1.2 1991-1995 CWI yes + 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes + 1.6 1.5.2 2000 CNRI no + 2.0 1.6 2000 BeOpen.com no + 1.6.1 1.6 2001 CNRI yes (2) + 2.1 2.0+1.6.1 2001 PSF no + 2.0.1 2.0+1.6.1 2001 PSF yes + 2.1.1 2.1+2.0.1 2001 PSF yes + 2.1.2 2.1.1 2002 PSF yes + 2.1.3 2.1.2 2002 PSF yes + 2.2 and above 2.1.1 2001-now PSF yes + +Footnotes: + +(1) GPL-compatible doesn't mean that we're distributing Python under + the GPL. All Python licenses, unlike the GPL, let you distribute + a modified version without making your changes open source. The + GPL-compatible licenses make it possible to combine Python with + other software that is released under the GPL; the others don't. + +(2) According to Richard Stallman, 1.6.1 is not GPL-compatible, + because its license has a choice of law clause. According to + CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 + is "not incompatible" with the GPL. + +Thanks to the many outside volunteers who have worked under Guido's +direction to make these releases possible. + + +B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON +=============================================================== + +Python software and documentation are licensed under the +Python Software Foundation License Version 2. + +Starting with Python 3.8.6, examples, recipes, and other code in +the documentation are dual licensed under the PSF License Version 2 +and the Zero-Clause BSD license. + +Some software incorporated into Python is under different licenses. +The licenses are listed with code falling under that license. + + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative version +prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 +------------------------------------------- + +BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 + +1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an +office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the +Individual or Organization ("Licensee") accessing and otherwise using +this software in source or binary form and its associated +documentation ("the Software"). + +2. Subject to the terms and conditions of this BeOpen Python License +Agreement, BeOpen hereby grants Licensee a non-exclusive, +royalty-free, world-wide license to reproduce, analyze, test, perform +and/or display publicly, prepare derivative works, distribute, and +otherwise use the Software alone or in any derivative version, +provided, however, that the BeOpen Python License is retained in the +Software, alone or in any derivative version prepared by Licensee. + +3. BeOpen is making the Software available to Licensee on an "AS IS" +basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE +SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS +AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY +DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +5. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +6. This License Agreement shall be governed by and interpreted in all +respects by the law of the State of California, excluding conflict of +law provisions. Nothing in this License Agreement shall be deemed to +create any relationship of agency, partnership, or joint venture +between BeOpen and Licensee. This License Agreement does not grant +permission to use BeOpen trademarks or trade names in a trademark +sense to endorse or promote products or services of Licensee, or any +third party. As an exception, the "BeOpen Python" logos available at +http://www.pythonlabs.com/logos.html may be used according to the +permissions granted on that web page. + +7. By copying, installing or otherwise using the software, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 +--------------------------------------- + +1. This LICENSE AGREEMENT is between the Corporation for National +Research Initiatives, having an office at 1895 Preston White Drive, +Reston, VA 20191 ("CNRI"), and the Individual or Organization +("Licensee") accessing and otherwise using Python 1.6.1 software in +source or binary form and its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, CNRI +hereby grants Licensee a nonexclusive, royalty-free, world-wide +license to reproduce, analyze, test, perform and/or display publicly, +prepare derivative works, distribute, and otherwise use Python 1.6.1 +alone or in any derivative version, provided, however, that CNRI's +License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) +1995-2001 Corporation for National Research Initiatives; All Rights +Reserved" are retained in Python 1.6.1 alone or in any derivative +version prepared by Licensee. Alternately, in lieu of CNRI's License +Agreement, Licensee may substitute the following text (omitting the +quotes): "Python 1.6.1 is made available subject to the terms and +conditions in CNRI's License Agreement. This Agreement together with +Python 1.6.1 may be located on the internet using the following +unique, persistent identifier (known as a handle): 1895.22/1013. This +Agreement may also be obtained from a proxy server on the internet +using the following URL: http://hdl.handle.net/1895.22/1013". + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python 1.6.1 or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python 1.6.1. + +4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" +basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. This License Agreement shall be governed by the federal +intellectual property law of the United States, including without +limitation the federal copyright law, and, to the extent such +U.S. federal law does not apply, by the law of the Commonwealth of +Virginia, excluding Virginia's conflict of law provisions. +Notwithstanding the foregoing, with regard to derivative works based +on Python 1.6.1 that incorporate non-separable material that was +previously distributed under the GNU General Public License (GPL), the +law of the Commonwealth of Virginia shall govern this License +Agreement only as to issues arising under or with respect to +Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this +License Agreement shall be deemed to create any relationship of +agency, partnership, or joint venture between CNRI and Licensee. This +License Agreement does not grant permission to use CNRI trademarks or +trade name in a trademark sense to endorse or promote products or +services of Licensee, or any third party. + +8. By clicking on the "ACCEPT" button where indicated, or by copying, +installing or otherwise using Python 1.6.1, Licensee agrees to be +bound by the terms and conditions of this License Agreement. + + ACCEPT + + +CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 +-------------------------------------------------- + +Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, +The Netherlands. All rights reserved. + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that the name of Stichting Mathematisch +Centrum or CWI not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO +THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE +FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION +---------------------------------------------------------------------- + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/typing_inspection-0.4.2.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/typing_inspection-0.4.2.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e825ad51621c5e34d370ba64f13f6854d89456a6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/typing_inspection-0.4.2.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Pydantic Services Inc. 2025 to present + +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/micromamba_root/envs/pytorch_env/Lib/site-packages/typing_inspection/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/typing_inspection/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e873fc18733f444af3584ddc146554d335bf0d0f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/typing_inspection/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/typing_inspection/__pycache__/introspection.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/typing_inspection/__pycache__/introspection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8d64a93a64766efc66fa0b743b703f5372097ef Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/typing_inspection/__pycache__/introspection.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/typing_inspection/__pycache__/typing_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/typing_inspection/__pycache__/typing_objects.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7dda51c7624c5677f2816087018c84c28a7686cb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/typing_inspection/__pycache__/typing_objects.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3-2.7.0.dist-info/licenses/LICENSE.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3-2.7.0.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..e6183d0276b26c5b87aecccf8d0d5bcd7b1148d4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3-2.7.0.dist-info/licenses/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2008-2020 Andrey Petrov and contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f2b72321f6676856a959c19b06119badbb82570 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/_base_connection.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/_base_connection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8731c414d436a500fc41476fe23cc4b7e78fc1d2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/_base_connection.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/_collections.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/_collections.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ad52b1fa61962722431da5bdbcb419efe35f3e7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/_collections.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/_request_methods.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/_request_methods.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4bfdf8d52ebd78ead4b5e729d0ebcd60dbd7d4ac Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/_request_methods.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/_version.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/_version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07e943a3f21d0b4f4229d2d8faeef69cc1c76df5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/_version.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/connection.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/connection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b4d791a5d81308116a655b073b1f9ba83d35c18 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/connection.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/connectionpool.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/connectionpool.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89afa6c9ca4487ceb406bf2b2372bfa09d4cdf39 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/connectionpool.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/exceptions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/exceptions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..576c2df8fbd1d039d6574793b1d13f8ee9569bf8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/exceptions.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/fields.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/fields.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c69a7fc203159ac5cbdf7afac303991ca646103e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/fields.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/filepost.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/filepost.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e0626a72fa26dfc22a299aac0a5a50dd9c2a9ce Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/filepost.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/poolmanager.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/poolmanager.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b7a1a65b03d362fa2f9008a60cf3a48c24eccc3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/poolmanager.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/response.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/response.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7c51e1df49de2afb166b08a1757fb4566341ec8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/__pycache__/response.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..639c60f69d3a9104d9d1bb2c9c2ac2afc3e36e3b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/__pycache__/pyopenssl.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/__pycache__/pyopenssl.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41b098b7419866894d99911caf3ed0ace75cbb5e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/__pycache__/pyopenssl.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/__pycache__/socks.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/__pycache__/socks.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0676a819cf27af516334a1de0b5361ecefba68b6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/__pycache__/socks.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e5b62b25e932566f7ae7599c1cedec2b8f30d95b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/__init__.py @@ -0,0 +1,17 @@ +from __future__ import annotations + +import urllib3.connection + +from ...connectionpool import HTTPConnectionPool, HTTPSConnectionPool +from .connection import EmscriptenHTTPConnection, EmscriptenHTTPSConnection + + +def inject_into_urllib3() -> None: + # override connection classes to use emscripten specific classes + # n.b. mypy complains about the overriding of classes below + # if it isn't ignored + HTTPConnectionPool.ConnectionCls = EmscriptenHTTPConnection + HTTPSConnectionPool.ConnectionCls = EmscriptenHTTPSConnection + urllib3.connection.HTTPConnection = EmscriptenHTTPConnection # type: ignore[misc,assignment] + urllib3.connection.HTTPSConnection = EmscriptenHTTPSConnection # type: ignore[misc,assignment] + urllib3.connection.VerifiedHTTPSConnection = EmscriptenHTTPSConnection # type: ignore[assignment] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc77ddb8fdc9795d4e6d741f7c9e5a671d3a4550 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/connection.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/connection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fae1a9289d5b47f7468e77803139a10b055a530c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/connection.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/fetch.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/fetch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3299ef609ab91caa7cb30af3dab44a0154caf400 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/fetch.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/request.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/request.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32f861633d2303f12de2485c34fb222bd04eb642 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/request.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/response.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/response.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44180b86d6c49470b8af533518711c2e8ea9ed7c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/__pycache__/response.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/connection.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..63f79dd3be803db09671c909f79316c3f65d6916 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/connection.py @@ -0,0 +1,260 @@ +from __future__ import annotations + +import os +import typing + +# use http.client.HTTPException for consistency with non-emscripten +from http.client import HTTPException as HTTPException # noqa: F401 +from http.client import ResponseNotReady + +from ..._base_connection import _TYPE_BODY +from ...connection import HTTPConnection, ProxyConfig, port_by_scheme +from ...exceptions import TimeoutError +from ...response import BaseHTTPResponse +from ...util.connection import _TYPE_SOCKET_OPTIONS +from ...util.timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT +from ...util.url import Url +from .fetch import _RequestError, _TimeoutError, send_request, send_streaming_request +from .request import EmscriptenRequest +from .response import EmscriptenHttpResponseWrapper, EmscriptenResponse + +if typing.TYPE_CHECKING: + from ..._base_connection import BaseHTTPConnection, BaseHTTPSConnection + + +class EmscriptenHTTPConnection: + default_port: typing.ClassVar[int] = port_by_scheme["http"] + default_socket_options: typing.ClassVar[_TYPE_SOCKET_OPTIONS] + + timeout: None | (float) + + host: str + port: int + blocksize: int + source_address: tuple[str, int] | None + socket_options: _TYPE_SOCKET_OPTIONS | None + + proxy: Url | None + proxy_config: ProxyConfig | None + + is_verified: bool = False + proxy_is_verified: bool | None = None + + response_class: type[BaseHTTPResponse] = EmscriptenHttpResponseWrapper + _response: EmscriptenResponse | None + + def __init__( + self, + host: str, + port: int = 0, + *, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + blocksize: int = 8192, + socket_options: _TYPE_SOCKET_OPTIONS | None = None, + proxy: Url | None = None, + proxy_config: ProxyConfig | None = None, + ) -> None: + self.host = host + self.port = port + self.timeout = timeout if isinstance(timeout, float) else 0.0 + self.scheme = "http" + self._closed = True + self._response = None + # ignore these things because we don't + # have control over that stuff + self.proxy = None + self.proxy_config = None + self.blocksize = blocksize + self.source_address = None + self.socket_options = None + self.is_verified = False + + def set_tunnel( + self, + host: str, + port: int | None = 0, + headers: typing.Mapping[str, str] | None = None, + scheme: str = "http", + ) -> None: + pass + + def connect(self) -> None: + pass + + def request( + self, + method: str, + url: str, + body: _TYPE_BODY | None = None, + headers: typing.Mapping[str, str] | None = None, + # We know *at least* botocore is depending on the order of the + # first 3 parameters so to be safe we only mark the later ones + # as keyword-only to ensure we have space to extend. + *, + chunked: bool = False, + preload_content: bool = True, + decode_content: bool = True, + enforce_content_length: bool = True, + ) -> None: + self._closed = False + if url.startswith("/"): + if self.port is not None: + port = f":{self.port}" + else: + port = "" + # no scheme / host / port included, make a full url + url = f"{self.scheme}://{self.host}{port}{url}" + request = EmscriptenRequest( + url=url, + method=method, + timeout=self.timeout if self.timeout else 0, + decode_content=decode_content, + ) + request.set_body(body) + if headers: + for k, v in headers.items(): + request.set_header(k, v) + self._response = None + try: + if not preload_content: + self._response = send_streaming_request(request) + if self._response is None: + self._response = send_request(request) + except _TimeoutError as e: + raise TimeoutError(e.message) from e + except _RequestError as e: + raise HTTPException(e.message) from e + + def getresponse(self) -> BaseHTTPResponse: + if self._response is not None: + return EmscriptenHttpResponseWrapper( + internal_response=self._response, + url=self._response.request.url, + connection=self, + ) + else: + raise ResponseNotReady() + + def close(self) -> None: + self._closed = True + self._response = None + + @property + def is_closed(self) -> bool: + """Whether the connection either is brand new or has been previously closed. + If this property is True then both ``is_connected`` and ``has_connected_to_proxy`` + properties must be False. + """ + return self._closed + + @property + def is_connected(self) -> bool: + """Whether the connection is actively connected to any origin (proxy or target)""" + return True + + @property + def has_connected_to_proxy(self) -> bool: + """Whether the connection has successfully connected to its proxy. + This returns False if no proxy is in use. Used to determine whether + errors are coming from the proxy layer or from tunnelling to the target origin. + """ + return False + + +class EmscriptenHTTPSConnection(EmscriptenHTTPConnection): + default_port = port_by_scheme["https"] + # all this is basically ignored, as browser handles https + cert_reqs: int | str | None = None + ca_certs: str | None = None + ca_cert_dir: str | None = None + ca_cert_data: None | str | bytes = None + cert_file: str | None + key_file: str | None + key_password: str | None + ssl_context: typing.Any | None + ssl_version: int | str | None = None + ssl_minimum_version: int | None = None + ssl_maximum_version: int | None = None + assert_hostname: None | str | typing.Literal[False] + assert_fingerprint: str | None = None + + def __init__( + self, + host: str, + port: int = 0, + *, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + blocksize: int = 16384, + socket_options: ( + None | _TYPE_SOCKET_OPTIONS + ) = HTTPConnection.default_socket_options, + proxy: Url | None = None, + proxy_config: ProxyConfig | None = None, + cert_reqs: int | str | None = None, + assert_hostname: None | str | typing.Literal[False] = None, + assert_fingerprint: str | None = None, + server_hostname: str | None = None, + ssl_context: typing.Any | None = None, + ca_certs: str | None = None, + ca_cert_dir: str | None = None, + ca_cert_data: None | str | bytes = None, + ssl_minimum_version: int | None = None, + ssl_maximum_version: int | None = None, + ssl_version: int | str | None = None, # Deprecated + cert_file: str | None = None, + key_file: str | None = None, + key_password: str | None = None, + ) -> None: + super().__init__( + host, + port=port, + timeout=timeout, + source_address=source_address, + blocksize=blocksize, + socket_options=socket_options, + proxy=proxy, + proxy_config=proxy_config, + ) + self.scheme = "https" + + self.key_file = key_file + self.cert_file = cert_file + self.key_password = key_password + self.ssl_context = ssl_context + self.server_hostname = server_hostname + self.assert_hostname = assert_hostname + self.assert_fingerprint = assert_fingerprint + self.ssl_version = ssl_version + self.ssl_minimum_version = ssl_minimum_version + self.ssl_maximum_version = ssl_maximum_version + self.ca_certs = ca_certs and os.path.expanduser(ca_certs) + self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir) + self.ca_cert_data = ca_cert_data + + self.cert_reqs = None + + # The browser will automatically verify all requests. + # We have no control over that setting. + self.is_verified = True + + def set_cert( + self, + key_file: str | None = None, + cert_file: str | None = None, + cert_reqs: int | str | None = None, + key_password: str | None = None, + ca_certs: str | None = None, + assert_hostname: None | str | typing.Literal[False] = None, + assert_fingerprint: str | None = None, + ca_cert_dir: str | None = None, + ca_cert_data: None | str | bytes = None, + ) -> None: + pass + + +# verify that this class implements BaseHTTP(s) connection correctly +if typing.TYPE_CHECKING: + _supports_http_protocol: BaseHTTPConnection = EmscriptenHTTPConnection("", 0) + _supports_https_protocol: BaseHTTPSConnection = EmscriptenHTTPSConnection("", 0) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/emscripten_fetch_worker.js b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/emscripten_fetch_worker.js new file mode 100644 index 0000000000000000000000000000000000000000..faf141e1fa4113a0c14480d1681ddecb9678ced4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/emscripten_fetch_worker.js @@ -0,0 +1,110 @@ +let Status = { + SUCCESS_HEADER: -1, + SUCCESS_EOF: -2, + ERROR_TIMEOUT: -3, + ERROR_EXCEPTION: -4, +}; + +let connections = new Map(); +let nextConnectionID = 1; +const encoder = new TextEncoder(); + +self.addEventListener("message", async function (event) { + if (event.data.close) { + let connectionID = event.data.close; + connections.delete(connectionID); + return; + } else if (event.data.getMore) { + let connectionID = event.data.getMore; + let { curOffset, value, reader, intBuffer, byteBuffer } = + connections.get(connectionID); + // if we still have some in buffer, then just send it back straight away + if (!value || curOffset >= value.length) { + // read another buffer if required + try { + let readResponse = await reader.read(); + + if (readResponse.done) { + // read everything - clear connection and return + connections.delete(connectionID); + Atomics.store(intBuffer, 0, Status.SUCCESS_EOF); + Atomics.notify(intBuffer, 0); + // finished reading successfully + // return from event handler + return; + } + curOffset = 0; + connections.get(connectionID).value = readResponse.value; + value = readResponse.value; + } catch (error) { + console.log("Request exception:", error); + let errorBytes = encoder.encode(error.message); + let written = errorBytes.length; + byteBuffer.set(errorBytes); + intBuffer[1] = written; + Atomics.store(intBuffer, 0, Status.ERROR_EXCEPTION); + Atomics.notify(intBuffer, 0); + } + } + + // send as much buffer as we can + let curLen = value.length - curOffset; + if (curLen > byteBuffer.length) { + curLen = byteBuffer.length; + } + byteBuffer.set(value.subarray(curOffset, curOffset + curLen), 0); + + Atomics.store(intBuffer, 0, curLen); // store current length in bytes + Atomics.notify(intBuffer, 0); + curOffset += curLen; + connections.get(connectionID).curOffset = curOffset; + + return; + } else { + // start fetch + let connectionID = nextConnectionID; + nextConnectionID += 1; + const intBuffer = new Int32Array(event.data.buffer); + const byteBuffer = new Uint8Array(event.data.buffer, 8); + try { + const response = await fetch(event.data.url, event.data.fetchParams); + // return the headers first via textencoder + var headers = []; + for (const pair of response.headers.entries()) { + headers.push([pair[0], pair[1]]); + } + let headerObj = { + headers: headers, + status: response.status, + connectionID, + }; + const headerText = JSON.stringify(headerObj); + let headerBytes = encoder.encode(headerText); + let written = headerBytes.length; + byteBuffer.set(headerBytes); + intBuffer[1] = written; + // make a connection + connections.set(connectionID, { + reader: response.body.getReader(), + intBuffer: intBuffer, + byteBuffer: byteBuffer, + value: undefined, + curOffset: 0, + }); + // set header ready + Atomics.store(intBuffer, 0, Status.SUCCESS_HEADER); + Atomics.notify(intBuffer, 0); + // all fetching after this goes through a new postmessage call with getMore + // this allows for parallel requests + } catch (error) { + console.log("Request exception:", error); + let errorBytes = encoder.encode(error.message); + let written = errorBytes.length; + byteBuffer.set(errorBytes); + intBuffer[1] = written; + Atomics.store(intBuffer, 0, Status.ERROR_EXCEPTION); + Atomics.notify(intBuffer, 0); + } + } +}); +self.postMessage({ inited: true }); diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/fetch.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/fetch.py new file mode 100644 index 0000000000000000000000000000000000000000..612cfddc4c28d2f0edf47522278fa6d9b7906623 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/fetch.py @@ -0,0 +1,726 @@ +""" +Support for streaming http requests in emscripten. + +A few caveats - + +If your browser (or Node.js) has WebAssembly JavaScript Promise Integration enabled +https://github.com/WebAssembly/js-promise-integration/blob/main/proposals/js-promise-integration/Overview.md +*and* you launch pyodide using `pyodide.runPythonAsync`, this will fetch data using the +JavaScript asynchronous fetch api (wrapped via `pyodide.ffi.call_sync`). In this case +timeouts and streaming should just work. + +Otherwise, it uses a combination of XMLHttpRequest and a web-worker for streaming. + +This approach has several caveats: + +Firstly, you can't do streaming http in the main UI thread, because atomics.wait isn't allowed. +Streaming only works if you're running pyodide in a web worker. + +Secondly, this uses an extra web worker and SharedArrayBuffer to do the asynchronous fetch +operation, so it requires that you have crossOriginIsolation enabled, by serving over https +(or from localhost) with the two headers below set: + + Cross-Origin-Opener-Policy: same-origin + Cross-Origin-Embedder-Policy: require-corp + +You can tell if cross origin isolation is successfully enabled by looking at the global crossOriginIsolated variable in +JavaScript console. If it isn't, streaming requests will fallback to XMLHttpRequest, i.e. getting the whole +request into a buffer and then returning it. it shows a warning in the JavaScript console in this case. + +Finally, the webworker which does the streaming fetch is created on initial import, but will only be started once +control is returned to javascript. Call `await wait_for_streaming_ready()` to wait for streaming fetch. + +NB: in this code, there are a lot of JavaScript objects. They are named js_* +to make it clear what type of object they are. +""" + +from __future__ import annotations + +import io +import json +from email.parser import Parser +from importlib.resources import files +from typing import TYPE_CHECKING, Any + +import js # type: ignore[import-not-found] +from pyodide.ffi import ( # type: ignore[import-not-found] + JsArray, + JsException, + JsProxy, + to_js, +) + +if TYPE_CHECKING: + from typing_extensions import Buffer + +from .request import EmscriptenRequest +from .response import EmscriptenResponse + +""" +There are some headers that trigger unintended CORS preflight requests. +See also https://github.com/koenvo/pyodide-http/issues/22 +""" +HEADERS_TO_IGNORE = ("user-agent",) + +SUCCESS_HEADER = -1 +SUCCESS_EOF = -2 +ERROR_TIMEOUT = -3 +ERROR_EXCEPTION = -4 + + +class _RequestError(Exception): + def __init__( + self, + message: str | None = None, + *, + request: EmscriptenRequest | None = None, + response: EmscriptenResponse | None = None, + ): + self.request = request + self.response = response + self.message = message + super().__init__(self.message) + + +class _StreamingError(_RequestError): + pass + + +class _TimeoutError(_RequestError): + pass + + +def _obj_from_dict(dict_val: dict[str, Any]) -> JsProxy: + return to_js(dict_val, dict_converter=js.Object.fromEntries) + + +class _ReadStream(io.RawIOBase): + def __init__( + self, + int_buffer: JsArray, + byte_buffer: JsArray, + timeout: float, + worker: JsProxy, + connection_id: int, + request: EmscriptenRequest, + ): + self.int_buffer = int_buffer + self.byte_buffer = byte_buffer + self.read_pos = 0 + self.read_len = 0 + self.connection_id = connection_id + self.worker = worker + self.timeout = int(1000 * timeout) if timeout > 0 else None + self.is_live = True + self._is_closed = False + self.request: EmscriptenRequest | None = request + + def __del__(self) -> None: + self.close() + + # this is compatible with _base_connection + def is_closed(self) -> bool: + return self._is_closed + + # for compatibility with RawIOBase + @property + def closed(self) -> bool: + return self.is_closed() + + def close(self) -> None: + if self.is_closed(): + return + self.read_len = 0 + self.read_pos = 0 + self.int_buffer = None + self.byte_buffer = None + self._is_closed = True + self.request = None + if self.is_live: + self.worker.postMessage(_obj_from_dict({"close": self.connection_id})) + self.is_live = False + super().close() + + def readable(self) -> bool: + return True + + def writable(self) -> bool: + return False + + def seekable(self) -> bool: + return False + + def readinto(self, byte_obj: Buffer) -> int: + if not self.int_buffer: + raise _StreamingError( + "No buffer for stream in _ReadStream.readinto", + request=self.request, + response=None, + ) + if self.read_len == 0: + # wait for the worker to send something + js.Atomics.store(self.int_buffer, 0, ERROR_TIMEOUT) + self.worker.postMessage(_obj_from_dict({"getMore": self.connection_id})) + if ( + js.Atomics.wait(self.int_buffer, 0, ERROR_TIMEOUT, self.timeout) + == "timed-out" + ): + raise _TimeoutError + data_len = self.int_buffer[0] + if data_len > 0: + self.read_len = data_len + self.read_pos = 0 + elif data_len == ERROR_EXCEPTION: + string_len = self.int_buffer[1] + # decode the error string + js_decoder = js.TextDecoder.new() + json_str = js_decoder.decode(self.byte_buffer.slice(0, string_len)) + raise _StreamingError( + f"Exception thrown in fetch: {json_str}", + request=self.request, + response=None, + ) + else: + # EOF, free the buffers and return zero + # and free the request + self.is_live = False + self.close() + return 0 + # copy from int32array to python bytes + ret_length = min(self.read_len, len(memoryview(byte_obj))) + subarray = self.byte_buffer.subarray( + self.read_pos, self.read_pos + ret_length + ).to_py() + memoryview(byte_obj)[0:ret_length] = subarray + self.read_len -= ret_length + self.read_pos += ret_length + return ret_length + + +class _StreamingFetcher: + def __init__(self) -> None: + # make web-worker and data buffer on startup + self.streaming_ready = False + streaming_worker_code = ( + files(__package__) + .joinpath("emscripten_fetch_worker.js") + .read_text(encoding="utf-8") + ) + js_data_blob = js.Blob.new( + to_js([streaming_worker_code], create_pyproxies=False), + _obj_from_dict({"type": "application/javascript"}), + ) + + def promise_resolver(js_resolve_fn: JsProxy, js_reject_fn: JsProxy) -> None: + def onMsg(e: JsProxy) -> None: + self.streaming_ready = True + js_resolve_fn(e) + + def onErr(e: JsProxy) -> None: + js_reject_fn(e) # Defensive: never happens in ci + + self.js_worker.onmessage = onMsg + self.js_worker.onerror = onErr + + js_data_url = js.URL.createObjectURL(js_data_blob) + self.js_worker = js.globalThis.Worker.new(js_data_url) + self.js_worker_ready_promise = js.globalThis.Promise.new(promise_resolver) + + def send(self, request: EmscriptenRequest) -> EmscriptenResponse: + headers = { + k: v for k, v in request.headers.items() if k not in HEADERS_TO_IGNORE + } + + body = request.body + fetch_data = {"headers": headers, "body": to_js(body), "method": request.method} + # start the request off in the worker + timeout = int(1000 * request.timeout) if request.timeout > 0 else None + js_shared_buffer = js.SharedArrayBuffer.new(1048576) + js_int_buffer = js.Int32Array.new(js_shared_buffer) + js_byte_buffer = js.Uint8Array.new(js_shared_buffer, 8) + + js.Atomics.store(js_int_buffer, 0, ERROR_TIMEOUT) + js.Atomics.notify(js_int_buffer, 0) + js_absolute_url = js.URL.new(request.url, js.location).href + self.js_worker.postMessage( + _obj_from_dict( + { + "buffer": js_shared_buffer, + "url": js_absolute_url, + "fetchParams": fetch_data, + } + ) + ) + # wait for the worker to send something + js.Atomics.wait(js_int_buffer, 0, ERROR_TIMEOUT, timeout) + if js_int_buffer[0] == ERROR_TIMEOUT: + raise _TimeoutError( + "Timeout connecting to streaming request", + request=request, + response=None, + ) + elif js_int_buffer[0] == SUCCESS_HEADER: + # got response + # header length is in second int of intBuffer + string_len = js_int_buffer[1] + # decode the rest to a JSON string + js_decoder = js.TextDecoder.new() + # this does a copy (the slice) because decode can't work on shared array + # for some silly reason + json_str = js_decoder.decode(js_byte_buffer.slice(0, string_len)) + # get it as an object + response_obj = json.loads(json_str) + return EmscriptenResponse( + request=request, + status_code=response_obj["status"], + headers=response_obj["headers"], + body=_ReadStream( + js_int_buffer, + js_byte_buffer, + request.timeout, + self.js_worker, + response_obj["connectionID"], + request, + ), + ) + elif js_int_buffer[0] == ERROR_EXCEPTION: + string_len = js_int_buffer[1] + # decode the error string + js_decoder = js.TextDecoder.new() + json_str = js_decoder.decode(js_byte_buffer.slice(0, string_len)) + raise _StreamingError( + f"Exception thrown in fetch: {json_str}", request=request, response=None + ) + else: + raise _StreamingError( + f"Unknown status from worker in fetch: {js_int_buffer[0]}", + request=request, + response=None, + ) + + +class _JSPIReadStream(io.RawIOBase): + """ + A read stream that uses pyodide.ffi.run_sync to read from a JavaScript fetch + response. This requires support for WebAssembly JavaScript Promise Integration + in the containing browser, and for pyodide to be launched via runPythonAsync. + + :param js_read_stream: + The JavaScript stream reader + + :param timeout: + Timeout in seconds + + :param request: + The request we're handling + + :param response: + The response this stream relates to + + :param js_abort_controller: + A JavaScript AbortController object, used for timeouts + """ + + def __init__( + self, + js_read_stream: Any, + timeout: float, + request: EmscriptenRequest, + response: EmscriptenResponse, + js_abort_controller: Any, # JavaScript AbortController for timeouts + ): + self.js_read_stream = js_read_stream + self.timeout = timeout + self._is_closed = False + self._is_done = False + self.request: EmscriptenRequest | None = request + self.response: EmscriptenResponse | None = response + self.current_buffer = None + self.current_buffer_pos = 0 + self.js_abort_controller = js_abort_controller + + def __del__(self) -> None: + self.close() + + # this is compatible with _base_connection + def is_closed(self) -> bool: + return self._is_closed + + # for compatibility with RawIOBase + @property + def closed(self) -> bool: + return self.is_closed() + + def close(self) -> None: + if self.is_closed(): + return + self.read_len = 0 + self.read_pos = 0 + self.js_read_stream.cancel() + self.js_read_stream = None + self._is_closed = True + self._is_done = True + self.request = None + self.response = None + super().close() + + def readable(self) -> bool: + return True + + def writable(self) -> bool: + return False + + def seekable(self) -> bool: + return False + + def _get_next_buffer(self) -> bool: + result_js = _run_sync_with_timeout( + self.js_read_stream.read(), + self.timeout, + self.js_abort_controller, + request=self.request, + response=self.response, + ) + if result_js.done: + self._is_done = True + return False + else: + self.current_buffer = result_js.value.to_py() + self.current_buffer_pos = 0 + return True + + def readinto(self, byte_obj: Buffer) -> int: + if self.current_buffer is None: + if not self._get_next_buffer() or self.current_buffer is None: + self.close() + return 0 + ret_length = min( + len(byte_obj), len(self.current_buffer) - self.current_buffer_pos + ) + byte_obj[0:ret_length] = self.current_buffer[ + self.current_buffer_pos : self.current_buffer_pos + ret_length + ] + self.current_buffer_pos += ret_length + if self.current_buffer_pos == len(self.current_buffer): + self.current_buffer = None + return ret_length + + +# check if we are in a worker or not +def is_in_browser_main_thread() -> bool: + return hasattr(js, "window") and hasattr(js, "self") and js.self == js.window + + +def is_cross_origin_isolated() -> bool: + return hasattr(js, "crossOriginIsolated") and js.crossOriginIsolated + + +def is_in_node() -> bool: + return ( + hasattr(js, "process") + and hasattr(js.process, "release") + and hasattr(js.process.release, "name") + and js.process.release.name == "node" + ) + + +def is_worker_available() -> bool: + return hasattr(js, "Worker") and hasattr(js, "Blob") + + +_fetcher: _StreamingFetcher | None = None + +if is_worker_available() and ( + (is_cross_origin_isolated() and not is_in_browser_main_thread()) + and (not is_in_node()) +): + _fetcher = _StreamingFetcher() +else: + _fetcher = None + + +NODE_JSPI_ERROR = ( + "urllib3 only works in Node.js with pyodide.runPythonAsync" + " and requires the flag --experimental-wasm-stack-switching in " + " versions of node <24." +) + + +def send_streaming_request(request: EmscriptenRequest) -> EmscriptenResponse | None: + if has_jspi(): + return send_jspi_request(request, True) + elif is_in_node(): + raise _RequestError( + message=NODE_JSPI_ERROR, + request=request, + response=None, + ) + + if _fetcher and streaming_ready(): + return _fetcher.send(request) + else: + _show_streaming_warning() + return None + + +_SHOWN_TIMEOUT_WARNING = False + + +def _show_timeout_warning() -> None: + global _SHOWN_TIMEOUT_WARNING + if not _SHOWN_TIMEOUT_WARNING: + _SHOWN_TIMEOUT_WARNING = True + message = "Warning: Timeout is not available on main browser thread" + js.console.warn(message) + + +_SHOWN_STREAMING_WARNING = False + + +def _show_streaming_warning() -> None: + global _SHOWN_STREAMING_WARNING + if not _SHOWN_STREAMING_WARNING: + _SHOWN_STREAMING_WARNING = True + message = "Can't stream HTTP requests because: \n" + if not is_cross_origin_isolated(): + message += " Page is not cross-origin isolated\n" + if is_in_browser_main_thread(): + message += " Python is running in main browser thread\n" + if not is_worker_available(): + message += " Worker or Blob classes are not available in this environment." # Defensive: this is always False in browsers that we test in + if streaming_ready() is False: + message += """ Streaming fetch worker isn't ready. If you want to be sure that streaming fetch +is working, you need to call: 'await urllib3.contrib.emscripten.fetch.wait_for_streaming_ready()`""" + from js import console + + console.warn(message) + + +def send_request(request: EmscriptenRequest) -> EmscriptenResponse: + if has_jspi(): + return send_jspi_request(request, False) + elif is_in_node(): + raise _RequestError( + message=NODE_JSPI_ERROR, + request=request, + response=None, + ) + try: + js_xhr = js.XMLHttpRequest.new() + + if not is_in_browser_main_thread(): + js_xhr.responseType = "arraybuffer" + if request.timeout: + js_xhr.timeout = int(request.timeout * 1000) + else: + js_xhr.overrideMimeType("text/plain; charset=ISO-8859-15") + if request.timeout: + # timeout isn't available on the main thread - show a warning in console + # if it is set + _show_timeout_warning() + + js_xhr.open(request.method, request.url, False) + for name, value in request.headers.items(): + if name.lower() not in HEADERS_TO_IGNORE: + js_xhr.setRequestHeader(name, value) + + js_xhr.send(to_js(request.body)) + + headers = dict(Parser().parsestr(js_xhr.getAllResponseHeaders())) + + if not is_in_browser_main_thread(): + body = js_xhr.response.to_py().tobytes() + else: + body = js_xhr.response.encode("ISO-8859-15") + return EmscriptenResponse( + status_code=js_xhr.status, headers=headers, body=body, request=request + ) + except JsException as err: + if err.name == "TimeoutError": + raise _TimeoutError(err.message, request=request) + elif err.name == "NetworkError": + raise _RequestError(err.message, request=request) + else: + # general http error + raise _RequestError(err.message, request=request) + + +def send_jspi_request( + request: EmscriptenRequest, streaming: bool +) -> EmscriptenResponse: + """ + Send a request using WebAssembly JavaScript Promise Integration + to wrap the asynchronous JavaScript fetch api (experimental). + + :param request: + Request to send + + :param streaming: + Whether to stream the response + + :return: The response object + :rtype: EmscriptenResponse + """ + timeout = request.timeout + js_abort_controller = js.AbortController.new() + headers = {k: v for k, v in request.headers.items() if k not in HEADERS_TO_IGNORE} + req_body = request.body + fetch_data = { + "headers": headers, + "body": to_js(req_body), + "method": request.method, + "signal": js_abort_controller.signal, + } + # Node.js returns the whole response (unlike opaqueredirect in browsers), + # so urllib3 can set `redirect: manual` to control redirects itself. + # https://stackoverflow.com/a/78524615 + if _is_node_js(): + fetch_data["redirect"] = "manual" + # Call JavaScript fetch (async api, returns a promise) + fetcher_promise_js = js.fetch(request.url, _obj_from_dict(fetch_data)) + # Now suspend WebAssembly until we resolve that promise + # or time out. + response_js = _run_sync_with_timeout( + fetcher_promise_js, + timeout, + js_abort_controller, + request=request, + response=None, + ) + headers = {} + header_iter = response_js.headers.entries() + while True: + iter_value_js = header_iter.next() + if getattr(iter_value_js, "done", False): + break + else: + headers[str(iter_value_js.value[0])] = str(iter_value_js.value[1]) + status_code = response_js.status + body: bytes | io.RawIOBase = b"" + + response = EmscriptenResponse( + status_code=status_code, headers=headers, body=b"", request=request + ) + if streaming: + # get via inputstream + if response_js.body is not None: + # get a reader from the fetch response + body_stream_js = response_js.body.getReader() + body = _JSPIReadStream( + body_stream_js, timeout, request, response, js_abort_controller + ) + else: + # get directly via arraybuffer + # n.b. this is another async JavaScript call. + body = _run_sync_with_timeout( + response_js.arrayBuffer(), + timeout, + js_abort_controller, + request=request, + response=response, + ).to_py() + response.body = body + return response + + +def _run_sync_with_timeout( + promise: Any, + timeout: float, + js_abort_controller: Any, + request: EmscriptenRequest | None, + response: EmscriptenResponse | None, +) -> Any: + """ + Await a JavaScript promise synchronously with a timeout which is implemented + via the AbortController + + :param promise: + Javascript promise to await + + :param timeout: + Timeout in seconds + + :param js_abort_controller: + A JavaScript AbortController object, used on timeout + + :param request: + The request being handled + + :param response: + The response being handled (if it exists yet) + + :raises _TimeoutError: If the request times out + :raises _RequestError: If the request raises a JavaScript exception + + :return: The result of awaiting the promise. + """ + timer_id = None + if timeout > 0: + timer_id = js.setTimeout( + js_abort_controller.abort.bind(js_abort_controller), int(timeout * 1000) + ) + try: + from pyodide.ffi import run_sync + + # run_sync here uses WebAssembly JavaScript Promise Integration to + # suspend python until the JavaScript promise resolves. + return run_sync(promise) + except JsException as err: + if err.name == "AbortError": + raise _TimeoutError( + message="Request timed out", request=request, response=response + ) + else: + raise _RequestError(message=err.message, request=request, response=response) + finally: + if timer_id is not None: + js.clearTimeout(timer_id) + + +def has_jspi() -> bool: + """ + Return true if jspi can be used. + + This requires both browser support and also WebAssembly + to be in the correct state - i.e. that the javascript + call into python was async not sync. + + :return: True if jspi can be used. + :rtype: bool + """ + try: + from pyodide.ffi import can_run_sync, run_sync # noqa: F401 + + return bool(can_run_sync()) + except ImportError: + return False + + +def _is_node_js() -> bool: + """ + Check if we are in Node.js. + + :return: True if we are in Node.js. + :rtype: bool + """ + return ( + hasattr(js, "process") + and hasattr(js.process, "release") + # According to the Node.js documentation, the release name is always "node". + and js.process.release.name == "node" + ) + + +def streaming_ready() -> bool | None: + if _fetcher: + return _fetcher.streaming_ready + else: + return None # no fetcher, return None to signify that + + +async def wait_for_streaming_ready() -> bool: + if _fetcher: + await _fetcher.js_worker_ready_promise + return True + else: + return False diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/request.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/request.py new file mode 100644 index 0000000000000000000000000000000000000000..e692e692bd0d38f6a0677992a6993fc68050dff3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/request.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +from dataclasses import dataclass, field + +from ..._base_connection import _TYPE_BODY + + +@dataclass +class EmscriptenRequest: + method: str + url: str + params: dict[str, str] | None = None + body: _TYPE_BODY | None = None + headers: dict[str, str] = field(default_factory=dict) + timeout: float = 0 + decode_content: bool = True + + def set_header(self, name: str, value: str) -> None: + self.headers[name.capitalize()] = value + + def set_body(self, body: _TYPE_BODY | None) -> None: + self.body = body diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/response.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/response.py new file mode 100644 index 0000000000000000000000000000000000000000..ec1e1dbe83722c5fb16290a852859252ae616826 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/emscripten/response.py @@ -0,0 +1,281 @@ +from __future__ import annotations + +import json as _json +import logging +import typing +from contextlib import contextmanager +from dataclasses import dataclass +from http.client import HTTPException as HTTPException +from io import BytesIO, IOBase + +from ...exceptions import InvalidHeader, TimeoutError +from ...response import BaseHTTPResponse +from ...util.retry import Retry +from .request import EmscriptenRequest + +if typing.TYPE_CHECKING: + from ..._base_connection import BaseHTTPConnection, BaseHTTPSConnection + +log = logging.getLogger(__name__) + + +@dataclass +class EmscriptenResponse: + status_code: int + headers: dict[str, str] + body: IOBase | bytes + request: EmscriptenRequest + + +class EmscriptenHttpResponseWrapper(BaseHTTPResponse): + def __init__( + self, + internal_response: EmscriptenResponse, + url: str | None = None, + connection: BaseHTTPConnection | BaseHTTPSConnection | None = None, + ): + self._pool = None # set by pool class + self._body = None + self._uncached_read_occurred = False + self._response = internal_response + self._url = url + self._connection = connection + self._closed = False + super().__init__( + headers=internal_response.headers, + status=internal_response.status_code, + request_url=url, + version=0, + version_string="HTTP/?", + reason="", + decode_content=True, + ) + self.length_remaining = self._init_length(self._response.request.method) + self.length_is_certain = False + + @property + def url(self) -> str | None: + return self._url + + @url.setter + def url(self, url: str | None) -> None: + self._url = url + + @property + def connection(self) -> BaseHTTPConnection | BaseHTTPSConnection | None: + return self._connection + + @property + def retries(self) -> Retry | None: + return self._retries + + @retries.setter + def retries(self, retries: Retry | None) -> None: + # Override the request_url if retries has a redirect location. + self._retries = retries + + def stream( + self, amt: int | None = 2**16, decode_content: bool | None = None + ) -> typing.Generator[bytes]: + """ + A generator wrapper for the read() method. A call will block until + ``amt`` bytes have been read from the connection or until the + connection is closed. + + :param amt: + How much of the content to read. The generator will return up to + much data per iteration, but may return less. This is particularly + likely when using compressed data. However, the empty string will + never be returned. + + :param decode_content: + If True, will attempt to decode the body based on the + 'content-encoding' header. + """ + while True: + data = self.read(amt=amt, decode_content=decode_content) + + if data: + yield data + else: + break + + def _init_length(self, request_method: str | None) -> int | None: + length: int | None + content_length: str | None = self.headers.get("content-length") + + if content_length is not None: + try: + # RFC 7230 section 3.3.2 specifies multiple content lengths can + # be sent in a single Content-Length header + # (e.g. Content-Length: 42, 42). This line ensures the values + # are all valid ints and that as long as the `set` length is 1, + # all values are the same. Otherwise, the header is invalid. + lengths = {int(val) for val in content_length.split(",")} + if len(lengths) > 1: + raise InvalidHeader( + "Content-Length contained multiple " + "unmatching values (%s)" % content_length + ) + length = lengths.pop() + except ValueError: + length = None + else: + if length < 0: + length = None + + else: # if content_length is None + length = None + + # Check for responses that shouldn't include a body + if ( + self.status in (204, 304) + or 100 <= self.status < 200 + or request_method == "HEAD" + ): + length = 0 + + return length + + def read( + self, + amt: int | None = None, + decode_content: bool | None = None, # ignored because browser decodes always + cache_content: bool = False, + ) -> bytes: + if ( + self._closed + or self._response is None + or (isinstance(self._response.body, IOBase) and self._response.body.closed) + ): + return b"" + + with self._error_catcher(): + # body has been preloaded as a string by XmlHttpRequest + if not isinstance(self._response.body, IOBase): + self.length_remaining = len(self._response.body) + self.length_is_certain = True + # wrap body in IOStream + self._response.body = BytesIO(self._response.body) + if amt is not None and amt >= 0: + # don't cache partial content + cache_content = False + data = self._response.body.read(amt) + self._uncached_read_occurred = True + else: # read all we can (and cache it) + data = self._response.body.read() + if cache_content and not self._uncached_read_occurred: + self._body = data + else: + self._uncached_read_occurred = True + if self.length_remaining is not None: + self.length_remaining = max(self.length_remaining - len(data), 0) + if len(data) == 0 or ( + self.length_is_certain and self.length_remaining == 0 + ): + # definitely finished reading, close response stream + self._response.body.close() + return typing.cast(bytes, data) + + def read_chunked( + self, + amt: int | None = None, + decode_content: bool | None = None, + ) -> typing.Generator[bytes]: + # chunked is handled by browser + while True: + bytes = self.read(amt, decode_content) + if not bytes: + break + yield bytes + + def release_conn(self) -> None: + if not self._pool or not self._connection: + return None + + self._pool._put_conn(self._connection) + self._connection = None + + def drain_conn(self) -> None: + self.close() + + @property + def data(self) -> bytes: + if self._body: + return self._body + else: + return self.read(cache_content=True) + + def json(self) -> typing.Any: + """ + Deserializes the body of the HTTP response as a Python object. + + The body of the HTTP response must be encoded using UTF-8, as per + `RFC 8529 Section 8.1 `_. + + To use a custom JSON decoder pass the result of :attr:`HTTPResponse.data` to + your custom decoder instead. + + If the body of the HTTP response is not decodable to UTF-8, a + `UnicodeDecodeError` will be raised. If the body of the HTTP response is not a + valid JSON document, a `json.JSONDecodeError` will be raised. + + Read more :ref:`here `. + + :returns: The body of the HTTP response as a Python object. + """ + data = self.data.decode("utf-8") + return _json.loads(data) + + def close(self) -> None: + if not self._closed: + if isinstance(self._response.body, IOBase): + self._response.body.close() + if self._connection: + self._connection.close() + self._connection = None + self._closed = True + + @contextmanager + def _error_catcher(self) -> typing.Generator[None]: + """ + Catch Emscripten specific exceptions thrown by fetch.py, + instead re-raising urllib3 variants, so that low-level exceptions + are not leaked in the high-level api. + + On exit, release the connection back to the pool. + """ + from .fetch import _RequestError, _TimeoutError # avoid circular import + + clean_exit = False + + try: + yield + # If no exception is thrown, we should avoid cleaning up + # unnecessarily. + clean_exit = True + except _TimeoutError as e: + raise TimeoutError(str(e)) + except _RequestError as e: + raise HTTPException(str(e)) + finally: + # If we didn't terminate cleanly, we need to throw away our + # connection. + if not clean_exit: + # The response may not be closed but we're not going to use it + # anymore so close it now + if ( + isinstance(self._response.body, IOBase) + and not self._response.body.closed + ): + self._response.body.close() + # release the connection back to the pool + self.release_conn() + else: + # If we have read everything from the response stream, + # return the connection back to the pool. + if ( + isinstance(self._response.body, IOBase) + and self._response.body.closed + ): + self.release_conn() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/pyopenssl.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/pyopenssl.py new file mode 100644 index 0000000000000000000000000000000000000000..f06b8599920fdcf6b8a2f869141378709a30c84c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/pyopenssl.py @@ -0,0 +1,563 @@ +""" +Module for using pyOpenSSL as a TLS backend. This module was relevant before +the standard library ``ssl`` module supported SNI, but now that we've dropped +support for Python 2.7 all relevant Python versions support SNI so +**this module is no longer recommended**. + +This needs the following packages installed: + +* `pyOpenSSL`_ (tested with 19.0.0) +* `cryptography`_ (minimum 2.3, from pyopenssl) +* `idna`_ (minimum 2.1, from cryptography) + +However, pyOpenSSL depends on cryptography, so while we use all three directly here we +end up having relatively few packages required. + +You can install them with the following command: + +.. code-block:: bash + + $ python -m pip install pyopenssl cryptography idna + +To activate certificate checking, call +:func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code +before you begin making HTTP requests. This can be done in a ``sitecustomize`` +module, or at any other time before your application begins using ``urllib3``, +like this: + +.. code-block:: python + + try: + import urllib3.contrib.pyopenssl + urllib3.contrib.pyopenssl.inject_into_urllib3() + except ImportError: + pass + +.. _pyopenssl: https://www.pyopenssl.org +.. _cryptography: https://cryptography.io +.. _idna: https://github.com/kjd/idna +""" + +from __future__ import annotations + +import OpenSSL.SSL # type: ignore[import-not-found] +from cryptography import x509 + +try: + from cryptography.x509 import UnsupportedExtension # type: ignore[attr-defined] +except ImportError: + # UnsupportedExtension is gone in cryptography >= 2.1.0 + class UnsupportedExtension(Exception): # type: ignore[no-redef] + pass + + +import logging +import ssl +import typing +from io import BytesIO +from socket import socket as socket_cls + +from .. import util + +if typing.TYPE_CHECKING: + from OpenSSL.crypto import X509 # type: ignore[import-not-found] + + +__all__ = ["inject_into_urllib3", "extract_from_urllib3"] + +# Map from urllib3 to PyOpenSSL compatible parameter-values. +_openssl_versions: dict[int, int] = { + util.ssl_.PROTOCOL_TLS: OpenSSL.SSL.SSLv23_METHOD, # type: ignore[attr-defined] + util.ssl_.PROTOCOL_TLS_CLIENT: OpenSSL.SSL.SSLv23_METHOD, # type: ignore[attr-defined] + ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD, +} + +if hasattr(ssl, "PROTOCOL_TLSv1_1") and hasattr(OpenSSL.SSL, "TLSv1_1_METHOD"): + _openssl_versions[ssl.PROTOCOL_TLSv1_1] = OpenSSL.SSL.TLSv1_1_METHOD + +if hasattr(ssl, "PROTOCOL_TLSv1_2") and hasattr(OpenSSL.SSL, "TLSv1_2_METHOD"): + _openssl_versions[ssl.PROTOCOL_TLSv1_2] = OpenSSL.SSL.TLSv1_2_METHOD + + +_stdlib_to_openssl_verify = { + ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE, + ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER, + ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER + + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT, +} +_openssl_to_stdlib_verify = {v: k for k, v in _stdlib_to_openssl_verify.items()} + +# The SSLvX values are the most likely to be missing in the future +# but we check them all just to be sure. +_OP_NO_SSLv2_OR_SSLv3: int = getattr(OpenSSL.SSL, "OP_NO_SSLv2", 0) | getattr( + OpenSSL.SSL, "OP_NO_SSLv3", 0 +) +_OP_NO_TLSv1: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1", 0) +_OP_NO_TLSv1_1: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1_1", 0) +_OP_NO_TLSv1_2: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1_2", 0) +_OP_NO_TLSv1_3: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1_3", 0) + +_openssl_to_ssl_minimum_version: dict[int, int] = { + ssl.TLSVersion.MINIMUM_SUPPORTED: _OP_NO_SSLv2_OR_SSLv3, + ssl.TLSVersion.TLSv1: _OP_NO_SSLv2_OR_SSLv3, + ssl.TLSVersion.TLSv1_1: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1, + ssl.TLSVersion.TLSv1_2: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1 | _OP_NO_TLSv1_1, + ssl.TLSVersion.TLSv1_3: ( + _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1 | _OP_NO_TLSv1_1 | _OP_NO_TLSv1_2 + ), + ssl.TLSVersion.MAXIMUM_SUPPORTED: ( + _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1 | _OP_NO_TLSv1_1 | _OP_NO_TLSv1_2 + ), +} +_openssl_to_ssl_maximum_version: dict[int, int] = { + ssl.TLSVersion.MINIMUM_SUPPORTED: ( + _OP_NO_SSLv2_OR_SSLv3 + | _OP_NO_TLSv1 + | _OP_NO_TLSv1_1 + | _OP_NO_TLSv1_2 + | _OP_NO_TLSv1_3 + ), + ssl.TLSVersion.TLSv1: ( + _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1_1 | _OP_NO_TLSv1_2 | _OP_NO_TLSv1_3 + ), + ssl.TLSVersion.TLSv1_1: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1_2 | _OP_NO_TLSv1_3, + ssl.TLSVersion.TLSv1_2: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1_3, + ssl.TLSVersion.TLSv1_3: _OP_NO_SSLv2_OR_SSLv3, + ssl.TLSVersion.MAXIMUM_SUPPORTED: _OP_NO_SSLv2_OR_SSLv3, +} + +# OpenSSL will only write 16K at a time +SSL_WRITE_BLOCKSIZE = 16384 + +orig_util_SSLContext = util.ssl_.SSLContext + + +log = logging.getLogger(__name__) + + +def inject_into_urllib3() -> None: + "Monkey-patch urllib3 with PyOpenSSL-backed SSL-support." + + _validate_dependencies_met() + + util.SSLContext = PyOpenSSLContext # type: ignore[assignment] + util.ssl_.SSLContext = PyOpenSSLContext # type: ignore[assignment] + util.IS_PYOPENSSL = True + util.ssl_.IS_PYOPENSSL = True + + +def extract_from_urllib3() -> None: + "Undo monkey-patching by :func:`inject_into_urllib3`." + + util.SSLContext = orig_util_SSLContext + util.ssl_.SSLContext = orig_util_SSLContext + util.IS_PYOPENSSL = False + util.ssl_.IS_PYOPENSSL = False + + +def _validate_dependencies_met() -> None: + """ + Verifies that PyOpenSSL's package-level dependencies have been met. + Throws `ImportError` if they are not met. + """ + # Method added in `cryptography==1.1`; not available in older versions + from cryptography.x509.extensions import Extensions + + if getattr(Extensions, "get_extension_for_class", None) is None: + raise ImportError( + "'cryptography' module missing required functionality. " + "Try upgrading to v1.3.4 or newer." + ) + + # pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509 + # attribute is only present on those versions. + from OpenSSL.crypto import X509 + + x509 = X509() + if getattr(x509, "_x509", None) is None: + raise ImportError( + "'pyOpenSSL' module missing required functionality. " + "Try upgrading to v0.14 or newer." + ) + + +def _dnsname_to_stdlib(name: str) -> str | None: + """ + Converts a dNSName SubjectAlternativeName field to the form used by the + standard library on the given Python version. + + Cryptography produces a dNSName as a unicode string that was idna-decoded + from ASCII bytes. We need to idna-encode that string to get it back, and + then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib + uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8). + + If the name cannot be idna-encoded then we return None signalling that + the name given should be skipped. + """ + + def idna_encode(name: str) -> bytes | None: + """ + Borrowed wholesale from the Python Cryptography Project. It turns out + that we can't just safely call `idna.encode`: it can explode for + wildcard names. This avoids that problem. + """ + import idna + + try: + for prefix in ["*.", "."]: + if name.startswith(prefix): + name = name[len(prefix) :] + return prefix.encode("ascii") + idna.encode(name) + return idna.encode(name) + except idna.core.IDNAError: + return None + + # Don't send IPv6 addresses through the IDNA encoder. + if ":" in name: + return name + + encoded_name = idna_encode(name) + if encoded_name is None: + return None + return encoded_name.decode("utf-8") + + +def get_subj_alt_name(peer_cert: X509) -> list[tuple[str, str]]: + """ + Given an PyOpenSSL certificate, provides all the subject alternative names. + """ + cert = peer_cert.to_cryptography() + + # We want to find the SAN extension. Ask Cryptography to locate it (it's + # faster than looping in Python) + try: + ext = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value + except x509.ExtensionNotFound: + # No such extension, return the empty list. + return [] + except ( + x509.DuplicateExtension, + UnsupportedExtension, + x509.UnsupportedGeneralNameType, + UnicodeError, + ) as e: + # A problem has been found with the quality of the certificate. Assume + # no SAN field is present. + log.warning( + "A problem was encountered with the certificate that prevented " + "urllib3 from finding the SubjectAlternativeName field. This can " + "affect certificate validation. The error was %s", + e, + ) + return [] + + # We want to return dNSName and iPAddress fields. We need to cast the IPs + # back to strings because the match_hostname function wants them as + # strings. + # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 + # decoded. This is pretty frustrating, but that's what the standard library + # does with certificates, and so we need to attempt to do the same. + # We also want to skip over names which cannot be idna encoded. + names = [ + ("DNS", name) + for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName)) + if name is not None + ] + names.extend( + ("IP Address", str(name)) for name in ext.get_values_for_type(x509.IPAddress) + ) + + return names + + +class WrappedSocket: + """API-compatibility wrapper for Python OpenSSL's Connection-class.""" + + def __init__( + self, + connection: OpenSSL.SSL.Connection, + socket: socket_cls, + suppress_ragged_eofs: bool = True, + ) -> None: + self.connection = connection + self.socket = socket + self.suppress_ragged_eofs = suppress_ragged_eofs + self._io_refs = 0 + self._closed = False + + def fileno(self) -> int: + return self.socket.fileno() + + # Copy-pasted from Python 3.5 source code + def _decref_socketios(self) -> None: + if self._io_refs > 0: + self._io_refs -= 1 + if self._closed: + self.close() + + def recv(self, *args: typing.Any, **kwargs: typing.Any) -> bytes: + try: + data = self.connection.recv(*args, **kwargs) + except OpenSSL.SSL.SysCallError as e: + if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"): + return b"" + else: + raise OSError(e.args[0], str(e)) from e + except OpenSSL.SSL.ZeroReturnError: + if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: + return b"" + else: + raise + except OpenSSL.SSL.WantReadError as e: + if not util.wait_for_read(self.socket, self.socket.gettimeout()): + raise TimeoutError("The read operation timed out") from e + else: + return self.recv(*args, **kwargs) + + # TLS 1.3 post-handshake authentication + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"read error: {e!r}") from e + else: + return data # type: ignore[no-any-return] + + def recv_into(self, *args: typing.Any, **kwargs: typing.Any) -> int: + try: + return self.connection.recv_into(*args, **kwargs) # type: ignore[no-any-return] + except OpenSSL.SSL.SysCallError as e: + if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"): + return 0 + else: + raise OSError(e.args[0], str(e)) from e + except OpenSSL.SSL.ZeroReturnError: + if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: + return 0 + else: + raise + except OpenSSL.SSL.WantReadError as e: + if not util.wait_for_read(self.socket, self.socket.gettimeout()): + raise TimeoutError("The read operation timed out") from e + else: + return self.recv_into(*args, **kwargs) + + # TLS 1.3 post-handshake authentication + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"read error: {e!r}") from e + + def settimeout(self, timeout: float) -> None: + return self.socket.settimeout(timeout) + + def _send_until_done(self, data: bytes) -> int: + while True: + try: + return self.connection.send(data) # type: ignore[no-any-return] + except OpenSSL.SSL.WantWriteError as e: + if not util.wait_for_write(self.socket, self.socket.gettimeout()): + raise TimeoutError() from e + continue + except OpenSSL.SSL.SysCallError as e: + raise OSError(e.args[0], str(e)) from e + + def sendall(self, data: bytes) -> None: + total_sent = 0 + while total_sent < len(data): + sent = self._send_until_done( + data[total_sent : total_sent + SSL_WRITE_BLOCKSIZE] + ) + total_sent += sent + + def shutdown(self, how: int) -> None: + try: + self.connection.shutdown() + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"shutdown error: {e!r}") from e + + def close(self) -> None: + self._closed = True + if self._io_refs <= 0: + self._real_close() + + def _real_close(self) -> None: + try: + return self.connection.close() # type: ignore[no-any-return] + except OpenSSL.SSL.Error: + return + + def getpeercert( + self, binary_form: bool = False + ) -> dict[str, list[typing.Any]] | None: + x509 = self.connection.get_peer_certificate() + + if not x509: + return x509 # type: ignore[no-any-return] + + if binary_form: + return OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, x509) # type: ignore[no-any-return] + + return { + "subject": ((("commonName", x509.get_subject().CN),),), # type: ignore[dict-item] + "subjectAltName": get_subj_alt_name(x509), + } + + def version(self) -> str: + return self.connection.get_protocol_version_name() # type: ignore[no-any-return] + + def selected_alpn_protocol(self) -> str | None: + alpn_proto = self.connection.get_alpn_proto_negotiated() + return alpn_proto.decode() if alpn_proto else None + + +WrappedSocket.makefile = socket_cls.makefile # type: ignore[attr-defined] + + +class PyOpenSSLContext: + """ + I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible + for translating the interface of the standard library ``SSLContext`` object + to calls into PyOpenSSL. + """ + + def __init__(self, protocol: int) -> None: + self.protocol = _openssl_versions[protocol] + self._ctx = OpenSSL.SSL.Context(self.protocol) + self._options = 0 + self.check_hostname = False + self._minimum_version: int = ssl.TLSVersion.MINIMUM_SUPPORTED + self._maximum_version: int = ssl.TLSVersion.MAXIMUM_SUPPORTED + self._verify_flags: int = ssl.VERIFY_X509_TRUSTED_FIRST + + @property + def options(self) -> int: + return self._options + + @options.setter + def options(self, value: int) -> None: + self._options = value + self._set_ctx_options() + + @property + def verify_flags(self) -> int: + return self._verify_flags + + @verify_flags.setter + def verify_flags(self, value: int) -> None: + self._verify_flags = value + self._ctx.get_cert_store().set_flags(self._verify_flags) + + @property + def verify_mode(self) -> int: + return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()] + + @verify_mode.setter + def verify_mode(self, value: ssl.VerifyMode) -> None: + self._ctx.set_verify(_stdlib_to_openssl_verify[value], _verify_callback) + + def set_default_verify_paths(self) -> None: + self._ctx.set_default_verify_paths() + + def set_ciphers(self, ciphers: bytes | str) -> None: + if isinstance(ciphers, str): + ciphers = ciphers.encode("utf-8") + self._ctx.set_cipher_list(ciphers) + + def load_verify_locations( + self, + cafile: str | None = None, + capath: str | None = None, + cadata: bytes | None = None, + ) -> None: + if cafile is not None: + cafile = cafile.encode("utf-8") # type: ignore[assignment] + if capath is not None: + capath = capath.encode("utf-8") # type: ignore[assignment] + try: + self._ctx.load_verify_locations(cafile, capath) + if cadata is not None: + self._ctx.load_verify_locations(BytesIO(cadata)) + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"unable to load trusted certificates: {e!r}") from e + + def load_cert_chain( + self, + certfile: str, + keyfile: str | None = None, + password: str | None = None, + ) -> None: + try: + self._ctx.use_certificate_chain_file(certfile) + if password is not None: + if not isinstance(password, bytes): + password = password.encode("utf-8") # type: ignore[assignment] + self._ctx.set_passwd_cb(lambda *_: password) + self._ctx.use_privatekey_file(keyfile or certfile) + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"Unable to load certificate chain: {e!r}") from e + + def set_alpn_protocols(self, protocols: list[bytes | str]) -> None: + protocols = [util.util.to_bytes(p, "ascii") for p in protocols] + return self._ctx.set_alpn_protos(protocols) # type: ignore[no-any-return] + + def wrap_socket( + self, + sock: socket_cls, + server_side: bool = False, + do_handshake_on_connect: bool = True, + suppress_ragged_eofs: bool = True, + server_hostname: bytes | str | None = None, + ) -> WrappedSocket: + cnx = OpenSSL.SSL.Connection(self._ctx, sock) + + # If server_hostname is an IP, don't use it for SNI, per RFC6066 Section 3 + if server_hostname and not util.ssl_.is_ipaddress(server_hostname): + if isinstance(server_hostname, str): + server_hostname = server_hostname.encode("utf-8") + cnx.set_tlsext_host_name(server_hostname) + + cnx.set_connect_state() + + while True: + try: + cnx.do_handshake() + except OpenSSL.SSL.WantReadError as e: + if not util.wait_for_read(sock, sock.gettimeout()): + raise TimeoutError("select timed out") from e + continue + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"bad handshake: {e!r}") from e + break + + return WrappedSocket(cnx, sock) + + def _set_ctx_options(self) -> None: + self._ctx.set_options( + self._options + | _openssl_to_ssl_minimum_version[self._minimum_version] + | _openssl_to_ssl_maximum_version[self._maximum_version] + ) + + @property + def minimum_version(self) -> int: + return self._minimum_version + + @minimum_version.setter + def minimum_version(self, minimum_version: int) -> None: + self._minimum_version = minimum_version + self._set_ctx_options() + + @property + def maximum_version(self) -> int: + return self._maximum_version + + @maximum_version.setter + def maximum_version(self, maximum_version: int) -> None: + self._maximum_version = maximum_version + self._set_ctx_options() + + +def _verify_callback( + cnx: OpenSSL.SSL.Connection, + x509: X509, + err_no: int, + err_depth: int, + return_code: int, +) -> bool: + return err_no == 0 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/socks.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/socks.py new file mode 100644 index 0000000000000000000000000000000000000000..d37da8fc2049a7b3f7e18d2f64e79c205cfe3d3e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/contrib/socks.py @@ -0,0 +1,228 @@ +""" +This module contains provisional support for SOCKS proxies from within +urllib3. This module supports SOCKS4, SOCKS4A (an extension of SOCKS4), and +SOCKS5. To enable its functionality, either install PySocks or install this +module with the ``socks`` extra. + +The SOCKS implementation supports the full range of urllib3 features. It also +supports the following SOCKS features: + +- SOCKS4A (``proxy_url='socks4a://...``) +- SOCKS4 (``proxy_url='socks4://...``) +- SOCKS5 with remote DNS (``proxy_url='socks5h://...``) +- SOCKS5 with local DNS (``proxy_url='socks5://...``) +- Usernames and passwords for the SOCKS proxy + +.. note:: + It is recommended to use ``socks5h://`` or ``socks4a://`` schemes in + your ``proxy_url`` to ensure that DNS resolution is done from the remote + server instead of client-side when connecting to a domain name. + +SOCKS4 supports IPv4 and domain names with the SOCKS4A extension. SOCKS5 +supports IPv4, IPv6, and domain names. + +When connecting to a SOCKS4 proxy the ``username`` portion of the ``proxy_url`` +will be sent as the ``userid`` section of the SOCKS request: + +.. code-block:: python + + proxy_url="socks4a://@proxy-host" + +When connecting to a SOCKS5 proxy the ``username`` and ``password`` portion +of the ``proxy_url`` will be sent as the username/password to authenticate +with the proxy: + +.. code-block:: python + + proxy_url="socks5h://:@proxy-host" + +""" + +from __future__ import annotations + +try: + import socks # type: ignore[import-untyped] +except ImportError: + import warnings + + from ..exceptions import DependencyWarning + + warnings.warn( + ( + "SOCKS support in urllib3 requires the installation of optional " + "dependencies: specifically, PySocks. For more information, see " + "https://urllib3.readthedocs.io/en/latest/advanced-usage.html#socks-proxies" + ), + DependencyWarning, + ) + raise + +import typing +from socket import timeout as SocketTimeout + +from ..connection import HTTPConnection, HTTPSConnection +from ..connectionpool import HTTPConnectionPool, HTTPSConnectionPool +from ..exceptions import ConnectTimeoutError, NewConnectionError +from ..poolmanager import PoolManager +from ..util.url import parse_url + +try: + import ssl +except ImportError: + ssl = None # type: ignore[assignment] + + +class _TYPE_SOCKS_OPTIONS(typing.TypedDict): + socks_version: int + proxy_host: str | None + proxy_port: str | None + username: str | None + password: str | None + rdns: bool + + +class SOCKSConnection(HTTPConnection): + """ + A plain-text HTTP connection that connects via a SOCKS proxy. + """ + + def __init__( + self, + _socks_options: _TYPE_SOCKS_OPTIONS, + *args: typing.Any, + **kwargs: typing.Any, + ) -> None: + self._socks_options = _socks_options + super().__init__(*args, **kwargs) + + def _new_conn(self) -> socks.socksocket: + """ + Establish a new connection via the SOCKS proxy. + """ + extra_kw: dict[str, typing.Any] = {} + if self.source_address: + extra_kw["source_address"] = self.source_address + + if self.socket_options: + extra_kw["socket_options"] = self.socket_options + + try: + conn = socks.create_connection( + (self.host, self.port), + proxy_type=self._socks_options["socks_version"], + proxy_addr=self._socks_options["proxy_host"], + proxy_port=self._socks_options["proxy_port"], + proxy_username=self._socks_options["username"], + proxy_password=self._socks_options["password"], + proxy_rdns=self._socks_options["rdns"], + timeout=self.timeout, + **extra_kw, + ) + + except SocketTimeout as e: + raise ConnectTimeoutError( + self, + f"Connection to {self.host} timed out. (connect timeout={self.timeout})", + ) from e + + except socks.ProxyError as e: + # This is fragile as hell, but it seems to be the only way to raise + # useful errors here. + if e.socket_err: + error = e.socket_err + if isinstance(error, SocketTimeout): + raise ConnectTimeoutError( + self, + f"Connection to {self.host} timed out. (connect timeout={self.timeout})", + ) from e + else: + # Adding `from e` messes with coverage somehow, so it's omitted. + # See #2386. + raise NewConnectionError( + self, f"Failed to establish a new connection: {error}" + ) + else: # Defensive: see https://github.com/urllib3/urllib3/pull/3728#pullrequestreview-3816302703 + raise NewConnectionError( + self, f"Failed to establish a new connection: {e}" + ) from e + + except OSError as e: # Defensive: PySocks should catch all these. + raise NewConnectionError( + self, f"Failed to establish a new connection: {e}" + ) from e + + return conn + + +# We don't need to duplicate the Verified/Unverified distinction from +# urllib3/connection.py here because the HTTPSConnection will already have been +# correctly set to either the Verified or Unverified form by that module. This +# means the SOCKSHTTPSConnection will automatically be the correct type. +class SOCKSHTTPSConnection(SOCKSConnection, HTTPSConnection): + pass + + +class SOCKSHTTPConnectionPool(HTTPConnectionPool): + ConnectionCls = SOCKSConnection + + +class SOCKSHTTPSConnectionPool(HTTPSConnectionPool): + ConnectionCls = SOCKSHTTPSConnection + + +class SOCKSProxyManager(PoolManager): + """ + A version of the urllib3 ProxyManager that routes connections via the + defined SOCKS proxy. + """ + + pool_classes_by_scheme = { + "http": SOCKSHTTPConnectionPool, + "https": SOCKSHTTPSConnectionPool, + } + + def __init__( + self, + proxy_url: str, + username: str | None = None, + password: str | None = None, + num_pools: int = 10, + headers: typing.Mapping[str, str] | None = None, + **connection_pool_kw: typing.Any, + ): + parsed = parse_url(proxy_url) + + if username is None and password is None and parsed.auth is not None: + split = parsed.auth.split(":") + if len(split) == 2: + username, password = split + if parsed.scheme == "socks5": + socks_version = socks.PROXY_TYPE_SOCKS5 + rdns = False + elif parsed.scheme == "socks5h": + socks_version = socks.PROXY_TYPE_SOCKS5 + rdns = True + elif parsed.scheme == "socks4": + socks_version = socks.PROXY_TYPE_SOCKS4 + rdns = False + elif parsed.scheme == "socks4a": + socks_version = socks.PROXY_TYPE_SOCKS4 + rdns = True + else: + raise ValueError(f"Unable to determine SOCKS version from {proxy_url}") + + self.proxy_url = proxy_url + + socks_options = { + "socks_version": socks_version, + "proxy_host": parsed.host, + "proxy_port": parsed.port, + "username": username, + "password": password, + "rdns": rdns, + } + connection_pool_kw["_socks_options"] = socks_options + + super().__init__(num_pools, headers, **connection_pool_kw) + + self.pool_classes_by_scheme = SOCKSProxyManager.pool_classes_by_scheme diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/http2/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/http2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..133e1d8f237f6fddd557ae1c0e0cf738f7cc2748 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/http2/__init__.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +from importlib.metadata import version + +__all__ = [ + "inject_into_urllib3", + "extract_from_urllib3", +] + +import typing + +orig_HTTPSConnection: typing.Any = None + + +def inject_into_urllib3() -> None: + # First check if h2 version is valid + h2_version = version("h2") + if not h2_version.startswith("4."): + raise ImportError( + "urllib3 v2 supports h2 version 4.x.x, currently " + f"the 'h2' module is compiled with {h2_version!r}. " + "See: https://github.com/urllib3/urllib3/issues/3290" + ) + + # Import here to avoid circular dependencies. + from .. import connection as urllib3_connection + from .. import util as urllib3_util + from ..connectionpool import HTTPSConnectionPool + from ..util import ssl_ as urllib3_util_ssl + from .connection import HTTP2Connection + + global orig_HTTPSConnection + orig_HTTPSConnection = urllib3_connection.HTTPSConnection + + HTTPSConnectionPool.ConnectionCls = HTTP2Connection + urllib3_connection.HTTPSConnection = HTTP2Connection # type: ignore[misc] + + # TODO: Offer 'http/1.1' as well, but for testing purposes this is handy. + urllib3_util.ALPN_PROTOCOLS = ["h2"] + urllib3_util_ssl.ALPN_PROTOCOLS = ["h2"] + + +def extract_from_urllib3() -> None: + from .. import connection as urllib3_connection + from .. import util as urllib3_util + from ..connectionpool import HTTPSConnectionPool + from ..util import ssl_ as urllib3_util_ssl + + HTTPSConnectionPool.ConnectionCls = orig_HTTPSConnection + urllib3_connection.HTTPSConnection = orig_HTTPSConnection # type: ignore[misc] + + urllib3_util.ALPN_PROTOCOLS = ["http/1.1"] + urllib3_util_ssl.ALPN_PROTOCOLS = ["http/1.1"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/http2/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/http2/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22315980af4e77579967b48c68445dc08daa272f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/http2/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/http2/__pycache__/connection.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/http2/__pycache__/connection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d56dccb1bd51a734a45e3c342e22e8cf410735b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/http2/__pycache__/connection.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/http2/__pycache__/probe.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/http2/__pycache__/probe.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..337bd483e46444e7c6cdf3171f0f9e146a8756c6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/http2/__pycache__/probe.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/http2/connection.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/http2/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..0a026da0a8357e324ded47b82b24042713b9bf06 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/http2/connection.py @@ -0,0 +1,356 @@ +from __future__ import annotations + +import logging +import re +import threading +import types +import typing + +import h2.config +import h2.connection +import h2.events + +from .._base_connection import _TYPE_BODY +from .._collections import HTTPHeaderDict +from ..connection import HTTPSConnection, _get_default_user_agent +from ..exceptions import ConnectionError +from ..response import BaseHTTPResponse + +orig_HTTPSConnection = HTTPSConnection + +T = typing.TypeVar("T") + +log = logging.getLogger(__name__) + +RE_IS_LEGAL_HEADER_NAME = re.compile(rb"^[!#$%&'*+\-.^_`|~0-9a-z]+$") +RE_IS_ILLEGAL_HEADER_VALUE = re.compile(rb"[\0\x00\x0a\x0d\r\n]|^[ \r\n\t]|[ \r\n\t]$") + + +def _is_legal_header_name(name: bytes) -> bool: + """ + "An implementation that validates fields according to the definitions in Sections + 5.1 and 5.5 of [HTTP] only needs an additional check that field names do not + include uppercase characters." (https://httpwg.org/specs/rfc9113.html#n-field-validity) + + `http.client._is_legal_header_name` does not validate the field name according to the + HTTP 1.1 spec, so we do that here, in addition to checking for uppercase characters. + + This does not allow for the `:` character in the header name, so should not + be used to validate pseudo-headers. + """ + return bool(RE_IS_LEGAL_HEADER_NAME.match(name)) + + +def _is_illegal_header_value(value: bytes) -> bool: + """ + "A field value MUST NOT contain the zero value (ASCII NUL, 0x00), line feed + (ASCII LF, 0x0a), or carriage return (ASCII CR, 0x0d) at any position. A field + value MUST NOT start or end with an ASCII whitespace character (ASCII SP or HTAB, + 0x20 or 0x09)." (https://httpwg.org/specs/rfc9113.html#n-field-validity) + """ + return bool(RE_IS_ILLEGAL_HEADER_VALUE.search(value)) + + +class _LockedObject(typing.Generic[T]): + """ + A wrapper class that hides a specific object behind a lock. + The goal here is to provide a simple way to protect access to an object + that cannot safely be simultaneously accessed from multiple threads. The + intended use of this class is simple: take hold of it with a context + manager, which returns the protected object. + """ + + __slots__ = ( + "lock", + "_obj", + ) + + def __init__(self, obj: T): + self.lock = threading.RLock() + self._obj = obj + + def __enter__(self) -> T: + self.lock.acquire() + return self._obj + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: types.TracebackType | None, + ) -> None: + self.lock.release() + + +class HTTP2Connection(HTTPSConnection): + def __init__( + self, host: str, port: int | None = None, **kwargs: typing.Any + ) -> None: + self._h2_conn = self._new_h2_conn() + self._h2_stream: int | None = None + self._headers: list[tuple[bytes, bytes]] = [] + + if "proxy" in kwargs or "proxy_config" in kwargs: # Defensive: + raise NotImplementedError("Proxies aren't supported with HTTP/2") + + super().__init__(host, port, **kwargs) + + if self._tunnel_host is not None: + raise NotImplementedError("Tunneling isn't supported with HTTP/2") + + def _new_h2_conn(self) -> _LockedObject[h2.connection.H2Connection]: + config = h2.config.H2Configuration(client_side=True) + return _LockedObject(h2.connection.H2Connection(config=config)) + + def connect(self) -> None: + super().connect() + with self._h2_conn as conn: + conn.initiate_connection() + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + + def putrequest( # type: ignore[override] + self, + method: str, + url: str, + **kwargs: typing.Any, + ) -> None: + """putrequest + This deviates from the HTTPConnection method signature since we never need to override + sending accept-encoding headers or the host header. + """ + if "skip_host" in kwargs: + raise NotImplementedError("`skip_host` isn't supported") + if "skip_accept_encoding" in kwargs: + raise NotImplementedError("`skip_accept_encoding` isn't supported") + + self._request_url = url or "/" + self._validate_path(url) # type: ignore[attr-defined] + + if ":" in self.host: + authority = f"[{self.host}]:{self.port or 443}" + else: + authority = f"{self.host}:{self.port or 443}" + + self._headers.append((b":scheme", b"https")) + self._headers.append((b":method", method.encode())) + self._headers.append((b":authority", authority.encode())) + self._headers.append((b":path", url.encode())) + + with self._h2_conn as conn: + self._h2_stream = conn.get_next_available_stream_id() + + def putheader(self, header: str | bytes, *values: str | bytes) -> None: # type: ignore[override] + # TODO SKIPPABLE_HEADERS from urllib3 are ignored. + header = header.encode() if isinstance(header, str) else header + header = header.lower() # A lot of upstream code uses capitalized headers. + if not _is_legal_header_name(header): + raise ValueError(f"Illegal header name {str(header)}") + + for value in values: + value = value.encode() if isinstance(value, str) else value + if _is_illegal_header_value(value): + raise ValueError(f"Illegal header value {str(value)}") + self._headers.append((header, value)) + + def endheaders(self, message_body: typing.Any = None) -> None: # type: ignore[override] + if self._h2_stream is None: + raise ConnectionError("Must call `putrequest` first.") + + with self._h2_conn as conn: + conn.send_headers( + stream_id=self._h2_stream, + headers=self._headers, + end_stream=(message_body is None), + ) + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + self._headers = [] # Reset headers for the next request. + + def send(self, data: typing.Any) -> None: + """Send data to the server. + `data` can be: `str`, `bytes`, an iterable, or file-like objects + that support a .read() method. + """ + if self._h2_stream is None: + raise ConnectionError("Must call `putrequest` first.") + + with self._h2_conn as conn: + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + + if hasattr(data, "read"): # file-like objects + while True: + chunk = data.read(self.blocksize) + if not chunk: + break + if isinstance(chunk, str): + chunk = chunk.encode() + conn.send_data(self._h2_stream, chunk, end_stream=False) + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + conn.end_stream(self._h2_stream) + return + + if isinstance(data, str): # str -> bytes + data = data.encode() + + try: + if isinstance(data, bytes): + conn.send_data(self._h2_stream, data, end_stream=True) + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + else: + for chunk in data: + conn.send_data(self._h2_stream, chunk, end_stream=False) + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + conn.end_stream(self._h2_stream) + except TypeError: + raise TypeError( + "`data` should be str, bytes, iterable, or file. got %r" + % type(data) + ) + + def set_tunnel( + self, + host: str, + port: int | None = None, + headers: typing.Mapping[str, str] | None = None, + scheme: str = "http", + ) -> None: + raise NotImplementedError( + "HTTP/2 does not support setting up a tunnel through a proxy" + ) + + def getresponse( # type: ignore[override] + self, + ) -> HTTP2Response: + status = None + data = bytearray() + with self._h2_conn as conn: + end_stream = False + while not end_stream: + # TODO: Arbitrary read value. + if received_data := self.sock.recv(65535): + events = conn.receive_data(received_data) + for event in events: + if isinstance(event, h2.events.ResponseReceived): + headers = HTTPHeaderDict() + for header, value in event.headers: + if header == b":status": + status = int(value.decode()) + else: + headers.add( + header.decode("ascii"), value.decode("ascii") + ) + + elif isinstance(event, h2.events.DataReceived): + data += event.data + conn.acknowledge_received_data( + event.flow_controlled_length, event.stream_id + ) + + elif isinstance(event, h2.events.StreamEnded): + end_stream = True + + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + + assert status is not None + return HTTP2Response( + status=status, + headers=headers, + request_url=self._request_url, + data=bytes(data), + ) + + def request( # type: ignore[override] + self, + method: str, + url: str, + body: _TYPE_BODY | None = None, + headers: typing.Mapping[str, str] | None = None, + *, + preload_content: bool = True, + decode_content: bool = True, + enforce_content_length: bool = True, + **kwargs: typing.Any, + ) -> None: + """Send an HTTP/2 request""" + if "chunked" in kwargs: + # TODO this is often present from upstream. + # raise NotImplementedError("`chunked` isn't supported with HTTP/2") + pass + + if self.sock is not None: + self.sock.settimeout(self.timeout) + + self.putrequest(method, url) + + headers = headers or {} + for k, v in headers.items(): + if k.lower() == "transfer-encoding" and v == "chunked": + continue + else: + self.putheader(k, v) + + if b"user-agent" not in dict(self._headers): + self.putheader(b"user-agent", _get_default_user_agent()) + + if body: + self.endheaders(message_body=body) + self.send(body) + else: + self.endheaders() + + def close(self) -> None: + with self._h2_conn as conn: + try: + conn.close_connection() + if data := conn.data_to_send(): + self.sock.sendall(data) + except Exception: + pass + + # Reset all our HTTP/2 connection state. + self._h2_conn = self._new_h2_conn() + self._h2_stream = None + self._headers = [] + + super().close() + + +class HTTP2Response(BaseHTTPResponse): + # TODO: This is a woefully incomplete response object, but works for non-streaming. + def __init__( + self, + status: int, + headers: HTTPHeaderDict, + request_url: str, + data: bytes, + decode_content: bool = False, # TODO: support decoding + ) -> None: + super().__init__( + status=status, + headers=headers, + # Following CPython, we map HTTP versions to major * 10 + minor integers + version=20, + version_string="HTTP/2", + # No reason phrase in HTTP/2 + reason=None, + decode_content=decode_content, + request_url=request_url, + ) + self._data = data + self.length_remaining = 0 + + @property + def data(self) -> bytes: + return self._data + + def get_redirect_location(self) -> None: + return None + + def close(self) -> None: + pass diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/http2/probe.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/http2/probe.py new file mode 100644 index 0000000000000000000000000000000000000000..9ea900764f0885eafaac9454523417d86e33df2d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/http2/probe.py @@ -0,0 +1,87 @@ +from __future__ import annotations + +import threading + + +class _HTTP2ProbeCache: + __slots__ = ( + "_lock", + "_cache_locks", + "_cache_values", + ) + + def __init__(self) -> None: + self._lock = threading.Lock() + self._cache_locks: dict[tuple[str, int], threading.RLock] = {} + self._cache_values: dict[tuple[str, int], bool | None] = {} + + def acquire_and_get(self, host: str, port: int) -> bool | None: + # By the end of this block we know that + # _cache_[values,locks] is available. + value = None + with self._lock: + key = (host, port) + try: + value = self._cache_values[key] + # If it's a known value we return right away. + if value is not None: + return value + except KeyError: + self._cache_locks[key] = threading.RLock() + self._cache_values[key] = None + + # If the value is unknown, we acquire the lock to signal + # to the requesting thread that the probe is in progress + # or that the current thread needs to return their findings. + key_lock = self._cache_locks[key] + key_lock.acquire() + try: + # If the by the time we get the lock the value has been + # updated we want to return the updated value. + value = self._cache_values[key] + + # In case an exception like KeyboardInterrupt is raised here. + except BaseException as e: # Defensive: + assert not isinstance(e, KeyError) # KeyError shouldn't be possible. + key_lock.release() + raise + + return value + + def set_and_release( + self, host: str, port: int, supports_http2: bool | None + ) -> None: + key = (host, port) + key_lock = self._cache_locks[key] + with key_lock: # Uses an RLock, so can be locked again from same thread. + if supports_http2 is None and self._cache_values[key] is not None: + raise ValueError( + "Cannot reset HTTP/2 support for origin after value has been set." + ) # Defensive: not expected in normal usage + + self._cache_values[key] = supports_http2 + key_lock.release() + + def _values(self) -> dict[tuple[str, int], bool | None]: + """This function is for testing purposes only. Gets the current state of the probe cache""" + with self._lock: + return {k: v for k, v in self._cache_values.items()} + + def _reset(self) -> None: + """This function is for testing purposes only. Reset the cache values""" + with self._lock: + self._cache_locks = {} + self._cache_values = {} + + +_HTTP2_PROBE_CACHE = _HTTP2ProbeCache() + +set_and_release = _HTTP2_PROBE_CACHE.set_and_release +acquire_and_get = _HTTP2_PROBE_CACHE.acquire_and_get +_values = _HTTP2_PROBE_CACHE._values +_reset = _HTTP2_PROBE_CACHE._reset + +__all__ = [ + "set_and_release", + "acquire_and_get", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..534126033c083203649022fa9b753a433f005556 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__init__.py @@ -0,0 +1,42 @@ +# For backwards compatibility, provide imports that used to be here. +from __future__ import annotations + +from .connection import is_connection_dropped +from .request import SKIP_HEADER, SKIPPABLE_HEADERS, make_headers +from .response import is_fp_closed +from .retry import Retry +from .ssl_ import ( + ALPN_PROTOCOLS, + IS_PYOPENSSL, + SSLContext, + assert_fingerprint, + create_urllib3_context, + resolve_cert_reqs, + resolve_ssl_version, + ssl_wrap_socket, +) +from .timeout import Timeout +from .url import Url, parse_url +from .wait import wait_for_read, wait_for_write + +__all__ = ( + "IS_PYOPENSSL", + "SSLContext", + "ALPN_PROTOCOLS", + "Retry", + "Timeout", + "Url", + "assert_fingerprint", + "create_urllib3_context", + "is_connection_dropped", + "is_fp_closed", + "parse_url", + "make_headers", + "resolve_cert_reqs", + "resolve_ssl_version", + "ssl_wrap_socket", + "wait_for_read", + "wait_for_write", + "SKIP_HEADER", + "SKIPPABLE_HEADERS", +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b2469b149f2c4e580be679600cdf83a2b889cc1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/connection.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/connection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e326814bc20695b00192edc5ca2341e6619ddbe Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/connection.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/proxy.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/proxy.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b6d790dd99287beac0f8dc66df279df6e086429 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/proxy.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/request.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/request.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfdf5c288adecdaa9ec4234941b68426be9fd774 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/request.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/response.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/response.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ab612bcf8af0810b3c9b7562232de2a0c1eab61 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/response.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/retry.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/retry.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..213facbe52fd1b4fa01ea6273d94a09e29bf305f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/retry.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/ssl_.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/ssl_.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6957a605b904870f7a84ec162a0fd035fa476a9a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/ssl_.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/ssl_match_hostname.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/ssl_match_hostname.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d56dc95c0f2fbd19d03878e7367ddb77069a83a8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/ssl_match_hostname.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/ssltransport.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/ssltransport.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5615b7ccb86da023c329cf9476cbb8a367949acb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/ssltransport.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/timeout.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/timeout.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de833b717d396e0037d41c6c40305c006a4f4cfb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/timeout.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/url.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/url.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9db9e3ca507f079fe108a76b9b8c1aebcbfd7b1a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/url.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/util.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1f3140217c99acc94070dedb859ba1aa3c014ef Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/util.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/wait.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/wait.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c805b0ee290066949f7eb685fb463442af0d9d5a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/__pycache__/wait.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/connection.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..f92519ee9124e91e5da7d60ccc3f274312ed3514 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/connection.py @@ -0,0 +1,137 @@ +from __future__ import annotations + +import socket +import typing + +from ..exceptions import LocationParseError +from .timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT + +_TYPE_SOCKET_OPTIONS = list[tuple[int, int, typing.Union[int, bytes]]] + +if typing.TYPE_CHECKING: + from .._base_connection import BaseHTTPConnection + + +def is_connection_dropped(conn: BaseHTTPConnection) -> bool: # Platform-specific + """ + Returns True if the connection is dropped and should be closed. + :param conn: :class:`urllib3.connection.HTTPConnection` object. + """ + return not conn.is_connected + + +# This function is copied from socket.py in the Python 2.7 standard +# library test suite. Added to its signature is only `socket_options`. +# One additional modification is that we avoid binding to IPv6 servers +# discovered in DNS if the system doesn't have IPv6 functionality. +def create_connection( + address: tuple[str, int], + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + socket_options: _TYPE_SOCKET_OPTIONS | None = None, +) -> socket.socket: + """Connect to *address* and return the socket object. + + Convenience function. Connect to *address* (a 2-tuple ``(host, + port)``) and return the socket object. Passing the optional + *timeout* parameter will set the timeout on the socket instance + before attempting to connect. If no *timeout* is supplied, the + global default timeout setting returned by :func:`socket.getdefaulttimeout` + is used. If *source_address* is set it must be a tuple of (host, port) + for the socket to bind as a source address before making the connection. + An host of '' or port 0 tells the OS to use the default. + """ + + host, port = address + if host.startswith("["): + host = host.strip("[]") + err = None + + # Using the value from allowed_gai_family() in the context of getaddrinfo lets + # us select whether to work with IPv4 DNS records, IPv6 records, or both. + # The original create_connection function always returns all records. + family = allowed_gai_family() + + try: + host.encode("idna") + except UnicodeError: + raise LocationParseError(f"'{host}', label empty or too long") from None + + for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): + af, socktype, proto, canonname, sa = res + sock = None + try: + sock = socket.socket(af, socktype, proto) + + # If provided, set socket level options before connecting. + _set_socket_options(sock, socket_options) + + if timeout is not _DEFAULT_TIMEOUT: + sock.settimeout(timeout) + if source_address: + sock.bind(source_address) + sock.connect(sa) + # Break explicitly a reference cycle + err = None + return sock + + except OSError as _: + err = _ + if sock is not None: + sock.close() + + if err is not None: + try: + raise err + finally: + # Break explicitly a reference cycle + err = None + else: + raise OSError("getaddrinfo returns an empty list") + + +def _set_socket_options( + sock: socket.socket, options: _TYPE_SOCKET_OPTIONS | None +) -> None: + if options is None: + return + + for opt in options: + sock.setsockopt(*opt) + + +def allowed_gai_family() -> socket.AddressFamily: + """This function is designed to work in the context of + getaddrinfo, where family=socket.AF_UNSPEC is the default and + will perform a DNS search for both IPv6 and IPv4 records.""" + + family = socket.AF_INET + if HAS_IPV6: + family = socket.AF_UNSPEC + return family + + +def _has_ipv6(host: str) -> bool: + """Returns True if the system can bind an IPv6 address.""" + sock = None + has_ipv6 = False + + if socket.has_ipv6: + # has_ipv6 returns true if cPython was compiled with IPv6 support. + # It does not tell us if the system has IPv6 support enabled. To + # determine that we must bind to an IPv6 address. + # https://github.com/urllib3/urllib3/pull/611 + # https://bugs.python.org/issue658327 + try: + sock = socket.socket(socket.AF_INET6) + sock.bind((host, 0)) + has_ipv6 = True + except Exception: + pass + + if sock: + sock.close() + return has_ipv6 + + +HAS_IPV6 = _has_ipv6("::1") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/proxy.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..908fc6621d0afbed16bde2c1957a5cf28d3a84d8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/proxy.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +import typing + +from .url import Url + +if typing.TYPE_CHECKING: + from ..connection import ProxyConfig + + +def connection_requires_http_tunnel( + proxy_url: Url | None = None, + proxy_config: ProxyConfig | None = None, + destination_scheme: str | None = None, +) -> bool: + """ + Returns True if the connection requires an HTTP CONNECT through the proxy. + + :param URL proxy_url: + URL of the proxy. + :param ProxyConfig proxy_config: + Proxy configuration from poolmanager.py + :param str destination_scheme: + The scheme of the destination. (i.e https, http, etc) + """ + # If we're not using a proxy, no way to use a tunnel. + if proxy_url is None: + return False + + # HTTP destinations never require tunneling, we always forward. + if destination_scheme == "http": + return False + + # Support for forwarding with HTTPS proxies and HTTPS destinations. + if ( + proxy_url.scheme == "https" + and proxy_config + and proxy_config.use_forwarding_for_https + ): + return False + + # Otherwise always use a tunnel. + return True diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/request.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/request.py new file mode 100644 index 0000000000000000000000000000000000000000..6c2372ba7e777826a4eb124ddfb54f0240b65d67 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/request.py @@ -0,0 +1,263 @@ +from __future__ import annotations + +import io +import sys +import typing +from base64 import b64encode +from enum import Enum + +from ..exceptions import UnrewindableBodyError +from .util import to_bytes + +if typing.TYPE_CHECKING: + from typing import Final + +# Pass as a value within ``headers`` to skip +# emitting some HTTP headers that are added automatically. +# The only headers that are supported are ``Accept-Encoding``, +# ``Host``, and ``User-Agent``. +SKIP_HEADER = "@@@SKIP_HEADER@@@" +SKIPPABLE_HEADERS = frozenset(["accept-encoding", "host", "user-agent"]) + +ACCEPT_ENCODING = "gzip,deflate" +try: + try: + import brotlicffi as _unused_module_brotli # type: ignore[import-not-found] # noqa: F401 + except ImportError: + import brotli as _unused_module_brotli # type: ignore[import-not-found] # noqa: F401 +except ImportError: + pass +else: + ACCEPT_ENCODING += ",br" + +try: + if sys.version_info >= (3, 14): + from compression import zstd as _unused_module_zstd # noqa: F401 + else: + from backports import zstd as _unused_module_zstd # noqa: F401 +except ImportError: + pass +else: + ACCEPT_ENCODING += ",zstd" + + +class _TYPE_FAILEDTELL(Enum): + token = 0 + + +_FAILEDTELL: Final[_TYPE_FAILEDTELL] = _TYPE_FAILEDTELL.token + +_TYPE_BODY_POSITION = typing.Union[int, _TYPE_FAILEDTELL] + +# When sending a request with these methods we aren't expecting +# a body so don't need to set an explicit 'Content-Length: 0' +# The reason we do this in the negative instead of tracking methods +# which 'should' have a body is because unknown methods should be +# treated as if they were 'POST' which *does* expect a body. +_METHODS_NOT_EXPECTING_BODY = {"GET", "HEAD", "DELETE", "TRACE", "OPTIONS", "CONNECT"} + + +def make_headers( + keep_alive: bool | None = None, + accept_encoding: bool | list[str] | str | None = None, + user_agent: str | None = None, + basic_auth: str | None = None, + proxy_basic_auth: str | None = None, + disable_cache: bool | None = None, +) -> dict[str, str]: + """ + Shortcuts for generating request headers. + + :param keep_alive: + If ``True``, adds 'connection: keep-alive' header. + + :param accept_encoding: + Can be a boolean, list, or string. + ``True`` translates to 'gzip,deflate'. If the dependencies for + Brotli (either the ``brotli`` or ``brotlicffi`` package) and/or + Zstandard (the ``backports.zstd`` package for Python before 3.14) + algorithms are installed, then their encodings are + included in the string ('br' and 'zstd', respectively). + List will get joined by comma. + String will be used as provided. + + :param user_agent: + String representing the user-agent you want, such as + "python-urllib3/0.6" + + :param basic_auth: + Colon-separated username:password string for 'authorization: basic ...' + auth header. + + :param proxy_basic_auth: + Colon-separated username:password string for 'proxy-authorization: basic ...' + auth header. + + :param disable_cache: + If ``True``, adds 'cache-control: no-cache' header. + + Example: + + .. code-block:: python + + import urllib3 + + print(urllib3.util.make_headers(keep_alive=True, user_agent="Batman/1.0")) + # {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'} + print(urllib3.util.make_headers(accept_encoding=True)) + # {'accept-encoding': 'gzip,deflate'} + """ + headers: dict[str, str] = {} + if accept_encoding: + if isinstance(accept_encoding, str): + pass + elif isinstance(accept_encoding, list): + accept_encoding = ",".join(accept_encoding) + else: + accept_encoding = ACCEPT_ENCODING + headers["accept-encoding"] = accept_encoding + + if user_agent: + headers["user-agent"] = user_agent + + if keep_alive: + headers["connection"] = "keep-alive" + + if basic_auth: + headers["authorization"] = ( + f"Basic {b64encode(basic_auth.encode('latin-1')).decode()}" + ) + + if proxy_basic_auth: + headers["proxy-authorization"] = ( + f"Basic {b64encode(proxy_basic_auth.encode('latin-1')).decode()}" + ) + + if disable_cache: + headers["cache-control"] = "no-cache" + + return headers + + +def set_file_position( + body: typing.Any, pos: _TYPE_BODY_POSITION | None +) -> _TYPE_BODY_POSITION | None: + """ + If a position is provided, move file to that point. + Otherwise, we'll attempt to record a position for future use. + """ + if pos is not None: + rewind_body(body, pos) + elif getattr(body, "tell", None) is not None: + try: + pos = body.tell() + except OSError: + # This differentiates from None, allowing us to catch + # a failed `tell()` later when trying to rewind the body. + pos = _FAILEDTELL + + return pos + + +def rewind_body(body: typing.IO[typing.AnyStr], body_pos: _TYPE_BODY_POSITION) -> None: + """ + Attempt to rewind body to a certain position. + Primarily used for request redirects and retries. + + :param body: + File-like object that supports seek. + + :param int pos: + Position to seek to in file. + """ + body_seek = getattr(body, "seek", None) + if body_seek is not None and isinstance(body_pos, int): + try: + body_seek(body_pos) + except OSError as e: + raise UnrewindableBodyError( + "An error occurred when rewinding request body for redirect/retry." + ) from e + elif body_pos is _FAILEDTELL: + raise UnrewindableBodyError( + "Unable to record file position for rewinding " + "request body during a redirect/retry." + ) + else: + raise ValueError( + f"body_pos must be of type integer, instead it was {type(body_pos)}." + ) + + +class ChunksAndContentLength(typing.NamedTuple): + chunks: typing.Iterable[bytes] | None + content_length: int | None + + +def body_to_chunks( + body: typing.Any | None, method: str, blocksize: int +) -> ChunksAndContentLength: + """Takes the HTTP request method, body, and blocksize and + transforms them into an iterable of chunks to pass to + socket.sendall() and an optional 'Content-Length' header. + + A 'Content-Length' of 'None' indicates the length of the body + can't be determined so should use 'Transfer-Encoding: chunked' + for framing instead. + """ + + chunks: typing.Iterable[bytes] | None + content_length: int | None + + # No body, we need to make a recommendation on 'Content-Length' + # based on whether that request method is expected to have + # a body or not. + if body is None: + chunks = None + if method.upper() not in _METHODS_NOT_EXPECTING_BODY: + content_length = 0 + else: + content_length = None + + # Bytes or strings become bytes + elif isinstance(body, (str, bytes)): + chunks = (to_bytes(body),) + content_length = len(chunks[0]) + + # File-like object, TODO: use seek() and tell() for length? + elif hasattr(body, "read"): + + def chunk_readable() -> typing.Iterable[bytes]: + encode = isinstance(body, io.TextIOBase) + while True: + datablock = body.read(blocksize) + if not datablock: + break + if encode: + datablock = datablock.encode("utf-8") + yield datablock + + chunks = chunk_readable() + content_length = None + + # Otherwise we need to start checking via duck-typing. + else: + try: + # Check if the body implements the buffer API. + mv = memoryview(body) + except TypeError: + try: + # Check if the body is an iterable + chunks = iter(body) + content_length = None + except TypeError: + raise TypeError( + f"'body' must be a bytes-like object, file-like " + f"object, or iterable. Instead was {body!r}" + ) from None + else: + # Since it implements the buffer API can be passed directly to socket.sendall() + chunks = (body,) + content_length = mv.nbytes + + return ChunksAndContentLength(chunks=chunks, content_length=content_length) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/response.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/response.py new file mode 100644 index 0000000000000000000000000000000000000000..0f4578696fa2e17a900c6890ec26d65e860b0b72 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/response.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +import http.client as httplib +from email.errors import MultipartInvariantViolationDefect, StartBoundaryNotFoundDefect + +from ..exceptions import HeaderParsingError + + +def is_fp_closed(obj: object) -> bool: + """ + Checks whether a given file-like object is closed. + + :param obj: + The file-like object to check. + """ + + try: + # Check `isclosed()` first, in case Python3 doesn't set `closed`. + # GH Issue #928 + return obj.isclosed() # type: ignore[no-any-return, attr-defined] + except AttributeError: + pass + + try: + # Check via the official file-like-object way. + return obj.closed # type: ignore[no-any-return, attr-defined] + except AttributeError: + pass + + try: + # Check if the object is a container for another file-like object that + # gets released on exhaustion (e.g. HTTPResponse). + return obj.fp is None # type: ignore[attr-defined] + except AttributeError: + pass + + raise ValueError("Unable to determine whether fp is closed.") + + +def assert_header_parsing(headers: httplib.HTTPMessage) -> None: + """ + Asserts whether all headers have been successfully parsed. + Extracts encountered errors from the result of parsing headers. + + Only works on Python 3. + + :param http.client.HTTPMessage headers: Headers to verify. + + :raises urllib3.exceptions.HeaderParsingError: + If parsing errors are found. + """ + + # This will fail silently if we pass in the wrong kind of parameter. + # To make debugging easier add an explicit check. + if not isinstance(headers, httplib.HTTPMessage): + raise TypeError(f"expected httplib.Message, got {type(headers)}.") + + unparsed_data = None + + # get_payload is actually email.message.Message.get_payload; + # we're only interested in the result if it's not a multipart message + if not headers.is_multipart(): + payload = headers.get_payload() + + if isinstance(payload, (bytes, str)): + unparsed_data = payload + + # httplib is assuming a response body is available + # when parsing headers even when httplib only sends + # header data to parse_headers() This results in + # defects on multipart responses in particular. + # See: https://github.com/urllib3/urllib3/issues/800 + + # So we ignore the following defects: + # - StartBoundaryNotFoundDefect: + # The claimed start boundary was never found. + # - MultipartInvariantViolationDefect: + # A message claimed to be a multipart but no subparts were found. + defects = [ + defect + for defect in headers.defects + if not isinstance( + defect, (StartBoundaryNotFoundDefect, MultipartInvariantViolationDefect) + ) + ] + + if defects or unparsed_data: + raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data) + + +def is_response_to_head(response: httplib.HTTPResponse) -> bool: + """ + Checks whether the request of a response has been a HEAD-request. + + :param http.client.HTTPResponse response: + Response to check if the originating request + used 'HEAD' as a method. + """ + # FIXME: Can we do this somehow without accessing private httplib _method? + method_str = response._method # type: str # type: ignore[attr-defined] + return method_str.upper() == "HEAD" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/retry.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/retry.py new file mode 100644 index 0000000000000000000000000000000000000000..7649898e1d9930724a456c1c6fdecb66e078b4cc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/retry.py @@ -0,0 +1,557 @@ +from __future__ import annotations + +import email +import logging +import random +import re +import time +import typing +from itertools import takewhile +from types import TracebackType + +from ..exceptions import ( + ConnectTimeoutError, + InvalidHeader, + MaxRetryError, + ProtocolError, + ProxyError, + ReadTimeoutError, + ResponseError, +) +from .util import reraise + +if typing.TYPE_CHECKING: + from typing_extensions import Self + + from ..connectionpool import ConnectionPool + from ..response import BaseHTTPResponse + +log = logging.getLogger(__name__) + + +# Data structure for representing the metadata of requests that result in a retry. +class RequestHistory(typing.NamedTuple): + method: str | None + url: str | None + error: Exception | None + status: int | None + redirect_location: str | None + + +class Retry: + """Retry configuration. + + Each retry attempt will create a new Retry object with updated values, so + they can be safely reused. + + Retries can be defined as a default for a pool: + + .. code-block:: python + + retries = Retry(connect=5, read=2, redirect=5) + http = PoolManager(retries=retries) + response = http.request("GET", "https://example.com/") + + Or per-request (which overrides the default for the pool): + + .. code-block:: python + + response = http.request("GET", "https://example.com/", retries=Retry(10)) + + Retries can be disabled by passing ``False``: + + .. code-block:: python + + response = http.request("GET", "https://example.com/", retries=False) + + Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless + retries are disabled, in which case the causing exception will be raised. + + :param int total: + Total number of retries to allow. Takes precedence over other counts. + + Set to ``None`` to remove this constraint and fall back on other + counts. + + Set to ``0`` to fail on the first retry. + + Set to ``False`` to disable and imply ``raise_on_redirect=False``. + + :param int connect: + How many connection-related errors to retry on. + + These are errors raised before the request is sent to the remote server, + which we assume has not triggered the server to process the request. + + Set to ``0`` to fail on the first retry of this type. + + :param int read: + How many times to retry on read errors. + + These errors are raised after the request was sent to the server, so the + request may have side-effects. + + Set to ``0`` to fail on the first retry of this type. + + :param int redirect: + How many redirects to perform. Limit this to avoid infinite redirect + loops. + + A redirect is a HTTP response with a status code 301, 302, 303, 307 or + 308. + + Set to ``0`` to fail on the first retry of this type. + + Set to ``False`` to disable and imply ``raise_on_redirect=False``. + + :param int status: + How many times to retry on bad status codes. + + These are retries made on responses, where status code matches + ``status_forcelist``. + + Set to ``0`` to fail on the first retry of this type. + + :param int other: + How many times to retry on other errors. + + Other errors are errors that are not connect, read, redirect or status errors. + These errors might be raised after the request was sent to the server, so the + request might have side-effects. + + Set to ``0`` to fail on the first retry of this type. + + If ``total`` is not set, it's a good idea to set this to 0 to account + for unexpected edge cases and avoid infinite retry loops. + + :param Collection allowed_methods: + Set of uppercased HTTP method verbs that we should retry on. + + By default, we only retry on methods which are considered to be + idempotent (multiple requests with the same parameters end with the + same state). See :attr:`Retry.DEFAULT_ALLOWED_METHODS`. + + Set to a ``None`` value to retry on any verb. + + :param Collection status_forcelist: + A set of integer HTTP status codes that we should force a retry on. + A retry is initiated if the request method is in ``allowed_methods`` + and the response status code is in ``status_forcelist``. + + By default, this is disabled with ``None``. + + :param float backoff_factor: + A backoff factor to apply between attempts after the second try + (most errors are resolved immediately by a second try without a + delay). urllib3 will sleep for:: + + {backoff factor} * (2 ** ({number of previous retries})) + + seconds. If `backoff_jitter` is non-zero, this sleep is extended by:: + + random.uniform(0, {backoff jitter}) + + seconds. For example, if the backoff_factor is 0.1, then :func:`Retry.sleep` will + sleep for [0.0s, 0.2s, 0.4s, 0.8s, ...] between retries. No backoff will ever + be longer than `backoff_max`. + + By default, backoff is disabled (factor set to 0). + + :param float backoff_max: + The maximum backoff time (in seconds) between retry attempts. + This value caps the computed backoff from `backoff_factor`. + + :param float backoff_jitter: + Random jitter amount (in seconds) added to the computed backoff. + Jitter is sampled uniformly from `0` to `backoff_jitter`. + + :param bool raise_on_redirect: Whether, if the number of redirects is + exhausted, to raise a MaxRetryError, or to return a response with a + response code in the 3xx range. + + :param bool raise_on_status: Similar meaning to ``raise_on_redirect``: + whether we should raise an exception, or return a response, + if status falls in ``status_forcelist`` range and retries have + been exhausted. + + :param tuple history: The history of the request encountered during + each call to :meth:`~Retry.increment`. The list is in the order + the requests occurred. Each list item is of class :class:`RequestHistory`. + + :param bool respect_retry_after_header: + Whether to respect Retry-After header on status codes defined as + :attr:`Retry.RETRY_AFTER_STATUS_CODES` or not. + + :param Collection remove_headers_on_redirect: + Sequence of headers to remove from the request when a response + indicating a redirect is returned before firing off the redirected + request. + + :param int retry_after_max: Number of seconds to allow as the maximum for + Retry-After headers. Defaults to :attr:`Retry.DEFAULT_RETRY_AFTER_MAX`. + Any Retry-After headers larger than this value will be limited to this + value. + """ + + #: Default methods to be used for ``allowed_methods`` + DEFAULT_ALLOWED_METHODS = frozenset( + ["HEAD", "GET", "PUT", "DELETE", "OPTIONS", "TRACE"] + ) + + #: Default status codes to be used for ``status_forcelist`` + RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503]) + + #: Default headers to be used for ``remove_headers_on_redirect`` + DEFAULT_REMOVE_HEADERS_ON_REDIRECT = frozenset( + ["Cookie", "Authorization", "Proxy-Authorization"] + ) + + #: Default maximum backoff time. + DEFAULT_BACKOFF_MAX = 120 + + # This is undocumented in the RFC. Setting to 6 hours matches other popular libraries. + #: Default maximum allowed value for Retry-After headers in seconds + DEFAULT_RETRY_AFTER_MAX: typing.Final[int] = 21600 + + # Backward compatibility; assigned outside of the class. + DEFAULT: typing.ClassVar[Retry] + + def __init__( + self, + total: bool | int | None = 10, + connect: int | None = None, + read: int | None = None, + redirect: bool | int | None = None, + status: int | None = None, + other: int | None = None, + allowed_methods: typing.Collection[str] | None = DEFAULT_ALLOWED_METHODS, + status_forcelist: typing.Collection[int] | None = None, + backoff_factor: float = 0, + backoff_max: float = DEFAULT_BACKOFF_MAX, + raise_on_redirect: bool = True, + raise_on_status: bool = True, + history: tuple[RequestHistory, ...] | None = None, + respect_retry_after_header: bool = True, + remove_headers_on_redirect: typing.Collection[ + str + ] = DEFAULT_REMOVE_HEADERS_ON_REDIRECT, + backoff_jitter: float = 0.0, + retry_after_max: int = DEFAULT_RETRY_AFTER_MAX, + ) -> None: + self.total = total + self.connect = connect + self.read = read + self.status = status + self.other = other + + if redirect is False or total is False: + redirect = 0 + raise_on_redirect = False + + self.redirect = redirect + self.status_forcelist = status_forcelist or set() + self.allowed_methods = allowed_methods + self.backoff_factor = backoff_factor + self.backoff_max = backoff_max + self.retry_after_max = retry_after_max + self.raise_on_redirect = raise_on_redirect + self.raise_on_status = raise_on_status + self.history = history or () + self.respect_retry_after_header = respect_retry_after_header + self.remove_headers_on_redirect = frozenset( + h.lower() for h in remove_headers_on_redirect + ) + self.backoff_jitter = backoff_jitter + + def new(self, **kw: typing.Any) -> Self: + params = dict( + total=self.total, + connect=self.connect, + read=self.read, + redirect=self.redirect, + status=self.status, + other=self.other, + allowed_methods=self.allowed_methods, + status_forcelist=self.status_forcelist, + backoff_factor=self.backoff_factor, + backoff_max=self.backoff_max, + retry_after_max=self.retry_after_max, + raise_on_redirect=self.raise_on_redirect, + raise_on_status=self.raise_on_status, + history=self.history, + remove_headers_on_redirect=self.remove_headers_on_redirect, + respect_retry_after_header=self.respect_retry_after_header, + backoff_jitter=self.backoff_jitter, + ) + + params.update(kw) + return type(self)(**params) # type: ignore[arg-type] + + @classmethod + def from_int( + cls, + retries: Retry | bool | int | None, + redirect: bool | int | None = True, + default: Retry | bool | int | None = None, + ) -> Retry: + """Backwards-compatibility for the old retries format.""" + if retries is None: + retries = default if default is not None else cls.DEFAULT + + if isinstance(retries, Retry): + return retries + + redirect = bool(redirect) and None + new_retries = cls(retries, redirect=redirect) + log.debug("Converted retries value: %r -> %r", retries, new_retries) + return new_retries + + def get_backoff_time(self) -> float: + """Formula for computing the current backoff + + :rtype: float + """ + # We want to consider only the last consecutive errors sequence (Ignore redirects). + consecutive_errors_len = len( + list( + takewhile(lambda x: x.redirect_location is None, reversed(self.history)) + ) + ) + if consecutive_errors_len <= 1: + return 0 + + backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1)) + if self.backoff_jitter != 0.0: + backoff_value += random.random() * self.backoff_jitter + return float(max(0, min(self.backoff_max, backoff_value))) + + def parse_retry_after(self, retry_after: str) -> float: + seconds: float + # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4 + if re.match(r"^\s*[0-9]+\s*$", retry_after): + seconds = int(retry_after) + else: + retry_date_tuple = email.utils.parsedate_tz(retry_after) + if retry_date_tuple is None: + raise InvalidHeader(f"Invalid Retry-After header: {retry_after}") + + retry_date = email.utils.mktime_tz(retry_date_tuple) + seconds = retry_date - time.time() + + seconds = max(seconds, 0) + + # Check the seconds do not exceed the specified maximum + if seconds > self.retry_after_max: + seconds = self.retry_after_max + + return seconds + + def get_retry_after(self, response: BaseHTTPResponse) -> float | None: + """Get the value of Retry-After in seconds.""" + + retry_after = response.headers.get("Retry-After") + + if retry_after is None: + return None + + return self.parse_retry_after(retry_after) + + def sleep_for_retry(self, response: BaseHTTPResponse) -> bool: + retry_after = self.get_retry_after(response) + if retry_after: + time.sleep(retry_after) + return True + + return False + + def _sleep_backoff(self) -> None: + backoff = self.get_backoff_time() + if backoff <= 0: + return + time.sleep(backoff) + + def sleep(self, response: BaseHTTPResponse | None = None) -> None: + """Sleep between retry attempts. + + This method will respect a server's ``Retry-After`` response header + and sleep the duration of the time requested. If that is not present, it + will use an exponential backoff. By default, the backoff factor is 0 and + this method will return immediately. + """ + + if self.respect_retry_after_header and response: + slept = self.sleep_for_retry(response) + if slept: + return + + self._sleep_backoff() + + def _is_connection_error(self, err: Exception) -> bool: + """Errors when we're fairly sure that the server did not receive the + request, so it should be safe to retry. + """ + if isinstance(err, ProxyError): + err = err.original_error + return isinstance(err, ConnectTimeoutError) + + def _is_read_error(self, err: Exception) -> bool: + """Errors that occur after the request has been started, so we should + assume that the server began processing it. + """ + return isinstance(err, (ReadTimeoutError, ProtocolError)) + + def _is_method_retryable(self, method: str) -> bool: + """Checks if a given HTTP method should be retried upon, depending if + it is included in the allowed_methods + """ + if self.allowed_methods and method.upper() not in self.allowed_methods: + return False + return True + + def is_retry( + self, method: str, status_code: int, has_retry_after: bool = False + ) -> bool: + """Is this method/status code retryable? (Based on allowlists and control + variables such as the number of total retries to allow, whether to + respect the Retry-After header, whether this header is present, and + whether the returned status code is on the list of status codes to + be retried upon on the presence of the aforementioned header) + """ + if not self._is_method_retryable(method): + return False + + if self.status_forcelist and status_code in self.status_forcelist: + return True + + return bool( + self.total + and self.respect_retry_after_header + and has_retry_after + and (status_code in self.RETRY_AFTER_STATUS_CODES) + ) + + def is_exhausted(self) -> bool: + """Are we out of retries?""" + retry_counts = [ + x + for x in ( + self.total, + self.connect, + self.read, + self.redirect, + self.status, + self.other, + ) + if x + ] + if not retry_counts: + return False + + return min(retry_counts) < 0 + + def increment( + self, + method: str | None = None, + url: str | None = None, + response: BaseHTTPResponse | None = None, + error: Exception | None = None, + _pool: ConnectionPool | None = None, + _stacktrace: TracebackType | None = None, + ) -> Self: + """Return a new Retry object with incremented retry counters. + + :param response: A response object, or None, if the server did not + return a response. + :type response: :class:`~urllib3.response.BaseHTTPResponse` + :param Exception error: An error encountered during the request, or + None if the response was received successfully. + + :return: A new ``Retry`` object. + """ + if self.total is False and error: + # Disabled, indicate to re-raise the error. + raise reraise(type(error), error, _stacktrace) + + total = self.total + if total is not None: + total -= 1 + + connect = self.connect + read = self.read + redirect = self.redirect + status_count = self.status + other = self.other + cause = "unknown" + status = None + redirect_location = None + + if error and self._is_connection_error(error): + # Connect retry? + if connect is False: + raise reraise(type(error), error, _stacktrace) + elif connect is not None: + connect -= 1 + + elif error and self._is_read_error(error): + # Read retry? + if read is False or method is None or not self._is_method_retryable(method): + raise reraise(type(error), error, _stacktrace) + elif read is not None: + read -= 1 + + elif error: + # Other retry? + if other is not None: + other -= 1 + + elif response and response.get_redirect_location(): + # Redirect retry? + if redirect is not None: + redirect -= 1 + cause = "too many redirects" + response_redirect_location = response.get_redirect_location() + if response_redirect_location: + redirect_location = response_redirect_location + status = response.status + + else: + # Incrementing because of a server error like a 500 in + # status_forcelist and the given method is in the allowed_methods + cause = ResponseError.GENERIC_ERROR + if response and response.status: + if status_count is not None: + status_count -= 1 + cause = ResponseError.SPECIFIC_ERROR.format(status_code=response.status) + status = response.status + + history = self.history + ( + RequestHistory(method, url, error, status, redirect_location), + ) + + new_retry = self.new( + total=total, + connect=connect, + read=read, + redirect=redirect, + status=status_count, + other=other, + history=history, + ) + + if new_retry.is_exhausted(): + reason = error or ResponseError(cause) + raise MaxRetryError(_pool, url, reason) from reason # type: ignore[arg-type] + + log.debug("Incremented Retry for (url='%s'): %r", url, new_retry) + + return new_retry + + def __repr__(self) -> str: + return ( + f"{type(self).__name__}(total={self.total}, connect={self.connect}, " + f"read={self.read}, redirect={self.redirect}, status={self.status})" + ) + + +# For backwards compatibility (equivalent to pre-v1.9): +Retry.DEFAULT = Retry(3) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/ssl_.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/ssl_.py new file mode 100644 index 0000000000000000000000000000000000000000..e66549a76c4b5821e639e5facfeb63dd1a39d543 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/ssl_.py @@ -0,0 +1,477 @@ +from __future__ import annotations + +import hashlib +import hmac +import os +import socket +import sys +import typing +import warnings +from binascii import unhexlify + +from ..exceptions import ProxySchemeUnsupported, SSLError +from .url import _BRACELESS_IPV6_ADDRZ_RE, _IPV4_RE + +SSLContext = None +SSLTransport = None +HAS_NEVER_CHECK_COMMON_NAME = False +IS_PYOPENSSL = False +ALPN_PROTOCOLS = ["http/1.1"] + +_TYPE_VERSION_INFO = tuple[int, int, int, str, int] + +# Maps the length of a digest to a possible hash function producing this digest +HASHFUNC_MAP = { + length: getattr(hashlib, algorithm, None) + for length, algorithm in ((32, "md5"), (40, "sha1"), (64, "sha256")) +} + + +def _is_has_never_check_common_name_reliable( + openssl_version: str, +) -> bool: + # As of May 2023, all released versions of LibreSSL fail to reject certificates with + # only common names, see https://github.com/urllib3/urllib3/pull/3024 + is_openssl = openssl_version.startswith("OpenSSL ") + + return is_openssl + + +if typing.TYPE_CHECKING: + from ssl import VerifyMode + from typing import TypedDict + + from .ssltransport import SSLTransport as SSLTransportType + + class _TYPE_PEER_CERT_RET_DICT(TypedDict, total=False): + subjectAltName: tuple[tuple[str, str], ...] + subject: tuple[tuple[tuple[str, str], ...], ...] + serialNumber: str + + +# Mapping from 'ssl.PROTOCOL_TLSX' to 'TLSVersion.X' +_SSL_VERSION_TO_TLS_VERSION: dict[int, int] = {} + +try: # Do we have ssl at all? + import ssl + from ssl import ( # type: ignore[assignment] + CERT_REQUIRED, + HAS_NEVER_CHECK_COMMON_NAME, + OP_NO_COMPRESSION, + OP_NO_TICKET, + OPENSSL_VERSION, + PROTOCOL_TLS, + PROTOCOL_TLS_CLIENT, + VERIFY_X509_PARTIAL_CHAIN, + VERIFY_X509_STRICT, + OP_NO_SSLv2, + OP_NO_SSLv3, + SSLContext, + TLSVersion, + ) + + PROTOCOL_SSLv23 = PROTOCOL_TLS + + # Setting SSLContext.hostname_checks_common_name = False didn't work with + # LibreSSL, check details in the used function. + if HAS_NEVER_CHECK_COMMON_NAME and not _is_has_never_check_common_name_reliable( + OPENSSL_VERSION, + ): # Defensive: + HAS_NEVER_CHECK_COMMON_NAME = False + + # Need to be careful here in case old TLS versions get + # removed in future 'ssl' module implementations. + for attr in ("TLSv1", "TLSv1_1", "TLSv1_2"): + try: + _SSL_VERSION_TO_TLS_VERSION[getattr(ssl, f"PROTOCOL_{attr}")] = getattr( + TLSVersion, attr + ) + except AttributeError: # Defensive: + continue + + from .ssltransport import SSLTransport # type: ignore[assignment] +except ImportError: + OP_NO_COMPRESSION = 0x20000 # type: ignore[assignment, misc] + OP_NO_TICKET = 0x4000 # type: ignore[assignment, misc] + OP_NO_SSLv2 = 0x1000000 # type: ignore[assignment, misc] + OP_NO_SSLv3 = 0x2000000 # type: ignore[assignment, misc] + PROTOCOL_SSLv23 = PROTOCOL_TLS = 2 # type: ignore[assignment, misc] + PROTOCOL_TLS_CLIENT = 16 # type: ignore[assignment, misc] + VERIFY_X509_PARTIAL_CHAIN = 0x80000 # type: ignore[assignment,misc] + VERIFY_X509_STRICT = 0x20 # type: ignore[assignment, misc] + + +_TYPE_PEER_CERT_RET = typing.Union["_TYPE_PEER_CERT_RET_DICT", bytes, None] + + +def assert_fingerprint(cert: bytes | None, fingerprint: str) -> None: + """ + Checks if given fingerprint matches the supplied certificate. + + :param cert: + Certificate as bytes object. + :param fingerprint: + Fingerprint as string of hexdigits, can be interspersed by colons. + """ + + if cert is None: + raise SSLError("No certificate for the peer.") + + fingerprint = fingerprint.replace(":", "").lower() + digest_length = len(fingerprint) + if digest_length not in HASHFUNC_MAP: + raise SSLError(f"Fingerprint of invalid length: {fingerprint}") + hashfunc = HASHFUNC_MAP.get(digest_length) + if hashfunc is None: + raise SSLError( + f"Hash function implementation unavailable for fingerprint length: {digest_length}" + ) + + # We need encode() here for py32; works on py2 and p33. + fingerprint_bytes = unhexlify(fingerprint.encode()) + + cert_digest = hashfunc(cert).digest() + + if not hmac.compare_digest(cert_digest, fingerprint_bytes): + raise SSLError( + f'Fingerprints did not match. Expected "{fingerprint}", got "{cert_digest.hex()}"' + ) + + +def resolve_cert_reqs(candidate: None | int | str) -> VerifyMode: + """ + Resolves the argument to a numeric constant, which can be passed to + the wrap_socket function/method from the ssl module. + Defaults to :data:`ssl.CERT_REQUIRED`. + If given a string it is assumed to be the name of the constant in the + :mod:`ssl` module or its abbreviation. + (So you can specify `REQUIRED` instead of `CERT_REQUIRED`. + If it's neither `None` nor a string we assume it is already the numeric + constant which can directly be passed to wrap_socket. + """ + if candidate is None: + return CERT_REQUIRED + + if isinstance(candidate, str): + res = getattr(ssl, candidate, None) + if res is None: + res = getattr(ssl, "CERT_" + candidate) + return res # type: ignore[no-any-return] + + return candidate # type: ignore[return-value] + + +def resolve_ssl_version(candidate: None | int | str) -> int: + """ + like resolve_cert_reqs + """ + if candidate is None: + return PROTOCOL_TLS + + if isinstance(candidate, str): + res = getattr(ssl, candidate, None) + if res is None: + res = getattr(ssl, "PROTOCOL_" + candidate) + return typing.cast(int, res) + + return candidate + + +def create_urllib3_context( + ssl_version: int | None = None, + cert_reqs: int | None = None, + options: int | None = None, + ciphers: str | None = None, + ssl_minimum_version: int | None = None, + ssl_maximum_version: int | None = None, + verify_flags: int | None = None, +) -> ssl.SSLContext: + """Creates and configures an :class:`ssl.SSLContext` instance for use with urllib3. + + :param ssl_version: + The desired protocol version to use. This will default to + PROTOCOL_SSLv23 which will negotiate the highest protocol that both + the server and your installation of OpenSSL support. + + This parameter is deprecated instead use 'ssl_minimum_version'. + :param ssl_minimum_version: + The minimum version of TLS to be used. Use the 'ssl.TLSVersion' enum for specifying the value. + :param ssl_maximum_version: + The maximum version of TLS to be used. Use the 'ssl.TLSVersion' enum for specifying the value. + Not recommended to set to anything other than 'ssl.TLSVersion.MAXIMUM_SUPPORTED' which is the + default value. + :param cert_reqs: + Whether to require the certificate verification. This defaults to + ``ssl.CERT_REQUIRED``. + :param options: + Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, + ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``, and ``ssl.OP_NO_TICKET``. + :param ciphers: + Which cipher suites to allow the server to select. Defaults to either system configured + ciphers if OpenSSL 1.1.1+, otherwise uses a secure default set of ciphers. + :param verify_flags: + The flags for certificate verification operations. These default to + ``ssl.VERIFY_X509_PARTIAL_CHAIN`` and ``ssl.VERIFY_X509_STRICT`` for Python 3.13+. + :returns: + Constructed SSLContext object with specified options + :rtype: SSLContext + """ + if SSLContext is None: + raise TypeError("Can't create an SSLContext object without an ssl module") + + # This means 'ssl_version' was specified as an exact value. + if ssl_version not in (None, PROTOCOL_TLS, PROTOCOL_TLS_CLIENT): + # Disallow setting 'ssl_version' and 'ssl_minimum|maximum_version' + # to avoid conflicts. + if ssl_minimum_version is not None or ssl_maximum_version is not None: + raise ValueError( + "Can't specify both 'ssl_version' and either " + "'ssl_minimum_version' or 'ssl_maximum_version'" + ) + + # 'ssl_version' is deprecated and will be removed in the future. + else: + # Use 'ssl_minimum_version' and 'ssl_maximum_version' instead. + ssl_minimum_version = _SSL_VERSION_TO_TLS_VERSION.get( + ssl_version, TLSVersion.MINIMUM_SUPPORTED + ) + ssl_maximum_version = _SSL_VERSION_TO_TLS_VERSION.get( + ssl_version, TLSVersion.MAXIMUM_SUPPORTED + ) + + # This warning message is pushing users to use 'ssl_minimum_version' + # instead of both min/max. Best practice is to only set the minimum version and + # keep the maximum version to be it's default value: 'TLSVersion.MAXIMUM_SUPPORTED' + warnings.warn( + "'ssl_version' option is deprecated and will be " + "removed in urllib3 v3.0. Instead use 'ssl_minimum_version'", + category=FutureWarning, + stacklevel=2, + ) + + context = SSLContext(PROTOCOL_TLS_CLIENT) + if ssl_minimum_version is not None: + context.minimum_version = ssl_minimum_version + else: # pyOpenSSL defaults to 'MINIMUM_SUPPORTED' so explicitly set TLSv1.2 here + context.minimum_version = TLSVersion.TLSv1_2 + + if ssl_maximum_version is not None: + context.maximum_version = ssl_maximum_version + + # Unless we're given ciphers defer to either system ciphers in + # the case of OpenSSL 1.1.1+ or use our own secure default ciphers. + if ciphers: + context.set_ciphers(ciphers) + + # Setting the default here, as we may have no ssl module on import + cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs + + if options is None: + options = 0 + # SSLv2 is easily broken and is considered harmful and dangerous + options |= OP_NO_SSLv2 + # SSLv3 has several problems and is now dangerous + options |= OP_NO_SSLv3 + # Disable compression to prevent CRIME attacks for OpenSSL 1.0+ + # (issue #309) + options |= OP_NO_COMPRESSION + # TLSv1.2 only. Unless set explicitly, do not request tickets. + # This may save some bandwidth on wire, and although the ticket is encrypted, + # there is a risk associated with it being on wire, + # if the server is not rotating its ticketing keys properly. + options |= OP_NO_TICKET + + context.options |= options + + if verify_flags is None: + verify_flags = 0 + # In Python 3.13+ ssl.create_default_context() sets VERIFY_X509_PARTIAL_CHAIN + # and VERIFY_X509_STRICT so we do the same + if sys.version_info >= (3, 13): + verify_flags |= VERIFY_X509_PARTIAL_CHAIN + verify_flags |= VERIFY_X509_STRICT + + context.verify_flags |= verify_flags + + # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is + # necessary for conditional client cert authentication with TLS 1.3. + # The attribute is None for OpenSSL <= 1.1.0 or does not exist when using + # an SSLContext created by pyOpenSSL. + if getattr(context, "post_handshake_auth", None) is not None: + context.post_handshake_auth = True + + # The order of the below lines setting verify_mode and check_hostname + # matter due to safe-guards SSLContext has to prevent an SSLContext with + # check_hostname=True, verify_mode=NONE/OPTIONAL. + # We always set 'check_hostname=False' for pyOpenSSL so we rely on our own + # 'ssl.match_hostname()' implementation. + if cert_reqs == ssl.CERT_REQUIRED and not IS_PYOPENSSL: + context.verify_mode = cert_reqs + context.check_hostname = True + else: + context.check_hostname = False + context.verify_mode = cert_reqs + + context.hostname_checks_common_name = False + + if "SSLKEYLOGFILE" in os.environ: + sslkeylogfile = os.path.expandvars(os.environ.get("SSLKEYLOGFILE")) + else: + sslkeylogfile = None + if sslkeylogfile: + context.keylog_filename = sslkeylogfile + + return context + + +@typing.overload +def ssl_wrap_socket( + sock: socket.socket, + keyfile: str | None = ..., + certfile: str | None = ..., + cert_reqs: int | None = ..., + ca_certs: str | None = ..., + server_hostname: str | None = ..., + ssl_version: int | None = ..., + ciphers: str | None = ..., + ssl_context: ssl.SSLContext | None = ..., + ca_cert_dir: str | None = ..., + key_password: str | None = ..., + ca_cert_data: None | str | bytes = ..., + tls_in_tls: typing.Literal[False] = ..., +) -> ssl.SSLSocket: ... + + +@typing.overload +def ssl_wrap_socket( + sock: socket.socket, + keyfile: str | None = ..., + certfile: str | None = ..., + cert_reqs: int | None = ..., + ca_certs: str | None = ..., + server_hostname: str | None = ..., + ssl_version: int | None = ..., + ciphers: str | None = ..., + ssl_context: ssl.SSLContext | None = ..., + ca_cert_dir: str | None = ..., + key_password: str | None = ..., + ca_cert_data: None | str | bytes = ..., + tls_in_tls: bool = ..., +) -> ssl.SSLSocket | SSLTransportType: ... + + +def ssl_wrap_socket( + sock: socket.socket, + keyfile: str | None = None, + certfile: str | None = None, + cert_reqs: int | None = None, + ca_certs: str | None = None, + server_hostname: str | None = None, + ssl_version: int | None = None, + ciphers: str | None = None, + ssl_context: ssl.SSLContext | None = None, + ca_cert_dir: str | None = None, + key_password: str | None = None, + ca_cert_data: None | str | bytes = None, + tls_in_tls: bool = False, +) -> ssl.SSLSocket | SSLTransportType: + """ + All arguments except for server_hostname, ssl_context, tls_in_tls, ca_cert_data and + ca_cert_dir have the same meaning as they do when using + :func:`ssl.create_default_context`, :meth:`ssl.SSLContext.load_cert_chain`, + :meth:`ssl.SSLContext.set_ciphers` and :meth:`ssl.SSLContext.wrap_socket`. + + :param server_hostname: + When SNI is supported, the expected hostname of the certificate + :param ssl_context: + A pre-made :class:`SSLContext` object. If none is provided, one will + be created using :func:`create_urllib3_context`. + :param ciphers: + A string of ciphers we wish the client to support. + :param ca_cert_dir: + A directory containing CA certificates in multiple separate files, as + supported by OpenSSL's -CApath flag or the capath argument to + SSLContext.load_verify_locations(). + :param key_password: + Optional password if the keyfile is encrypted. + :param ca_cert_data: + Optional string containing CA certificates in PEM format suitable for + passing as the cadata parameter to SSLContext.load_verify_locations() + :param tls_in_tls: + Use SSLTransport to wrap the existing socket. + """ + context = ssl_context + if context is None: + # Note: This branch of code and all the variables in it are only used in tests. + # We should consider deprecating and removing this code. + context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers) + + if ca_certs or ca_cert_dir or ca_cert_data: + try: + context.load_verify_locations(ca_certs, ca_cert_dir, ca_cert_data) + except OSError as e: + raise SSLError(e) from e + + elif ssl_context is None and hasattr(context, "load_default_certs"): + # try to load OS default certs; works well on Windows. + context.load_default_certs() + + # Attempt to detect if we get the goofy behavior of the + # keyfile being encrypted and OpenSSL asking for the + # passphrase via the terminal and instead error out. + if keyfile and key_password is None and _is_key_file_encrypted(keyfile): + raise SSLError("Client private key is encrypted, password is required") + + if certfile: + if key_password is None: + context.load_cert_chain(certfile, keyfile) + else: + context.load_cert_chain(certfile, keyfile, key_password) + + context.set_alpn_protocols(ALPN_PROTOCOLS) + + ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls, server_hostname) + return ssl_sock + + +def is_ipaddress(hostname: str | bytes) -> bool: + """Detects whether the hostname given is an IPv4 or IPv6 address. + Also detects IPv6 addresses with Zone IDs. + + :param str hostname: Hostname to examine. + :return: True if the hostname is an IP address, False otherwise. + """ + if isinstance(hostname, bytes): + # IDN A-label bytes are ASCII compatible. + hostname = hostname.decode("ascii") + return bool(_IPV4_RE.match(hostname) or _BRACELESS_IPV6_ADDRZ_RE.match(hostname)) + + +def _is_key_file_encrypted(key_file: str) -> bool: + """Detects if a key file is encrypted or not.""" + with open(key_file) as f: + for line in f: + # Look for Proc-Type: 4,ENCRYPTED + if "ENCRYPTED" in line: + return True + + return False + + +def _ssl_wrap_socket_impl( + sock: socket.socket, + ssl_context: ssl.SSLContext, + tls_in_tls: bool, + server_hostname: str | None = None, +) -> ssl.SSLSocket | SSLTransportType: + if tls_in_tls: + if not SSLTransport: + # Import error, ssl is not available. + raise ProxySchemeUnsupported( + "TLS in TLS requires support for the 'ssl' module" + ) + + SSLTransport._validate_ssl_context_for_tls_in_tls(ssl_context) + return SSLTransport(sock, ssl_context, server_hostname) + + return ssl_context.wrap_socket(sock, server_hostname=server_hostname) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/ssl_match_hostname.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/ssl_match_hostname.py new file mode 100644 index 0000000000000000000000000000000000000000..94994f25ae1570211c0b98353790f669ef4585fa --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/ssl_match_hostname.py @@ -0,0 +1,153 @@ +"""The match_hostname() function from Python 3.5, essential when using SSL.""" + +# Note: This file is under the PSF license as the code comes from the python +# stdlib. http://docs.python.org/3/license.html +# It is modified to remove commonName support. + +from __future__ import annotations + +import ipaddress +import re +import typing +from ipaddress import IPv4Address, IPv6Address + +if typing.TYPE_CHECKING: + from .ssl_ import _TYPE_PEER_CERT_RET_DICT + +__version__ = "3.5.0.1" + + +class CertificateError(ValueError): + pass + + +def _dnsname_match( + dn: typing.Any, hostname: str, max_wildcards: int = 1 +) -> typing.Match[str] | None | bool: + """Matching according to RFC 6125, section 6.4.3 + + http://tools.ietf.org/html/rfc6125#section-6.4.3 + """ + pats = [] + if not dn: + return False + + # Ported from python3-syntax: + # leftmost, *remainder = dn.split(r'.') + parts = dn.split(r".") + leftmost = parts[0] + remainder = parts[1:] + + wildcards = leftmost.count("*") + if wildcards > max_wildcards: + # Issue #17980: avoid denials of service by refusing more + # than one wildcard per fragment. A survey of established + # policy among SSL implementations showed it to be a + # reasonable choice. + raise CertificateError( + "too many wildcards in certificate DNS name: " + repr(dn) + ) + + # speed up common case w/o wildcards + if not wildcards: + return bool(dn.lower() == hostname.lower()) + + # RFC 6125, section 6.4.3, subitem 1. + # The client SHOULD NOT attempt to match a presented identifier in which + # the wildcard character comprises a label other than the left-most label. + if leftmost == "*": + # When '*' is a fragment by itself, it matches a non-empty dotless + # fragment. + pats.append("[^.]+") + elif leftmost.startswith("xn--") or hostname.startswith("xn--"): + # RFC 6125, section 6.4.3, subitem 3. + # The client SHOULD NOT attempt to match a presented identifier + # where the wildcard character is embedded within an A-label or + # U-label of an internationalized domain name. + pats.append(re.escape(leftmost)) + else: + # Otherwise, '*' matches any dotless string, e.g. www* + pats.append(re.escape(leftmost).replace(r"\*", "[^.]*")) + + # add the remaining fragments, ignore any wildcards + for frag in remainder: + pats.append(re.escape(frag)) + + pat = re.compile(r"\A" + r"\.".join(pats) + r"\Z", re.IGNORECASE) + return pat.match(hostname) + + +def _ipaddress_match(ipname: str, host_ip: IPv4Address | IPv6Address) -> bool: + """Exact matching of IP addresses. + + RFC 9110 section 4.3.5: "A reference identity of IP-ID contains the decoded + bytes of the IP address. An IP version 4 address is 4 octets, and an IP + version 6 address is 16 octets. [...] A reference identity of type IP-ID + matches if the address is identical to an iPAddress value of the + subjectAltName extension of the certificate." + """ + # OpenSSL may add a trailing newline to a subjectAltName's IP address + # Divergence from upstream: ipaddress can't handle byte str + ip = ipaddress.ip_address(ipname.rstrip()) + return bool(ip.packed == host_ip.packed) + + +def match_hostname( + cert: _TYPE_PEER_CERT_RET_DICT | None, + hostname: str, + hostname_checks_common_name: bool = False, +) -> None: + """Verify that *cert* (in decoded format as returned by + SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 + rules are followed, but IP addresses are not accepted for *hostname*. + + CertificateError is raised on failure. On success, the function + returns nothing. + """ + if not cert: + raise ValueError( + "empty or no certificate, match_hostname needs a " + "SSL socket or SSL context with either " + "CERT_OPTIONAL or CERT_REQUIRED" + ) + + try: + host_ip = ipaddress.ip_address(hostname) + except ValueError: + # Not an IP address (common case) + host_ip = None + dnsnames = [] + san: tuple[tuple[str, str], ...] = cert.get("subjectAltName", ()) + key: str + value: str + for key, value in san: + if key == "DNS": + if host_ip is None and _dnsname_match(value, hostname): + return + dnsnames.append(value) + elif key == "IP Address": + if host_ip is not None and _ipaddress_match(value, host_ip): + return + dnsnames.append(value) + + # We only check 'commonName' if it's enabled and we're not verifying + # an IP address. IP addresses aren't valid within 'commonName'. + if hostname_checks_common_name and host_ip is None and not dnsnames: + for sub in cert.get("subject", ()): + for key, value in sub: + if key == "commonName": + if _dnsname_match(value, hostname): + return + dnsnames.append( + value + ) # Defensive: for older PyPy and OpenSSL versions + + if len(dnsnames) > 1: + raise CertificateError( + "hostname %r " + "doesn't match either of %s" % (hostname, ", ".join(map(repr, dnsnames))) + ) + elif len(dnsnames) == 1: + raise CertificateError(f"hostname {hostname!r} doesn't match {dnsnames[0]!r}") + else: + raise CertificateError("no appropriate subjectAltName fields were found") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/ssltransport.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/ssltransport.py new file mode 100644 index 0000000000000000000000000000000000000000..6d59bc3bce2489c3a0aa5bcb83b737dcf33c033b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/ssltransport.py @@ -0,0 +1,271 @@ +from __future__ import annotations + +import io +import socket +import ssl +import typing + +from ..exceptions import ProxySchemeUnsupported + +if typing.TYPE_CHECKING: + from typing_extensions import Self + + from .ssl_ import _TYPE_PEER_CERT_RET, _TYPE_PEER_CERT_RET_DICT + + +_WriteBuffer = typing.Union[bytearray, memoryview] +_ReturnValue = typing.TypeVar("_ReturnValue") + +SSL_BLOCKSIZE = 16384 + + +class SSLTransport: + """ + The SSLTransport wraps an existing socket and establishes an SSL connection. + + Contrary to Python's implementation of SSLSocket, it allows you to chain + multiple TLS connections together. It's particularly useful if you need to + implement TLS within TLS. + + The class supports most of the socket API operations. + """ + + @staticmethod + def _validate_ssl_context_for_tls_in_tls(ssl_context: ssl.SSLContext) -> None: + """ + Raises a ProxySchemeUnsupported if the provided ssl_context can't be used + for TLS in TLS. + + The only requirement is that the ssl_context provides the 'wrap_bio' + methods. + """ + + if not hasattr(ssl_context, "wrap_bio"): + raise ProxySchemeUnsupported( + "TLS in TLS requires SSLContext.wrap_bio() which isn't " + "available on non-native SSLContext" + ) + + def __init__( + self, + socket: socket.socket, + ssl_context: ssl.SSLContext, + server_hostname: str | None = None, + suppress_ragged_eofs: bool = True, + ) -> None: + """ + Create an SSLTransport around socket using the provided ssl_context. + """ + self.incoming = ssl.MemoryBIO() + self.outgoing = ssl.MemoryBIO() + + self.suppress_ragged_eofs = suppress_ragged_eofs + self.socket = socket + + self.sslobj = ssl_context.wrap_bio( + self.incoming, self.outgoing, server_hostname=server_hostname + ) + + # Perform initial handshake. + self._ssl_io_loop(self.sslobj.do_handshake) + + def __enter__(self) -> Self: + return self + + def __exit__(self, *_: typing.Any) -> None: + self.close() + + def fileno(self) -> int: + return self.socket.fileno() + + def read(self, len: int = 1024, buffer: typing.Any | None = None) -> int | bytes: + return self._wrap_ssl_read(len, buffer) + + def recv(self, buflen: int = 1024, flags: int = 0) -> int | bytes: + if flags != 0: + raise ValueError("non-zero flags not allowed in calls to recv") + return self._wrap_ssl_read(buflen) + + def recv_into( + self, + buffer: _WriteBuffer, + nbytes: int | None = None, + flags: int = 0, + ) -> None | int | bytes: + if flags != 0: + raise ValueError("non-zero flags not allowed in calls to recv_into") + if nbytes is None: + nbytes = len(buffer) + return self.read(nbytes, buffer) + + def sendall(self, data: bytes, flags: int = 0) -> None: + if flags != 0: + raise ValueError("non-zero flags not allowed in calls to sendall") + count = 0 + with memoryview(data) as view, view.cast("B") as byte_view: + amount = len(byte_view) + while count < amount: + v = self.send(byte_view[count:]) + count += v + + def send(self, data: bytes, flags: int = 0) -> int: + if flags != 0: + raise ValueError("non-zero flags not allowed in calls to send") + return self._ssl_io_loop(self.sslobj.write, data) + + def makefile( + self, + mode: str, + buffering: int | None = None, + *, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> typing.BinaryIO | typing.TextIO | socket.SocketIO: + """ + Python's httpclient uses makefile and buffered io when reading HTTP + messages and we need to support it. + + This is unfortunately a copy and paste of socket.py makefile with small + changes to point to the socket directly. + """ + if not set(mode) <= {"r", "w", "b"}: + raise ValueError(f"invalid mode {mode!r} (only r, w, b allowed)") + + writing = "w" in mode + reading = "r" in mode or not writing + assert reading or writing + binary = "b" in mode + rawmode = "" + if reading: + rawmode += "r" + if writing: + rawmode += "w" + raw = socket.SocketIO(self, rawmode) # type: ignore[arg-type] + self.socket._io_refs += 1 # type: ignore[attr-defined] + if buffering is None: + buffering = -1 + if buffering < 0: + buffering = io.DEFAULT_BUFFER_SIZE + if buffering == 0: + if not binary: + raise ValueError("unbuffered streams must be binary") + return raw + buffer: typing.BinaryIO + if reading and writing: + buffer = io.BufferedRWPair(raw, raw, buffering) # type: ignore[assignment] + elif reading: + buffer = io.BufferedReader(raw, buffering) + else: + assert writing + buffer = io.BufferedWriter(raw, buffering) + if binary: + return buffer + text = io.TextIOWrapper(buffer, encoding, errors, newline) + text.mode = mode # type: ignore[misc] + return text + + def unwrap(self) -> None: + self._ssl_io_loop(self.sslobj.unwrap) + + def close(self) -> None: + self.socket.close() + + @typing.overload + def getpeercert( + self, binary_form: typing.Literal[False] = ... + ) -> _TYPE_PEER_CERT_RET_DICT | None: ... + + @typing.overload + def getpeercert(self, binary_form: typing.Literal[True]) -> bytes | None: ... + + def getpeercert(self, binary_form: bool = False) -> _TYPE_PEER_CERT_RET: + return self.sslobj.getpeercert(binary_form) # type: ignore[return-value] + + def version(self) -> str | None: + return self.sslobj.version() + + def cipher(self) -> tuple[str, str, int] | None: + return self.sslobj.cipher() + + def selected_alpn_protocol(self) -> str | None: + return self.sslobj.selected_alpn_protocol() + + def shared_ciphers(self) -> list[tuple[str, str, int]] | None: + return self.sslobj.shared_ciphers() + + def compression(self) -> str | None: + return self.sslobj.compression() + + def settimeout(self, value: float | None) -> None: + self.socket.settimeout(value) + + def gettimeout(self) -> float | None: + return self.socket.gettimeout() + + def _decref_socketios(self) -> None: + self.socket._decref_socketios() # type: ignore[attr-defined] + + def _wrap_ssl_read(self, len: int, buffer: bytearray | None = None) -> int | bytes: + try: + return self._ssl_io_loop(self.sslobj.read, len, buffer) + except ssl.SSLError as e: + if e.errno == ssl.SSL_ERROR_EOF and self.suppress_ragged_eofs: + return 0 # eof, return 0. + else: + raise + + # func is sslobj.do_handshake or sslobj.unwrap + @typing.overload + def _ssl_io_loop(self, func: typing.Callable[[], None]) -> None: ... + + # func is sslobj.write, arg1 is data + @typing.overload + def _ssl_io_loop(self, func: typing.Callable[[bytes], int], arg1: bytes) -> int: ... + + # func is sslobj.read, arg1 is len, arg2 is buffer + @typing.overload + def _ssl_io_loop( + self, + func: typing.Callable[[int, bytearray | None], bytes], + arg1: int, + arg2: bytearray | None, + ) -> bytes: ... + + def _ssl_io_loop( + self, + func: typing.Callable[..., _ReturnValue], + arg1: None | bytes | int = None, + arg2: bytearray | None = None, + ) -> _ReturnValue: + """Performs an I/O loop between incoming/outgoing and the socket.""" + should_loop = True + ret = None + + while should_loop: + errno = None + try: + if arg1 is None and arg2 is None: + ret = func() + elif arg2 is None: + ret = func(arg1) + else: + ret = func(arg1, arg2) + except ssl.SSLError as e: + if e.errno not in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE): + # WANT_READ, and WANT_WRITE are expected, others are not. + raise e + errno = e.errno + + buf = self.outgoing.read() + self.socket.sendall(buf) + + if errno is None: + should_loop = False + elif errno == ssl.SSL_ERROR_WANT_READ: + buf = self.socket.recv(SSL_BLOCKSIZE) + if buf: + self.incoming.write(buf) + else: + self.incoming.write_eof() + return typing.cast(_ReturnValue, ret) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/timeout.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/timeout.py new file mode 100644 index 0000000000000000000000000000000000000000..4bb1be11d9cb06900dd82ecebd06aa6a7c5de916 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/timeout.py @@ -0,0 +1,275 @@ +from __future__ import annotations + +import time +import typing +from enum import Enum +from socket import getdefaulttimeout + +from ..exceptions import TimeoutStateError + +if typing.TYPE_CHECKING: + from typing import Final + + +class _TYPE_DEFAULT(Enum): + # This value should never be passed to socket.settimeout() so for safety we use a -1. + # socket.settimout() raises a ValueError for negative values. + token = -1 + + +_DEFAULT_TIMEOUT: Final[_TYPE_DEFAULT] = _TYPE_DEFAULT.token + +_TYPE_TIMEOUT = typing.Optional[typing.Union[float, _TYPE_DEFAULT]] + + +class Timeout: + """Timeout configuration. + + Timeouts can be defined as a default for a pool: + + .. code-block:: python + + import urllib3 + + timeout = urllib3.util.Timeout(connect=2.0, read=7.0) + + http = urllib3.PoolManager(timeout=timeout) + + resp = http.request("GET", "https://example.com/") + + print(resp.status) + + Or per-request (which overrides the default for the pool): + + .. code-block:: python + + response = http.request("GET", "https://example.com/", timeout=Timeout(10)) + + Timeouts can be disabled by setting all the parameters to ``None``: + + .. code-block:: python + + no_timeout = Timeout(connect=None, read=None) + response = http.request("GET", "https://example.com/", timeout=no_timeout) + + + :param total: + This combines the connect and read timeouts into one; the read timeout + will be set to the time leftover from the connect attempt. In the + event that both a connect timeout and a total are specified, or a read + timeout and a total are specified, the shorter timeout will be applied. + + Defaults to None. + + :type total: int, float, or None + + :param connect: + The maximum amount of time (in seconds) to wait for a connection + attempt to a server to succeed. Omitting the parameter will default the + connect timeout to the system default, probably `the global default + timeout in socket.py + `_. + None will set an infinite timeout for connection attempts. + + :type connect: int, float, or None + + :param read: + The maximum amount of time (in seconds) to wait between consecutive + read operations for a response from the server. Omitting the parameter + will default the read timeout to the system default, probably `the + global default timeout in socket.py + `_. + None will set an infinite timeout. + + :type read: int, float, or None + + .. note:: + + Many factors can affect the total amount of time for urllib3 to return + an HTTP response. + + For example, Python's DNS resolver does not obey the timeout specified + on the socket. Other factors that can affect total request time include + high CPU load, high swap, the program running at a low priority level, + or other behaviors. + + In addition, the read and total timeouts only measure the time between + read operations on the socket connecting the client and the server, + not the total amount of time for the request to return a complete + response. For most requests, the timeout is raised because the server + has not sent the first byte in the specified time. This is not always + the case; if a server streams one byte every fifteen seconds, a timeout + of 20 seconds will not trigger, even though the request will take + several minutes to complete. + """ + + #: A sentinel object representing the default timeout value + DEFAULT_TIMEOUT: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT + + def __init__( + self, + total: _TYPE_TIMEOUT = None, + connect: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + read: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + ) -> None: + self._connect = self._validate_timeout(connect, "connect") + self._read = self._validate_timeout(read, "read") + self.total = self._validate_timeout(total, "total") + self._start_connect: float | None = None + + def __repr__(self) -> str: + return f"{type(self).__name__}(connect={self._connect!r}, read={self._read!r}, total={self.total!r})" + + # __str__ provided for backwards compatibility + __str__ = __repr__ + + @staticmethod + def resolve_default_timeout(timeout: _TYPE_TIMEOUT) -> float | None: + return getdefaulttimeout() if timeout is _DEFAULT_TIMEOUT else timeout + + @classmethod + def _validate_timeout(cls, value: _TYPE_TIMEOUT, name: str) -> _TYPE_TIMEOUT: + """Check that a timeout attribute is valid. + + :param value: The timeout value to validate + :param name: The name of the timeout attribute to validate. This is + used to specify in error messages. + :return: The validated and casted version of the given value. + :raises ValueError: If it is a numeric value less than or equal to + zero, or the type is not an integer, float, or None. + """ + if value is None or value is _DEFAULT_TIMEOUT: + return value + + if isinstance(value, bool): + raise ValueError( + "Timeout cannot be a boolean value. It must " + "be an int, float or None." + ) + try: + float(value) + except (TypeError, ValueError): + raise ValueError( + "Timeout value %s was %s, but it must be an " + "int, float or None." % (name, value) + ) from None + + try: + if value <= 0: + raise ValueError( + "Attempted to set %s timeout to %s, but the " + "timeout cannot be set to a value less " + "than or equal to 0." % (name, value) + ) + except TypeError: + raise ValueError( + "Timeout value %s was %s, but it must be an " + "int, float or None." % (name, value) + ) from None + + return value + + @classmethod + def from_float(cls, timeout: _TYPE_TIMEOUT) -> Timeout: + """Create a new Timeout from a legacy timeout value. + + The timeout value used by httplib.py sets the same timeout on the + connect(), and recv() socket requests. This creates a :class:`Timeout` + object that sets the individual timeouts to the ``timeout`` value + passed to this function. + + :param timeout: The legacy timeout value. + :type timeout: integer, float, :attr:`urllib3.util.Timeout.DEFAULT_TIMEOUT`, or None + :return: Timeout object + :rtype: :class:`Timeout` + """ + return Timeout(read=timeout, connect=timeout) + + def clone(self) -> Timeout: + """Create a copy of the timeout object + + Timeout properties are stored per-pool but each request needs a fresh + Timeout object to ensure each one has its own start/stop configured. + + :return: a copy of the timeout object + :rtype: :class:`Timeout` + """ + # We can't use copy.deepcopy because that will also create a new object + # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to + # detect the user default. + return Timeout(connect=self._connect, read=self._read, total=self.total) + + def start_connect(self) -> float: + """Start the timeout clock, used during a connect() attempt + + :raises urllib3.exceptions.TimeoutStateError: if you attempt + to start a timer that has been started already. + """ + if self._start_connect is not None: + raise TimeoutStateError("Timeout timer has already been started.") + self._start_connect = time.monotonic() + return self._start_connect + + def get_connect_duration(self) -> float: + """Gets the time elapsed since the call to :meth:`start_connect`. + + :return: Elapsed time in seconds. + :rtype: float + :raises urllib3.exceptions.TimeoutStateError: if you attempt + to get duration for a timer that hasn't been started. + """ + if self._start_connect is None: + raise TimeoutStateError( + "Can't get connect duration for timer that has not started." + ) + return time.monotonic() - self._start_connect + + @property + def connect_timeout(self) -> _TYPE_TIMEOUT: + """Get the value to use when setting a connection timeout. + + This will be a positive float or integer, the value None + (never timeout), or the default system timeout. + + :return: Connect timeout. + :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None + """ + if self.total is None: + return self._connect + + if self._connect is None or self._connect is _DEFAULT_TIMEOUT: + return self.total + + return min(self._connect, self.total) # type: ignore[type-var] + + @property + def read_timeout(self) -> float | None: + """Get the value for the read timeout. + + This assumes some time has elapsed in the connection timeout and + computes the read timeout appropriately. + + If self.total is set, the read timeout is dependent on the amount of + time taken by the connect timeout. If the connection time has not been + established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be + raised. + + :return: Value to use for the read timeout. + :rtype: int, float or None + :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect` + has not yet been called on this object. + """ + if ( + self.total is not None + and self.total is not _DEFAULT_TIMEOUT + and self._read is not None + and self._read is not _DEFAULT_TIMEOUT + ): + # In case the connect timeout has not yet been established. + if self._start_connect is None: + return self._read + return max(0, min(self.total - self.get_connect_duration(), self._read)) + elif self.total is not None and self.total is not _DEFAULT_TIMEOUT: + return max(0, self.total - self.get_connect_duration()) + else: + return self.resolve_default_timeout(self._read) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/url.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/url.py new file mode 100644 index 0000000000000000000000000000000000000000..db057f17be610174f30928748b5004dcbf6c501c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/url.py @@ -0,0 +1,469 @@ +from __future__ import annotations + +import re +import typing + +from ..exceptions import LocationParseError +from .util import to_str + +# We only want to normalize urls with an HTTP(S) scheme. +# urllib3 infers URLs without a scheme (None) to be http. +_NORMALIZABLE_SCHEMES = ("http", "https", None) + +# Almost all of these patterns were derived from the +# 'rfc3986' module: https://github.com/python-hyper/rfc3986 +_PERCENT_RE = re.compile(r"%[a-fA-F0-9]{2}") +_SCHEME_RE = re.compile(r"^(?:[a-zA-Z][a-zA-Z0-9+-]*:|/)") +_URI_RE = re.compile( + r"^(?:([a-zA-Z][a-zA-Z0-9+.-]*):)?" + r"(?://([^\\/?#]*))?" + r"([^?#]*)" + r"(?:\?([^#]*))?" + r"(?:#(.*))?$", + re.UNICODE | re.DOTALL, +) + +_IPV4_PAT = r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}" +_HEX_PAT = "[0-9A-Fa-f]{1,4}" +_LS32_PAT = "(?:{hex}:{hex}|{ipv4})".format(hex=_HEX_PAT, ipv4=_IPV4_PAT) +_subs = {"hex": _HEX_PAT, "ls32": _LS32_PAT} +_variations = [ + # 6( h16 ":" ) ls32 + "(?:%(hex)s:){6}%(ls32)s", + # "::" 5( h16 ":" ) ls32 + "::(?:%(hex)s:){5}%(ls32)s", + # [ h16 ] "::" 4( h16 ":" ) ls32 + "(?:%(hex)s)?::(?:%(hex)s:){4}%(ls32)s", + # [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + "(?:(?:%(hex)s:)?%(hex)s)?::(?:%(hex)s:){3}%(ls32)s", + # [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + "(?:(?:%(hex)s:){0,2}%(hex)s)?::(?:%(hex)s:){2}%(ls32)s", + # [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + "(?:(?:%(hex)s:){0,3}%(hex)s)?::%(hex)s:%(ls32)s", + # [ *4( h16 ":" ) h16 ] "::" ls32 + "(?:(?:%(hex)s:){0,4}%(hex)s)?::%(ls32)s", + # [ *5( h16 ":" ) h16 ] "::" h16 + "(?:(?:%(hex)s:){0,5}%(hex)s)?::%(hex)s", + # [ *6( h16 ":" ) h16 ] "::" + "(?:(?:%(hex)s:){0,6}%(hex)s)?::", +] + +_UNRESERVED_PAT = r"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._\-~" +_IPV6_PAT = "(?:" + "|".join([x % _subs for x in _variations]) + ")" +_ZONE_ID_PAT = "(?:%25|%)(?:[" + _UNRESERVED_PAT + "]|%[a-fA-F0-9]{2})+" +_IPV6_ADDRZ_PAT = r"\[" + _IPV6_PAT + r"(?:" + _ZONE_ID_PAT + r")?\]" +_REG_NAME_PAT = r"(?:[^\[\]%:/?#]|%[a-fA-F0-9]{2})*" +_TARGET_RE = re.compile(r"^(/[^?#]*)(?:\?([^#]*))?(?:#.*)?$") + +_IPV4_RE = re.compile("^" + _IPV4_PAT + "$") +_IPV6_RE = re.compile("^" + _IPV6_PAT + "$") +_IPV6_ADDRZ_RE = re.compile("^" + _IPV6_ADDRZ_PAT + "$") +_BRACELESS_IPV6_ADDRZ_RE = re.compile("^" + _IPV6_ADDRZ_PAT[2:-2] + "$") +_ZONE_ID_RE = re.compile("(" + _ZONE_ID_PAT + r")\]$") + +_HOST_PORT_PAT = ("^(%s|%s|%s)(?::0*?(|0|[1-9][0-9]{0,4}))?$") % ( + _REG_NAME_PAT, + _IPV4_PAT, + _IPV6_ADDRZ_PAT, +) +_HOST_PORT_RE = re.compile(_HOST_PORT_PAT, re.UNICODE | re.DOTALL) + +_UNRESERVED_CHARS = set( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-~" +) +_SUB_DELIM_CHARS = set("!$&'()*+,;=") +_USERINFO_CHARS = _UNRESERVED_CHARS | _SUB_DELIM_CHARS | {":"} +_PATH_CHARS = _USERINFO_CHARS | {"@", "/"} +_QUERY_CHARS = _FRAGMENT_CHARS = _PATH_CHARS | {"?"} + + +class Url( + typing.NamedTuple( + "Url", + [ + ("scheme", typing.Optional[str]), + ("auth", typing.Optional[str]), + ("host", typing.Optional[str]), + ("port", typing.Optional[int]), + ("path", typing.Optional[str]), + ("query", typing.Optional[str]), + ("fragment", typing.Optional[str]), + ], + ) +): + """ + Data structure for representing an HTTP URL. Used as a return value for + :func:`parse_url`. Both the scheme and host are normalized as they are + both case-insensitive according to RFC 3986. + """ + + def __new__( # type: ignore[no-untyped-def] + cls, + scheme: str | None = None, + auth: str | None = None, + host: str | None = None, + port: int | None = None, + path: str | None = None, + query: str | None = None, + fragment: str | None = None, + ): + if path and not path.startswith("/"): + path = "/" + path + if scheme is not None: + scheme = scheme.lower() + return super().__new__(cls, scheme, auth, host, port, path, query, fragment) + + @property + def hostname(self) -> str | None: + """For backwards-compatibility with urlparse. We're nice like that.""" + return self.host + + @property + def request_uri(self) -> str: + """Absolute path including the query string.""" + uri = self.path or "/" + + if self.query is not None: + uri += "?" + self.query + + return uri + + @property + def authority(self) -> str | None: + """ + Authority component as defined in RFC 3986 3.2. + This includes userinfo (auth), host and port. + + i.e. + userinfo@host:port + """ + userinfo = self.auth + netloc = self.netloc + if netloc is None or userinfo is None: + return netloc + else: + return f"{userinfo}@{netloc}" + + @property + def netloc(self) -> str | None: + """ + Network location including host and port. + + If you need the equivalent of urllib.parse's ``netloc``, + use the ``authority`` property instead. + """ + if self.host is None: + return None + if self.port: + return f"{self.host}:{self.port}" + return self.host + + @property + def url(self) -> str: + """ + Convert self into a url + + This function should more or less round-trip with :func:`.parse_url`. The + returned url may not be exactly the same as the url inputted to + :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls + with a blank port will have : removed). + + Example: + + .. code-block:: python + + import urllib3 + + U = urllib3.util.parse_url("https://google.com/mail/") + + print(U.url) + # "https://google.com/mail/" + + print( urllib3.util.Url("https", "username:password", + "host.com", 80, "/path", "query", "fragment" + ).url + ) + # "https://username:password@host.com:80/path?query#fragment" + """ + scheme, auth, host, port, path, query, fragment = self + url = "" + + # We use "is not None" we want things to happen with empty strings (or 0 port) + if scheme is not None: + url += scheme + "://" + if auth is not None: + url += auth + "@" + if host is not None: + url += host + if port is not None: + url += ":" + str(port) + if path is not None: + url += path + if query is not None: + url += "?" + query + if fragment is not None: + url += "#" + fragment + + return url + + def __str__(self) -> str: + return self.url + + +@typing.overload +def _encode_invalid_chars( + component: str, allowed_chars: typing.Container[str] +) -> str: # Abstract + ... + + +@typing.overload +def _encode_invalid_chars( + component: None, allowed_chars: typing.Container[str] +) -> None: # Abstract + ... + + +def _encode_invalid_chars( + component: str | None, allowed_chars: typing.Container[str] +) -> str | None: + """Percent-encodes a URI component without reapplying + onto an already percent-encoded component. + """ + if component is None: + return component + + component = to_str(component) + + # Normalize existing percent-encoded bytes. + # Try to see if the component we're encoding is already percent-encoded + # so we can skip all '%' characters but still encode all others. + component, percent_encodings = _PERCENT_RE.subn( + lambda match: match.group(0).upper(), component + ) + + uri_bytes = component.encode("utf-8", "surrogatepass") + is_percent_encoded = percent_encodings == uri_bytes.count(b"%") + encoded_component = bytearray() + + for i in range(0, len(uri_bytes)): + # Will return a single character bytestring + byte = uri_bytes[i : i + 1] + byte_ord = ord(byte) + if (is_percent_encoded and byte == b"%") or ( + byte_ord < 128 and byte.decode() in allowed_chars + ): + encoded_component += byte + continue + encoded_component.extend(b"%" + (hex(byte_ord)[2:].encode().zfill(2).upper())) + + return encoded_component.decode() + + +def _remove_path_dot_segments(path: str) -> str: + # See http://tools.ietf.org/html/rfc3986#section-5.2.4 for pseudo-code + segments = path.split("/") # Turn the path into a list of segments + output = [] # Initialize the variable to use to store output + + for segment in segments: + # '.' is the current directory, so ignore it, it is superfluous + if segment == ".": + continue + # Anything other than '..', should be appended to the output + if segment != "..": + output.append(segment) + # In this case segment == '..', if we can, we should pop the last + # element + elif output: + output.pop() + + # If the path starts with '/' and the output is empty or the first string + # is non-empty + if path.startswith("/") and (not output or output[0]): + output.insert(0, "") + + # If the path starts with '/.' or '/..' ensure we add one more empty + # string to add a trailing '/' + if path.endswith(("/.", "/..")): + output.append("") + + return "/".join(output) + + +@typing.overload +def _normalize_host(host: None, scheme: str | None) -> None: ... + + +@typing.overload +def _normalize_host(host: str, scheme: str | None) -> str: ... + + +def _normalize_host(host: str | None, scheme: str | None) -> str | None: + if host: + if scheme in _NORMALIZABLE_SCHEMES: + is_ipv6 = _IPV6_ADDRZ_RE.match(host) + if is_ipv6: + # IPv6 hosts of the form 'a::b%zone' are encoded in a URL as + # such per RFC 6874: 'a::b%25zone'. Unquote the ZoneID + # separator as necessary to return a valid RFC 4007 scoped IP. + match = _ZONE_ID_RE.search(host) + if match: + start, end = match.span(1) + zone_id = host[start:end] + + if zone_id.startswith("%25") and zone_id != "%25": + zone_id = zone_id[3:] + else: + zone_id = zone_id[1:] + zone_id = _encode_invalid_chars(zone_id, _UNRESERVED_CHARS) + return f"{host[:start].lower()}%{zone_id}{host[end:]}" + else: + return host.lower() + elif not _IPV4_RE.match(host): + return to_str( + b".".join([_idna_encode(label) for label in host.split(".")]), + "ascii", + ) + return host + + +def _idna_encode(name: str) -> bytes: + if not name.isascii(): + try: + import idna + except ImportError: + raise LocationParseError( + "Unable to parse URL without the 'idna' module" + ) from None + + try: + return idna.encode(name.lower(), strict=True, std3_rules=True) + except idna.IDNAError: + raise LocationParseError( + f"Name '{name}' is not a valid IDNA label" + ) from None + + return name.lower().encode("ascii") + + +def _encode_target(target: str) -> str: + """Percent-encodes a request target so that there are no invalid characters + + Pre-condition for this function is that 'target' must start with '/'. + If that is the case then _TARGET_RE will always produce a match. + """ + match = _TARGET_RE.match(target) + if not match: # Defensive: + raise LocationParseError(f"{target!r} is not a valid request URI") + + path, query = match.groups() + encoded_target = _encode_invalid_chars(path, _PATH_CHARS) + if query is not None: + query = _encode_invalid_chars(query, _QUERY_CHARS) + encoded_target += "?" + query + return encoded_target + + +def parse_url(url: str) -> Url: + """ + Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is + performed to parse incomplete urls. Fields not provided will be None. + This parser is RFC 3986 and RFC 6874 compliant. + + The parser logic and helper functions are based heavily on + work done in the ``rfc3986`` module. + + :param str url: URL to parse into a :class:`.Url` namedtuple. + + Partly backwards-compatible with :mod:`urllib.parse`. + + Example: + + .. code-block:: python + + import urllib3 + + print( urllib3.util.parse_url('http://google.com/mail/')) + # Url(scheme='http', host='google.com', port=None, path='/mail/', ...) + + print( urllib3.util.parse_url('google.com:80')) + # Url(scheme=None, host='google.com', port=80, path=None, ...) + + print( urllib3.util.parse_url('/foo?bar')) + # Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...) + """ + if not url: + # Empty + return Url() + + source_url = url + if not _SCHEME_RE.search(url): + url = "//" + url + + scheme: str | None + authority: str | None + auth: str | None + host: str | None + port: str | None + port_int: int | None + path: str | None + query: str | None + fragment: str | None + + try: + scheme, authority, path, query, fragment = _URI_RE.match(url).groups() # type: ignore[union-attr] + normalize_uri = scheme is None or scheme.lower() in _NORMALIZABLE_SCHEMES + + if scheme: + scheme = scheme.lower() + + if authority: + auth, _, host_port = authority.rpartition("@") + auth = auth or None + host, port = _HOST_PORT_RE.match(host_port).groups() # type: ignore[union-attr] + if auth and normalize_uri: + auth = _encode_invalid_chars(auth, _USERINFO_CHARS) + if port == "": + port = None + else: + auth, host, port = None, None, None + + if port is not None: + port_int = int(port) + if not (0 <= port_int <= 65535): + raise LocationParseError(url) + else: + port_int = None + + host = _normalize_host(host, scheme) + + if normalize_uri and path: + path = _remove_path_dot_segments(path) + path = _encode_invalid_chars(path, _PATH_CHARS) + if normalize_uri and query: + query = _encode_invalid_chars(query, _QUERY_CHARS) + if normalize_uri and fragment: + fragment = _encode_invalid_chars(fragment, _FRAGMENT_CHARS) + + except (ValueError, AttributeError) as e: + raise LocationParseError(source_url) from e + + # For the sake of backwards compatibility we put empty + # string values for path if there are any defined values + # beyond the path in the URL. + # TODO: Remove this when we break backwards compatibility. + if not path: + if query is not None or fragment is not None: + path = "" + else: + path = None + + return Url( + scheme=scheme, + auth=auth, + host=host, + port=port_int, + path=path, + query=query, + fragment=fragment, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/util.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/util.py new file mode 100644 index 0000000000000000000000000000000000000000..35c77e4025842f548565334a3c04cba90f9283d6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/util.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +import typing +from types import TracebackType + + +def to_bytes( + x: str | bytes, encoding: str | None = None, errors: str | None = None +) -> bytes: + if isinstance(x, bytes): + return x + elif not isinstance(x, str): + raise TypeError(f"not expecting type {type(x).__name__}") + if encoding or errors: + return x.encode(encoding or "utf-8", errors=errors or "strict") + return x.encode() + + +def to_str( + x: str | bytes, encoding: str | None = None, errors: str | None = None +) -> str: + if isinstance(x, str): + return x + elif not isinstance(x, bytes): + raise TypeError(f"not expecting type {type(x).__name__}") + if encoding or errors: + return x.decode(encoding or "utf-8", errors=errors or "strict") + return x.decode() + + +def reraise( + tp: type[BaseException] | None, + value: BaseException, + tb: TracebackType | None = None, +) -> typing.NoReturn: + try: + if value.__traceback__ is not tb: + raise value.with_traceback(tb) + raise value + finally: + value = None # type: ignore[assignment] + tb = None diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/wait.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/wait.py new file mode 100644 index 0000000000000000000000000000000000000000..aeca0c7ad5b232eeb1ad9c43d315bd1d74eaed9a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/urllib3/util/wait.py @@ -0,0 +1,124 @@ +from __future__ import annotations + +import select +import socket +from functools import partial + +__all__ = ["wait_for_read", "wait_for_write"] + + +# How should we wait on sockets? +# +# There are two types of APIs you can use for waiting on sockets: the fancy +# modern stateful APIs like epoll/kqueue, and the older stateless APIs like +# select/poll. The stateful APIs are more efficient when you have a lots of +# sockets to keep track of, because you can set them up once and then use them +# lots of times. But we only ever want to wait on a single socket at a time +# and don't want to keep track of state, so the stateless APIs are actually +# more efficient. So we want to use select() or poll(). +# +# Now, how do we choose between select() and poll()? On traditional Unixes, +# select() has a strange calling convention that makes it slow, or fail +# altogether, for high-numbered file descriptors. The point of poll() is to fix +# that, so on Unixes, we prefer poll(). +# +# On Windows, there is no poll() (or at least Python doesn't provide a wrapper +# for it), but that's OK, because on Windows, select() doesn't have this +# strange calling convention; plain select() works fine. +# +# So: on Windows we use select(), and everywhere else we use poll(). We also +# fall back to select() in case poll() is somehow broken or missing. + + +def select_wait_for_socket( + sock: socket.socket, + read: bool = False, + write: bool = False, + timeout: float | None = None, +) -> bool: + if not read and not write: + raise RuntimeError("must specify at least one of read=True, write=True") + rcheck = [] + wcheck = [] + if read: + rcheck.append(sock) + if write: + wcheck.append(sock) + # When doing a non-blocking connect, most systems signal success by + # marking the socket writable. Windows, though, signals success by marked + # it as "exceptional". We paper over the difference by checking the write + # sockets for both conditions. (The stdlib selectors module does the same + # thing.) + fn = partial(select.select, rcheck, wcheck, wcheck) + rready, wready, xready = fn(timeout) + return bool(rready or wready or xready) + + +def poll_wait_for_socket( + sock: socket.socket, + read: bool = False, + write: bool = False, + timeout: float | None = None, +) -> bool: + if not read and not write: + raise RuntimeError("must specify at least one of read=True, write=True") + mask = 0 + if read: + mask |= select.POLLIN + if write: + mask |= select.POLLOUT + poll_obj = select.poll() + poll_obj.register(sock, mask) + + # For some reason, poll() takes timeout in milliseconds + def do_poll(t: float | None) -> list[tuple[int, int]]: + if t is not None: + t *= 1000 + return poll_obj.poll(t) + + return bool(do_poll(timeout)) + + +def _have_working_poll() -> bool: + # Apparently some systems have a select.poll that fails as soon as you try + # to use it, either due to strange configuration or broken monkeypatching + # from libraries like eventlet/greenlet. + try: + poll_obj = select.poll() + poll_obj.poll(0) + except (AttributeError, OSError): + return False + else: + return True + + +def wait_for_socket( + sock: socket.socket, + read: bool = False, + write: bool = False, + timeout: float | None = None, +) -> bool: + # We delay choosing which implementation to use until the first time we're + # called. We could do it at import time, but then we might make the wrong + # decision if someone goes wild with monkeypatching select.poll after + # we're imported. + global wait_for_socket + if _have_working_poll(): + wait_for_socket = poll_wait_for_socket + elif hasattr(select, "select"): + wait_for_socket = select_wait_for_socket + return wait_for_socket(sock, read, write, timeout) + + +def wait_for_read(sock: socket.socket, timeout: float | None = None) -> bool: + """Waits for reading to be available on a given socket. + Returns True if the socket is readable, or False if the timeout expired. + """ + return wait_for_socket(sock, read=True, timeout=timeout) + + +def wait_for_write(sock: socket.socket, timeout: float | None = None) -> bool: + """Waits for writing to be available on a given socket. + Returns True if the socket is readable, or False if the timeout expired. + """ + return wait_for_socket(sock, write=True, timeout=timeout) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uuid_utils-0.15.0.dist-info/licenses/LICENSE.md b/micromamba_root/envs/pytorch_env/Lib/site-packages/uuid_utils-0.15.0.dist-info/licenses/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..ce1ca0367f03ae325bb07f7b09b53fb11ede15d9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uuid_utils-0.15.0.dist-info/licenses/LICENSE.md @@ -0,0 +1,27 @@ +Copyright © 2023, Amin Alaee. +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. \ No newline at end of file diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uuid_utils-0.15.0.dist-info/sboms/uuid-utils.cyclonedx.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/uuid_utils-0.15.0.dist-info/sboms/uuid-utils.cyclonedx.json new file mode 100644 index 0000000000000000000000000000000000000000..e430ea9fbb2a03ec17badc63fd98c6c9917b7960 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uuid_utils-0.15.0.dist-info/sboms/uuid-utils.cyclonedx.json @@ -0,0 +1,1412 @@ +{ + "bomFormat": "CycloneDX", + "specVersion": "1.5", + "version": 1, + "serialNumber": "urn:uuid:6b186989-3aae-4b97-bac9-ec9d9251b16c", + "metadata": { + "timestamp": "2026-05-11T12:04:03.324183600Z", + "tools": [ + { + "vendor": "CycloneDX", + "name": "cargo-cyclonedx", + "version": "0.5.9" + } + ], + "component": { + "type": "library", + "bom-ref": "path+file:///D:/a/uuid-utils/uuid-utils#0.15.0", + "name": "uuid-utils", + "version": "0.15.0", + "scope": "required", + "purl": "pkg:cargo/uuid-utils@0.15.0?download_url=file://.", + "components": [ + { + "type": "library", + "bom-ref": "path+file:///D:/a/uuid-utils/uuid-utils#0.15.0 bin-target-0", + "name": "uuid_utils", + "version": "0.15.0", + "purl": "pkg:cargo/uuid-utils@0.15.0?download_url=file://.#src/lib.rs" + } + ] + }, + "properties": [ + { + "name": "cdx:rustc:sbom:target:all_targets", + "value": "true" + } + ] + }, + "components": [ + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ahash@0.8.12", + "author": "Tom Kaitchuck ", + "name": "ahash", + "version": "0.8.12", + "description": "A non-cryptographic hash function using AES-NI for high performance", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/ahash@0.8.12", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/ahash" + }, + { + "type": "vcs", + "url": "https://github.com/tkaitchuck/ahash" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#atomic@0.6.1", + "author": "Amanieu d'Antras ", + "name": "atomic", + "version": "0.6.1", + "description": "Generic Atomic wrapper type", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a89cbf775b137e9b968e67227ef7f775587cde3fd31b0d8599dbd0f598a48340" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/atomic@0.6.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Amanieu/atomic-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#block-buffer@0.10.4", + "author": "RustCrypto Developers", + "name": "block-buffer", + "version": "0.10.4", + "description": "Buffer type for block processing of data", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/block-buffer@0.10.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/block-buffer" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/utils" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bytemuck@1.23.2", + "author": "Lokathor ", + "name": "bytemuck", + "version": "1.23.2", + "description": "A crate for mucking around with piles of bytes.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "3995eaeebcdf32f91f980d360f78732ddc061097ab4e39991ae7a6ace9194677" + } + ], + "licenses": [ + { + "expression": "Zlib OR Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/bytemuck@1.23.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Lokathor/bytemuck" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cc@1.0.83", + "author": "Alex Crichton ", + "name": "cc", + "version": "1.0.83", + "description": "A build-time dependency for Cargo build scripts to assist in invoking the native C compiler to compile native C code into a static archive to be linked into Rust code. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/cc@1.0.83", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/cc" + }, + { + "type": "website", + "url": "https://github.com/rust-lang/cc-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/cc-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.0", + "author": "Alex Crichton ", + "name": "cfg-if", + "version": "1.0.0", + "description": "A macro to ergonomically define an item depending on a large number of #[cfg] parameters. Structured like an if-else chain, the first matching branch is the item that gets emitted. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/cfg-if@1.0.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/cfg-if" + }, + { + "type": "website", + "url": "https://github.com/alexcrichton/cfg-if" + }, + { + "type": "vcs", + "url": "https://github.com/alexcrichton/cfg-if" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#chacha20@0.10.0", + "author": "RustCrypto Developers", + "name": "chacha20", + "version": "0.10.0", + "description": "The ChaCha20 stream cipher (RFC 8439) implemented in pure Rust using traits from the RustCrypto `cipher` crate, with optional architecture-specific hardware acceleration (AVX2, SSE2). Additionally provides the ChaCha8, ChaCha12, XChaCha20, XChaCha12 and XChaCha8 stream ciphers, and also optional rand_core-compatible RNGs based on those ciphers. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6f8d983286843e49675a4b7a2d174efe136dc93a18d69130dd18198a6c167601" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/chacha20@0.10.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/chacha20" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/stream-ciphers" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cpufeatures@0.3.0", + "author": "RustCrypto Developers", + "name": "cpufeatures", + "version": "0.3.0", + "description": "Lightweight runtime CPU feature detection for aarch64, loongarch64, and x86/x86_64 targets, with no_std support and support for mobile targets including Android and iOS ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/cpufeatures@0.3.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/cpufeatures" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/utils" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#crypto-common@0.1.6", + "author": "RustCrypto Developers", + "name": "crypto-common", + "version": "0.1.6", + "description": "Common cryptographic traits", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/crypto-common@0.1.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/crypto-common" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/traits" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#digest@0.10.7", + "author": "RustCrypto Developers", + "name": "digest", + "version": "0.10.7", + "description": "Traits for cryptographic hash functions and message authentication codes", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/digest@0.10.7", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/digest" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/traits" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#generic-array@0.14.7", + "author": "Bartłomiej Kamiński , Aaron Trent ", + "name": "generic-array", + "version": "0.14.7", + "description": "Generic types implementing functionality of arrays", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/generic-array@0.14.7", + "externalReferences": [ + { + "type": "documentation", + "url": "http://fizyk20.github.io/generic-array/generic_array/" + }, + { + "type": "vcs", + "url": "https://github.com/fizyk20/generic-array.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.3.2", + "author": "The Rand Project Developers", + "name": "getrandom", + "version": "0.3.2", + "description": "A small cross-platform library for retrieving random data from system source", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "73fea8450eea4bac3940448fb7ae50d91f034f941199fcd9d909a5a07aa455f0" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/getrandom@0.3.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/getrandom" + }, + { + "type": "vcs", + "url": "https://github.com/rust-random/getrandom" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.4.1", + "author": "The Rand Project Developers", + "name": "getrandom", + "version": "0.4.1", + "description": "A small cross-platform library for retrieving random data from system source", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "139ef39800118c7683f2fd3c98c1b23c09ae076556b435f8e9064ae108aaeeec" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/getrandom@0.4.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/getrandom" + }, + { + "type": "vcs", + "url": "https://github.com/rust-random/getrandom" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0", + "name": "heck", + "version": "0.5.0", + "description": "heck is a case conversion library.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/heck@0.5.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/withoutboats/heck" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.171", + "author": "The Rust Project Developers", + "name": "libc", + "version": "0.2.171", + "description": "Raw FFI bindings to platform libraries like libc. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c19937216e9d3aa9956d9bb8dfc0b0c8beb6058fc4f7a4dc4d850edf86a237d6" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/libc@0.2.171", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/libc/" + }, + { + "type": "website", + "url": "https://github.com/rust-lang/libc" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/libc" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#mac_address@1.1.8", + "author": "rep-nop ", + "name": "mac_address", + "version": "1.1.8", + "description": "Cross-platform retrieval of a network interface MAC address.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c0aeb26bf5e836cc1c341c8106051b573f1766dfa05aa87f0b98be5e51b02303" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/mac_address@1.1.8", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rep-nop/mac_address" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#md-5@0.10.6", + "author": "RustCrypto Developers", + "name": "md-5", + "version": "0.10.6", + "description": "MD5 hash function", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/md-5@0.10.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/md-5" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/hashes" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.3", + "author": "Aleksey Kladov ", + "name": "once_cell", + "version": "1.21.3", + "description": "Single assignment cells and lazy values.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/once_cell@1.21.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/once_cell" + }, + { + "type": "vcs", + "url": "https://github.com/matklad/once_cell" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "author": "David Tolnay , Alex Crichton ", + "name": "proc-macro2", + "version": "1.0.106", + "description": "A substitute implementation of the compiler's `proc_macro` API to decouple token-based libraries from the procedural macro use case.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/proc-macro2@1.0.106", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/proc-macro2" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/proc-macro2" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3", + "author": "PyO3 Project and Contributors ", + "name": "pyo3-build-config", + "version": "0.28.3", + "description": "Build configuration for the PyO3 ecosystem", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e368e7ddfdeb98c9bca7f8383be1648fd84ab466bf2bc015e94008db6d35611e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3-build-config@0.28.3", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.28.3", + "author": "PyO3 Project and Contributors ", + "name": "pyo3-ffi", + "version": "0.28.3", + "description": "Python-API bindings for the PyO3 ecosystem", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7f29e10af80b1f7ccaf7f69eace800a03ecd13e883acfacc1e5d0988605f651e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3-ffi@0.28.3", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "other", + "url": "python" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros-backend@0.28.3", + "author": "PyO3 Project and Contributors ", + "name": "pyo3-macros-backend", + "version": "0.28.3", + "description": "Code generation for PyO3 package", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c4cdc218d835738f81c2338f822078af45b4afdf8b2e33cbb5916f108b813acb" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3-macros-backend@0.28.3", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros@0.28.3", + "author": "PyO3 Project and Contributors ", + "name": "pyo3-macros", + "version": "0.28.3", + "description": "Proc macros for PyO3 package", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "df6e520eff47c45997d2fc7dd8214b25dd1310918bbb2642156ef66a67f29813" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3-macros@0.28.3", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.28.3", + "author": "PyO3 Project and Contributors ", + "name": "pyo3", + "version": "0.28.3", + "description": "Bindings to Python interpreter", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "91fd8e38a3b50ed1167fb981cd6fd60147e091784c427b8f7183a7ee32c31c12" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3@0.28.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/crate/pyo3/" + }, + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#python3-dll-a@0.2.15", + "author": "Sergey Kvachonok , messense , Adam Reichold ", + "name": "python3-dll-a", + "version": "0.2.15", + "description": "Standalone python3(y)(t).dll import library generator", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d80ba7540edb18890d444c5aa8e1f1f99b1bdf26fb26ae383135325f4a36042b" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/python3-dll-a@0.2.15", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/PyO3/python3-dll-a" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.44", + "author": "David Tolnay ", + "name": "quote", + "version": "1.0.44", + "description": "Quasi-quoting macro quote!(...)", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/quote@1.0.44", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/quote/" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/quote" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rand@0.10.1", + "author": "The Rand Project Developers, The Rust Project Developers", + "name": "rand", + "version": "0.10.1", + "description": "Random number generators and other randomness functionality. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rand@0.10.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rand" + }, + { + "type": "website", + "url": "https://rust-random.github.io/book" + }, + { + "type": "vcs", + "url": "https://github.com/rust-random/rand" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.10.0", + "author": "The Rand Project Developers", + "name": "rand_core", + "version": "0.10.0", + "description": "Core random number generation traits and tools for implementation.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0c8d0fd677905edcbeedbf2edb6494d676f0e98d54d5cf9bda0b061cb8fb8aba" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rand_core@0.10.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rand_core" + }, + { + "type": "website", + "url": "https://rust-random.github.io/book" + }, + { + "type": "vcs", + "url": "https://github.com/rust-random/rand_core" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#sha1_smol@1.0.1", + "author": "Armin Ronacher ", + "name": "sha1_smol", + "version": "1.0.1", + "description": "Minimal dependency-free implementation of SHA1 for Rust.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" + } + ], + "licenses": [ + { + "expression": "BSD-3-Clause" + } + ], + "purl": "pkg:cargo/sha1_smol@1.0.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/mitsuhiko/sha1-smol" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117", + "author": "David Tolnay ", + "name": "syn", + "version": "2.0.117", + "description": "Parser for Rust source code", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/syn@2.0.117", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/syn" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/syn" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.5", + "author": "Dan Gohman ", + "name": "target-lexicon", + "version": "0.13.5", + "description": "LLVM target triple types", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 WITH LLVM-exception" + } + ], + "purl": "pkg:cargo/target-lexicon@0.13.5", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/target-lexicon/" + }, + { + "type": "vcs", + "url": "https://github.com/bytecodealliance/target-lexicon" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#typenum@1.18.0", + "author": "Paho Lurie-Gregg , Andre Bogus ", + "name": "typenum", + "version": "1.18.0", + "description": "Typenum is a Rust library for type-level numbers evaluated at compile time. It currently supports bits, unsigned integers, and signed integers. It also provides a type-level array of type-level numbers, but its implementation is incomplete.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/typenum@1.18.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/typenum" + }, + { + "type": "vcs", + "url": "https://github.com/paholg/typenum" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.12", + "author": "David Tolnay ", + "name": "unicode-ident", + "version": "1.0.12", + "description": "Determine whether characters have the XID_Start or XID_Continue properties according to Unicode Standard Annex #31", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" + } + ], + "licenses": [ + { + "expression": "(MIT OR Apache-2.0) AND Unicode-DFS-2016" + } + ], + "purl": "pkg:cargo/unicode-ident@1.0.12", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/unicode-ident" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/unicode-ident" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#uuid@1.23.1", + "author": "Ashley Mannix, Dylan DPC, Hunar Roop Kahlon", + "name": "uuid", + "version": "1.23.1", + "description": "A library to generate and parse UUIDs.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ddd74a9687298c6858e9b88ec8935ec45d22e8fd5e6394fa1bd4e99a87789c76" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/uuid@1.23.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/uuid" + }, + { + "type": "website", + "url": "https://github.com/uuid-rs/uuid" + }, + { + "type": "vcs", + "url": "https://github.com/uuid-rs/uuid" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#version_check@0.9.4", + "author": "Sergio Benitez ", + "name": "version_check", + "version": "0.9.4", + "description": "Tiny crate to check the version of the installed/running rustc.", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/version_check@0.9.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/version_check/" + }, + { + "type": "vcs", + "url": "https://github.com/SergioBenitez/version_check" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#winapi@0.3.9", + "author": "Peter Atashian ", + "name": "winapi", + "version": "0.3.9", + "description": "Raw FFI bindings for all of Windows API.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/winapi@0.3.9", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/winapi/" + }, + { + "type": "vcs", + "url": "https://github.com/retep998/winapi-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zerocopy@0.8.26", + "author": "Joshua Liebow-Feeser , Jack Wrenn ", + "name": "zerocopy", + "version": "0.8.26", + "description": "Zerocopy makes zero-cost memory manipulation effortless. We write \"unsafe\" so you don't have to.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1039dd0d3c310cf05de012d8a39ff557cb0d23087fd44cad61df08fc31907a2f" + } + ], + "licenses": [ + { + "expression": "BSD-2-Clause OR Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/zerocopy@0.8.26", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/google/zerocopy" + } + ] + } + ], + "dependencies": [ + { + "ref": "path+file:///D:/a/uuid-utils/uuid-utils#0.15.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#ahash@0.8.12", + "registry+https://github.com/rust-lang/crates.io-index#mac_address@1.1.8", + "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.28.3", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.10.1", + "registry+https://github.com/rust-lang/crates.io-index#uuid@1.23.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ahash@0.8.12", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.0", + "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.3.2", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.3", + "registry+https://github.com/rust-lang/crates.io-index#version_check@0.9.4", + "registry+https://github.com/rust-lang/crates.io-index#zerocopy@0.8.26" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#atomic@0.6.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytemuck@1.23.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#block-buffer@0.10.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#generic-array@0.14.7" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#bytemuck@1.23.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cc@1.0.83" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#chacha20@0.10.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.0", + "registry+https://github.com/rust-lang/crates.io-index#cpufeatures@0.3.0", + "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.10.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cpufeatures@0.3.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#crypto-common@0.1.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#generic-array@0.14.7", + "registry+https://github.com/rust-lang/crates.io-index#typenum@1.18.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#digest@0.10.7", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#block-buffer@0.10.4", + "registry+https://github.com/rust-lang/crates.io-index#crypto-common@0.1.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#generic-array@0.14.7", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#typenum@1.18.0", + "registry+https://github.com/rust-lang/crates.io-index#version_check@0.9.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.3.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.4.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.0", + "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.10.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.171" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#mac_address@1.1.8", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#winapi@0.3.9" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#md-5@0.10.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.0", + "registry+https://github.com/rust-lang/crates.io-index#digest@0.10.7" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.3" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.12" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#python3-dll-a@0.2.15", + "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.28.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.171", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros-backend@0.28.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.44", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros@0.28.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros-backend@0.28.3", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.44", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.28.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.171", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.3", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.28.3", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros@0.28.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#python3-dll-a@0.2.15", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cc@1.0.83" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.44", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rand@0.10.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#chacha20@0.10.0", + "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.4.1", + "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.10.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.10.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#sha1_smol@1.0.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.44", + "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.12" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.5" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#typenum@1.18.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.12" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#uuid@1.23.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#atomic@0.6.1", + "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.4.1", + "registry+https://github.com/rust-lang/crates.io-index#md-5@0.10.6", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.10.1", + "registry+https://github.com/rust-lang/crates.io-index#sha1_smol@1.0.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#version_check@0.9.4" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#winapi@0.3.9" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zerocopy@0.8.26" + } + ] +} \ No newline at end of file diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uuid_utils/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uuid_utils/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4fc102b2e81059269971e3cb212ab3690ac42e1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uuid_utils/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uuid_utils/compat/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uuid_utils/compat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..560363235ec1e5b5acb39771acf75d6f5a260003 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uuid_utils/compat/__init__.py @@ -0,0 +1,83 @@ +from uuid import ( + NAMESPACE_DNS, + NAMESPACE_OID, + NAMESPACE_URL, + NAMESPACE_X500, + RESERVED_FUTURE, + RESERVED_MICROSOFT, + RESERVED_NCS, + RFC_4122, + UUID, + getnode, +) + +import uuid_utils + +NIL = UUID("00000000-0000-0000-0000-000000000000") +MAX = UUID("ffffffff-ffff-ffff-ffff-ffffffffffff") + + +def uuid1(node=None, clock_seq=None): + """Generate a UUID from a host ID, sequence number, and the current time. + If 'node' is not given, getnode() is used to obtain the hardware + address. If 'clock_seq' is given, it is used as the sequence number; + otherwise a random 14-bit sequence number is chosen.""" + return UUID(int=uuid_utils.uuid1(node, clock_seq).int) + + +def uuid3(namespace, name): + """Generate a UUID from the MD5 hash of a namespace UUID and a name.""" + namespace = uuid_utils.UUID(namespace.hex) if namespace else namespace + return UUID(int=uuid_utils.uuid3(namespace, name).int) + + +def uuid4(): + """Generate a random UUID.""" + return UUID(int=uuid_utils.uuid4().int) + + +def uuid5(namespace, name): + """Generate a UUID from the SHA-1 hash of a namespace UUID and a name.""" + namespace = uuid_utils.UUID(namespace.hex) if namespace else namespace + return UUID(int=uuid_utils.uuid5(namespace, name).int) + + +def uuid6(node=None, timestamp=None): + """Generate a version 6 UUID using the given timestamp and a host ID. + This is similar to version 1 UUIDs, + except that it is lexicographically sortable by timestamp. + """ + return UUID(int=uuid_utils.uuid6(node, timestamp).int) + + +def uuid7(timestamp=None, nanos=None): + """Generate a version 7 UUID using a time value and random bytes.""" + return UUID(int=uuid_utils.uuid7(timestamp, nanos).int) + + +def uuid8(bytes): + """Generate a custom UUID comprised almost entirely of user-supplied bytes.""" + return UUID(bytes=uuid_utils.uuid8(bytes).bytes) + + +__all__ = [ + "MAX", + "NAMESPACE_DNS", + "NAMESPACE_OID", + "NAMESPACE_URL", + "NAMESPACE_X500", + "NIL", + "RESERVED_FUTURE", + "RESERVED_MICROSOFT", + "RESERVED_NCS", + "RFC_4122", + "UUID", + "getnode", + "uuid1", + "uuid3", + "uuid4", + "uuid5", + "uuid6", + "uuid7", + "uuid8", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uuid_utils/compat/__init__.pyi b/micromamba_root/envs/pytorch_env/Lib/site-packages/uuid_utils/compat/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..834bdf3555323905a96478dbb2cedd3ff4a9df7d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uuid_utils/compat/__init__.pyi @@ -0,0 +1,79 @@ +import sys +from typing import Final +from uuid import ( + NAMESPACE_DNS, + NAMESPACE_OID, + NAMESPACE_URL, + NAMESPACE_X500, + RESERVED_FUTURE, + RESERVED_MICROSOFT, + RESERVED_NCS, + RFC_4122, + UUID, + SafeUUID, + getnode, +) + +def uuid1(node: int | None = None, clock_seq: int | None = None) -> UUID: + """Generate a UUID from a host ID, sequence number, and the current time. + If 'node' is not given, getnode() is used to obtain the hardware + address. If 'clock_seq' is given, it is used as the sequence number; + otherwise a random 14-bit sequence number is chosen.""" + ... + +if sys.version_info >= (3, 12): + def uuid3(namespace: UUID, name: str | bytes) -> UUID: + """Generate a UUID from the MD5 hash of a namespace UUID and a name.""" + ... + +else: + def uuid3(namespace: UUID, name: str) -> UUID: + """Generate a UUID from the MD5 hash of a namespace UUID and a name.""" + ... + +def uuid4() -> UUID: + """Generate a random UUID.""" + ... + +if sys.version_info >= (3, 12): + def uuid5(namespace: UUID, name: str | bytes) -> UUID: + """Generate a UUID from the SHA-1 hash of a namespace UUID and a name.""" + ... +else: + def uuid5(namespace: UUID, name: str) -> UUID: + """Generate a UUID from the SHA-1 hash of a namespace UUID and a name.""" + ... + +def uuid6(node: int | None = None, timestamp: int | None = None) -> UUID: + """Generate a version 6 UUID using the given timestamp and a host ID. + This is similar to version 1 UUIDs, + except that it is lexicographically sortable by timestamp. + """ + ... + +def uuid7(timestamp: int | None = None, nanos: int | None = None) -> UUID: + """Generate a version 7 UUID using a time value and random bytes.""" + ... + +def uuid8(bytes: bytes) -> UUID: + """Generate a custom UUID comprised almost entirely of user-supplied bytes.""" + ... + +NIL: Final[UUID] +MAX: Final[UUID] + +__all__ = [ + "MAX", + "NAMESPACE_DNS", + "NAMESPACE_OID", + "NAMESPACE_URL", + "NAMESPACE_X500", + "NIL", + "RESERVED_FUTURE", + "RESERVED_MICROSOFT", + "RESERVED_NCS", + "RFC_4122", + "UUID", + "SafeUUID", + "getnode", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uuid_utils/compat/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uuid_utils/compat/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4010ddc127e33ddf0ee005d921f100f30f6058d3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uuid_utils/compat/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn-0.46.0.dist-info/licenses/LICENSE.md b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn-0.46.0.dist-info/licenses/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..a6bba14552c7673a7db57a5750ddb06508264273 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn-0.46.0.dist-info/licenses/LICENSE.md @@ -0,0 +1,27 @@ +Copyright © 2017-present, [Encode OSS Ltd](https://www.encode.io/). +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. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de38c07ec4e5f4ee2ac998d19b05f08b21681be1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/__main__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/__main__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31063bbd67b14935416b74632ee7c2541f13bbcf Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/__main__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/_compat.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/_compat.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd16b3ad3b9f3f4dfc6c59c6c4292f4f8d700cf4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/_compat.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/_subprocess.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/_subprocess.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a98f6f8c9389af568eaccabd0ddd568b38895aa3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/_subprocess.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/_types.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/_types.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c12e578bde73e522596509775f355d0cf79bcf2e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/_types.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/config.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/config.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2737b7c8b2febd9d571b7887b8735686b96b6452 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/config.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/importer.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/importer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bffc15180204a976f92baa39cb7dbbdc08bd6a2b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/importer.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/logging.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/logging.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a892dc8152d8eef7022c3d1edd34a16875ce1a08 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/logging.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/main.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/main.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1b3fad9b33d56c77d5983af7dad01bde14ce00d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/main.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/server.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f41511a3e61b35b2d24cc938232c5dcb7f5a3cc5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/server.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/workers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/workers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a573b37bf2b594c02398a12de6b3d5b9712f381c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/__pycache__/workers.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/lifespan/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/lifespan/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/lifespan/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/lifespan/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbcd98832c59610a79aa5111382149ca78d70196 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/lifespan/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/lifespan/__pycache__/off.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/lifespan/__pycache__/off.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2d5668c3a8f55d045bb07f98aca70f76d9f8583 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/lifespan/__pycache__/off.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/lifespan/__pycache__/on.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/lifespan/__pycache__/on.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8dddf6ec90d4fd1ede8e0f4d5818c6f7abf930da Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/lifespan/__pycache__/on.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/lifespan/off.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/lifespan/off.py new file mode 100644 index 0000000000000000000000000000000000000000..74554b1e2a149c37131168fbe283f3e2476a8f75 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/lifespan/off.py @@ -0,0 +1,17 @@ +from __future__ import annotations + +from typing import Any + +from uvicorn import Config + + +class LifespanOff: + def __init__(self, config: Config) -> None: + self.should_exit = False + self.state: dict[str, Any] = {} + + async def startup(self) -> None: + pass + + async def shutdown(self) -> None: + pass diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/lifespan/on.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/lifespan/on.py new file mode 100644 index 0000000000000000000000000000000000000000..71ac39472e9e07025f25c62b074b1d44df39cf8e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/lifespan/on.py @@ -0,0 +1,137 @@ +from __future__ import annotations + +import asyncio +import logging +from asyncio import Queue +from typing import Any + +from uvicorn import Config +from uvicorn._types import ( + LifespanScope, + LifespanShutdownCompleteEvent, + LifespanShutdownEvent, + LifespanShutdownFailedEvent, + LifespanStartupCompleteEvent, + LifespanStartupEvent, + LifespanStartupFailedEvent, +) + +LifespanReceiveMessage = LifespanStartupEvent | LifespanShutdownEvent +LifespanSendMessage = ( + LifespanStartupFailedEvent + | LifespanShutdownFailedEvent + | LifespanStartupCompleteEvent + | LifespanShutdownCompleteEvent +) + + +STATE_TRANSITION_ERROR = "Got invalid state transition on lifespan protocol." + + +class LifespanOn: + def __init__(self, config: Config) -> None: + if not config.loaded: + config.load() + + self.config = config + self.logger = logging.getLogger("uvicorn.error") + self.startup_event = asyncio.Event() + self.shutdown_event = asyncio.Event() + self.receive_queue: Queue[LifespanReceiveMessage] = asyncio.Queue() + self.error_occurred = False + self.startup_failed = False + self.shutdown_failed = False + self.should_exit = False + self.state: dict[str, Any] = {} + + async def startup(self) -> None: + self.logger.info("Waiting for application startup.") + + loop = asyncio.get_event_loop() + main_lifespan_task = loop.create_task(self.main()) # noqa: F841 + # Keep a hard reference to prevent garbage collection + # See https://github.com/Kludex/uvicorn/pull/972 + startup_event: LifespanStartupEvent = {"type": "lifespan.startup"} + await self.receive_queue.put(startup_event) + await self.startup_event.wait() + + if self.startup_failed or (self.error_occurred and self.config.lifespan == "on"): + self.logger.error("Application startup failed. Exiting.") + self.should_exit = True + else: + self.logger.info("Application startup complete.") + + async def shutdown(self) -> None: + if self.error_occurred: + return + self.logger.info("Waiting for application shutdown.") + shutdown_event: LifespanShutdownEvent = {"type": "lifespan.shutdown"} + await self.receive_queue.put(shutdown_event) + await self.shutdown_event.wait() + + if self.shutdown_failed or (self.error_occurred and self.config.lifespan == "on"): + self.logger.error("Application shutdown failed. Exiting.") + self.should_exit = True + else: + self.logger.info("Application shutdown complete.") + + async def main(self) -> None: + try: + app = self.config.loaded_app + scope: LifespanScope = { + "type": "lifespan", + "asgi": {"version": self.config.asgi_version, "spec_version": "2.0"}, + "state": self.state, + } + await app(scope, self.receive, self.send) + except BaseException as exc: + self.asgi = None + self.error_occurred = True + if self.startup_failed or self.shutdown_failed: + return + if self.config.lifespan == "auto": + msg = "ASGI 'lifespan' protocol appears unsupported." + self.logger.info(msg) + else: + msg = "Exception in 'lifespan' protocol\n" + self.logger.error(msg, exc_info=exc) + finally: + self.startup_event.set() + self.shutdown_event.set() + + async def send(self, message: LifespanSendMessage) -> None: + assert message["type"] in ( + "lifespan.startup.complete", + "lifespan.startup.failed", + "lifespan.shutdown.complete", + "lifespan.shutdown.failed", + ) + + if message["type"] == "lifespan.startup.complete": + assert not self.startup_event.is_set(), STATE_TRANSITION_ERROR + assert not self.shutdown_event.is_set(), STATE_TRANSITION_ERROR + self.startup_event.set() + + elif message["type"] == "lifespan.startup.failed": + assert not self.startup_event.is_set(), STATE_TRANSITION_ERROR + assert not self.shutdown_event.is_set(), STATE_TRANSITION_ERROR + self.startup_event.set() + self.startup_failed = True + if message.get("message"): + self.logger.error(message["message"]) + + elif message["type"] == "lifespan.shutdown.complete": + assert self.startup_event.is_set(), STATE_TRANSITION_ERROR + assert not self.shutdown_event.is_set(), STATE_TRANSITION_ERROR + self.shutdown_event.set() + + elif message["type"] == "lifespan.shutdown.failed": + assert self.startup_event.is_set(), STATE_TRANSITION_ERROR + assert not self.shutdown_event.is_set(), STATE_TRANSITION_ERROR + self.shutdown_event.set() + self.shutdown_failed = True + if message.get("message"): + self.logger.error(message["message"]) + + async def receive(self) -> LifespanReceiveMessage: + return await self.receive_queue.get() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/loops/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/loops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/loops/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/loops/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1c78a94b973d678e88402ee50d70ddc498bff32 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/loops/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/loops/__pycache__/asyncio.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/loops/__pycache__/asyncio.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8630d4793b623fb181795536a0538dab777e535 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/loops/__pycache__/asyncio.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/loops/__pycache__/auto.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/loops/__pycache__/auto.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7da1a668837dc7c40ad16f4977838a74d5b94d87 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/loops/__pycache__/auto.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/loops/__pycache__/uvloop.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/loops/__pycache__/uvloop.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..912909d2bd92087e5929a824e6a0dbb3c10dacf9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/loops/__pycache__/uvloop.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/loops/asyncio.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/loops/asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..ad6121ee086b0c3b2fc2cb8dd378134725c1edf6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/loops/asyncio.py @@ -0,0 +1,11 @@ +from __future__ import annotations + +import asyncio +import sys +from collections.abc import Callable + + +def asyncio_loop_factory(use_subprocess: bool = False) -> Callable[[], asyncio.AbstractEventLoop]: + if sys.platform == "win32" and not use_subprocess: + return asyncio.ProactorEventLoop + return asyncio.SelectorEventLoop diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/loops/auto.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/loops/auto.py new file mode 100644 index 0000000000000000000000000000000000000000..190839905566f0c0e59c6119604887c326078115 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/loops/auto.py @@ -0,0 +1,17 @@ +from __future__ import annotations + +import asyncio +from collections.abc import Callable + + +def auto_loop_factory(use_subprocess: bool = False) -> Callable[[], asyncio.AbstractEventLoop]: + try: + import uvloop # noqa + except ImportError: # pragma: no cover + from uvicorn.loops.asyncio import asyncio_loop_factory as loop_factory + + return loop_factory(use_subprocess=use_subprocess) + else: # pragma: no cover + from uvicorn.loops.uvloop import uvloop_loop_factory + + return uvloop_loop_factory(use_subprocess=use_subprocess) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/loops/uvloop.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/loops/uvloop.py new file mode 100644 index 0000000000000000000000000000000000000000..c6692c58f5c63501b2ad0f3d3c1d6b2336d88aad --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/loops/uvloop.py @@ -0,0 +1,10 @@ +from __future__ import annotations + +import asyncio +from collections.abc import Callable + +import uvloop + + +def uvloop_loop_factory(use_subprocess: bool = False) -> Callable[[], asyncio.AbstractEventLoop]: + return uvloop.new_event_loop diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5ddc8b4f707df44d77e633c9422326e561d05eb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/__pycache__/asgi2.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/__pycache__/asgi2.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba85de0cb3f94025895b171aeb9e40db46a532b3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/__pycache__/asgi2.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/__pycache__/message_logger.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/__pycache__/message_logger.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..239e967e9e3c896d4e2a1445315d3990ea1c0573 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/__pycache__/message_logger.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/__pycache__/proxy_headers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/__pycache__/proxy_headers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15988ec5fff57cec987b64cd640bdf2be1eee415 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/__pycache__/proxy_headers.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/__pycache__/wsgi.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/__pycache__/wsgi.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b90bb97fcaebc94c0bffb76c9f1d51b99bba108a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/__pycache__/wsgi.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/asgi2.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/asgi2.py new file mode 100644 index 0000000000000000000000000000000000000000..4e15d1599bab04ac38f56cf271d2ff9b1b9984c8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/asgi2.py @@ -0,0 +1,15 @@ +from uvicorn._types import ( + ASGI2Application, + ASGIReceiveCallable, + ASGISendCallable, + Scope, +) + + +class ASGI2Middleware: + def __init__(self, app: "ASGI2Application"): + self.app = app + + async def __call__(self, scope: "Scope", receive: "ASGIReceiveCallable", send: "ASGISendCallable") -> None: + instance = self.app(scope) + await instance(receive, send) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/message_logger.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/message_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..0174bcce6d48de946214d59bcae5543d38d89c3a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/message_logger.py @@ -0,0 +1,87 @@ +import logging +from typing import Any + +from uvicorn._types import ( + ASGI3Application, + ASGIReceiveCallable, + ASGIReceiveEvent, + ASGISendCallable, + ASGISendEvent, + WWWScope, +) +from uvicorn.logging import TRACE_LOG_LEVEL + +PLACEHOLDER_FORMAT = { + "body": "<{length} bytes>", + "bytes": "<{length} bytes>", + "text": "<{length} chars>", + "headers": "<...>", +} + + +def message_with_placeholders(message: Any) -> Any: + """ + Return an ASGI message, with any body-type content omitted and replaced + with a placeholder. + """ + new_message = message.copy() + for attr in PLACEHOLDER_FORMAT.keys(): + if message.get(attr) is not None: + content = message[attr] + placeholder = PLACEHOLDER_FORMAT[attr].format(length=len(content)) + new_message[attr] = placeholder + return new_message + + +class MessageLoggerMiddleware: + def __init__(self, app: "ASGI3Application"): + self.task_counter = 0 + self.app = app + self.logger = logging.getLogger("uvicorn.asgi") + + def trace(message: Any, *args: Any, **kwargs: Any) -> None: + self.logger.log(TRACE_LOG_LEVEL, message, *args, **kwargs) + + self.logger.trace = trace # type: ignore + + async def __call__( + self, + scope: "WWWScope", + receive: "ASGIReceiveCallable", + send: "ASGISendCallable", + ) -> None: + self.task_counter += 1 + + task_counter = self.task_counter + client = scope.get("client") + prefix = "%s:%d - ASGI" % (client[0], client[1]) if client else "ASGI" + + async def inner_receive() -> "ASGIReceiveEvent": + message = await receive() + logged_message = message_with_placeholders(message) + log_text = "%s [%d] Receive %s" + self.logger.trace( # type: ignore + log_text, prefix, task_counter, logged_message + ) + return message + + async def inner_send(message: "ASGISendEvent") -> None: + logged_message = message_with_placeholders(message) + log_text = "%s [%d] Send %s" + self.logger.trace( # type: ignore + log_text, prefix, task_counter, logged_message + ) + await send(message) + + logged_scope = message_with_placeholders(scope) + log_text = "%s [%d] Started scope=%s" + self.logger.trace(log_text, prefix, task_counter, logged_scope) # type: ignore + try: + await self.app(scope, inner_receive, inner_send) + except BaseException as exc: + log_text = "%s [%d] Raised exception" + self.logger.trace(log_text, prefix, task_counter) # type: ignore + raise exc from None + else: + log_text = "%s [%d] Completed" + self.logger.trace(log_text, prefix, task_counter) # type: ignore diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/proxy_headers.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/proxy_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..1b97fbfca29f1aaa8f59dbdd940117059519dc6a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/proxy_headers.py @@ -0,0 +1,174 @@ +from __future__ import annotations + +import ipaddress + +from uvicorn._types import ASGI3Application, ASGIReceiveCallable, ASGISendCallable, Scope + + +class ProxyHeadersMiddleware: + """Middleware for handling known proxy headers + + This middleware can be used when a known proxy is fronting the application, + and is trusted to be properly setting the `X-Forwarded-Proto` and + `X-Forwarded-For` headers with the connecting client information. + + Modifies the `client` and `scheme` information so that they reference + the connecting client, rather that the connecting proxy. + + References: + - + - + """ + + def __init__(self, app: ASGI3Application, trusted_hosts: list[str] | str = "127.0.0.1") -> None: + self.app = app + self.trusted_hosts = _TrustedHosts(trusted_hosts) + + async def __call__(self, scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None: + if scope["type"] == "lifespan": + return await self.app(scope, receive, send) + + client_addr = scope.get("client") + client_host = client_addr[0] if client_addr else None + + if client_host in self.trusted_hosts: + headers = dict(scope["headers"]) + + if b"x-forwarded-proto" in headers: + x_forwarded_proto = headers[b"x-forwarded-proto"].decode("latin1").strip() + + if x_forwarded_proto in {"http", "https", "ws", "wss"}: + if scope["type"] == "websocket": + scope["scheme"] = x_forwarded_proto.replace("http", "ws") + else: + scope["scheme"] = x_forwarded_proto + + if b"x-forwarded-for" in headers: + x_forwarded_for = headers[b"x-forwarded-for"].decode("latin1") + host, port = self.trusted_hosts.get_trusted_client_address(x_forwarded_for) + + if host: + # If the x-forwarded-for header is empty then host is an empty string. + # Only set the client if we actually got something usable. + # See: https://github.com/Kludex/uvicorn/issues/1068 + scope["client"] = (host, port) + + return await self.app(scope, receive, send) + + +def _parse_raw_hosts(value: str) -> list[str]: + return [item.strip() for item in value.split(",")] + + +def _parse_host_port(value: str) -> tuple[str, int]: + """Parse a forwarded host value into host and optional port. + + Accepts bare IPs, IPv4 `host:port`, and bracketed IPv6 `[host]:port`. + Any unrecognized or malformed value is treated conservatively and returned + without a port so trust checks do not silently normalize arbitrary input. + """ + + if value.startswith("["): + bracket_end = value.find("]") + if bracket_end == -1: + return value, 0 + + host = value[1:bracket_end] + remainder = value[bracket_end + 1 :] + if not remainder: + return host, 0 + if not remainder.startswith(":"): + return value, 0 + + try: + return host, int(remainder[1:]) + except ValueError: + return host, 0 + + if value.count(":") == 1: + host, port = value.rsplit(":", 1) + try: + return host, int(port) + except ValueError: + return value, 0 + + return value, 0 + + +class _TrustedHosts: + """Container for trusted hosts and networks""" + + def __init__(self, trusted_hosts: list[str] | str) -> None: + self.always_trust: bool = trusted_hosts in ("*", ["*"]) + + self.trusted_literals: set[str] = set() + self.trusted_hosts: set[ipaddress.IPv4Address | ipaddress.IPv6Address] = set() + self.trusted_networks: set[ipaddress.IPv4Network | ipaddress.IPv6Network] = set() + + # Notes: + # - We separate hosts from literals as there are many ways to write + # an IPv6 Address so we need to compare by object. + # - We don't convert IP Address to single host networks (e.g. /32 / 128) as + # it more efficient to do an address lookup in a set than check for + # membership in each network. + # - We still allow literals as it might be possible that we receive a + # something that isn't an IP Address e.g. a unix socket. + + if not self.always_trust: + if isinstance(trusted_hosts, str): + trusted_hosts = _parse_raw_hosts(trusted_hosts) + + for host in trusted_hosts: + # Note: because we always convert invalid IP types to literals it + # is not possible for the user to know they provided a malformed IP + # type - this may lead to unexpected / difficult to debug behaviour. + + if "/" in host: + # Looks like a network + try: + self.trusted_networks.add(ipaddress.ip_network(host)) + except ValueError: + # Was not a valid IP Network + self.trusted_literals.add(host) + else: + try: + self.trusted_hosts.add(ipaddress.ip_address(host)) + except ValueError: + # Was not a valid IP Address + self.trusted_literals.add(host) + + def __contains__(self, host: str | None) -> bool: + if self.always_trust: + return True + + if not host: + return False + + try: + ip = ipaddress.ip_address(host) + if ip in self.trusted_hosts: + return True + return any(ip in net for net in self.trusted_networks) + + except ValueError: + return host in self.trusted_literals + + def get_trusted_client_address(self, x_forwarded_for: str) -> tuple[str, int]: + """Extract the client address from x_forwarded_for header. + + In general this is the first "untrusted" host in the forwarded for list. + """ + x_forwarded_for_hosts = _parse_raw_hosts(x_forwarded_for) + + if self.always_trust: + return _parse_host_port(x_forwarded_for_hosts[0]) + + # Note: each proxy appends to the header list so check it in reverse order + for host_port in reversed(x_forwarded_for_hosts): + host, port = _parse_host_port(host_port) + if host not in self: + return host, port + + # All hosts are trusted meaning that the client was also a trusted proxy + # See https://github.com/Kludex/uvicorn/issues/1068#issuecomment-855371576 + return _parse_host_port(x_forwarded_for_hosts[0]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/wsgi.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/wsgi.py new file mode 100644 index 0000000000000000000000000000000000000000..b2e3cb77d421085947741430e8b5451821eb66c7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/middleware/wsgi.py @@ -0,0 +1,199 @@ +from __future__ import annotations + +import asyncio +import concurrent.futures +import io +import sys +import warnings +from collections import deque +from collections.abc import Iterable + +from uvicorn._types import ( + ASGIReceiveCallable, + ASGIReceiveEvent, + ASGISendCallable, + ASGISendEvent, + Environ, + ExcInfo, + HTTPRequestEvent, + HTTPResponseBodyEvent, + HTTPResponseStartEvent, + HTTPScope, + StartResponse, + WSGIApp, +) + + +def build_environ(scope: HTTPScope, message: ASGIReceiveEvent, body: io.BytesIO) -> Environ: + """ + Builds a scope and request message into a WSGI environ object. + """ + script_name = scope.get("root_path", "").encode("utf8").decode("latin1") + path_info = scope["path"].encode("utf8").decode("latin1") + if path_info.startswith(script_name): + path_info = path_info[len(script_name) :] + environ = { + "REQUEST_METHOD": scope["method"], + "SCRIPT_NAME": script_name, + "PATH_INFO": path_info, + "QUERY_STRING": scope["query_string"].decode("ascii"), + "SERVER_PROTOCOL": "HTTP/%s" % scope["http_version"], + "wsgi.version": (1, 0), + "wsgi.url_scheme": scope.get("scheme", "http"), + "wsgi.input": body, + "wsgi.errors": sys.stdout, + "wsgi.multithread": True, + "wsgi.multiprocess": True, + "wsgi.run_once": False, + } + + # Get server name and port - required in WSGI, not in ASGI + server = scope.get("server") + if server is None: + server = ("localhost", 80) + environ["SERVER_NAME"] = server[0] + environ["SERVER_PORT"] = server[1] + + # Get client IP address + client = scope.get("client") + if client is not None: + environ["REMOTE_ADDR"] = client[0] + + # Go through headers and make them into environ entries + for name, value in scope.get("headers", []): + name_str: str = name.decode("latin1") + if name_str == "content-length": + corrected_name = "CONTENT_LENGTH" + elif name_str == "content-type": + corrected_name = "CONTENT_TYPE" + else: + corrected_name = "HTTP_%s" % name_str.upper().replace("-", "_") + # HTTPbis say only ASCII chars are allowed in headers, but we latin1 + # just in case + value_str: str = value.decode("latin1") + if corrected_name in environ: + corrected_name_environ = environ[corrected_name] + assert isinstance(corrected_name_environ, str) + value_str = corrected_name_environ + "," + value_str + environ[corrected_name] = value_str + return environ + + +class _WSGIMiddleware: + def __init__(self, app: WSGIApp, workers: int = 10): + warnings.warn( + "Uvicorn's native WSGI implementation is deprecated, you should switch to a2wsgi (`pip install a2wsgi`).", + DeprecationWarning, + ) + self.app = app + self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=workers) + + async def __call__( + self, + scope: HTTPScope, + receive: ASGIReceiveCallable, + send: ASGISendCallable, + ) -> None: + assert scope["type"] == "http" + instance = WSGIResponder(self.app, self.executor, scope) + await instance(receive, send) + + +class WSGIResponder: + def __init__( + self, + app: WSGIApp, + executor: concurrent.futures.ThreadPoolExecutor, + scope: HTTPScope, + ): + self.app = app + self.executor = executor + self.scope = scope + self.status = None + self.response_headers = None + self.send_event = asyncio.Event() + self.send_queue: deque[ASGISendEvent | None] = deque() + self.loop: asyncio.AbstractEventLoop = asyncio.get_event_loop() + self.response_started = False + self.exc_info: ExcInfo | None = None + + async def __call__(self, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None: + message: HTTPRequestEvent = await receive() # type: ignore[assignment] + body = io.BytesIO(message.get("body", b"")) + more_body = message.get("more_body", False) + if more_body: + body.seek(0, io.SEEK_END) + while more_body: + body_message: HTTPRequestEvent = ( + await receive() # type: ignore[assignment] + ) + body.write(body_message.get("body", b"")) + more_body = body_message.get("more_body", False) + body.seek(0) + environ = build_environ(self.scope, message, body) + self.loop = asyncio.get_event_loop() + wsgi = self.loop.run_in_executor(self.executor, self.wsgi, environ, self.start_response) + sender = self.loop.create_task(self.sender(send)) + try: + await asyncio.wait_for(wsgi, None) + finally: + self.send_queue.append(None) + self.send_event.set() + await asyncio.wait_for(sender, None) + if self.exc_info is not None: + raise self.exc_info[0].with_traceback(self.exc_info[1], self.exc_info[2]) + + async def sender(self, send: ASGISendCallable) -> None: + while True: + if self.send_queue: + message = self.send_queue.popleft() + if message is None: + return + await send(message) + else: # pragma: no cover + await self.send_event.wait() + self.send_event.clear() + + def start_response( + self, + status: str, + response_headers: Iterable[tuple[str, str]], + exc_info: ExcInfo | None = None, + ) -> None: + self.exc_info = exc_info + if not self.response_started: + self.response_started = True + status_code_str, _ = status.split(" ", 1) + status_code = int(status_code_str) + headers = [(name.encode("ascii"), value.encode("ascii")) for name, value in response_headers] + http_response_start_event: HTTPResponseStartEvent = { + "type": "http.response.start", + "status": status_code, + "headers": headers, + } + self.send_queue.append(http_response_start_event) + self.loop.call_soon_threadsafe(self.send_event.set) + + def wsgi(self, environ: Environ, start_response: StartResponse) -> None: + for chunk in self.app(environ, start_response): # type: ignore + response_body: HTTPResponseBodyEvent = { + "type": "http.response.body", + "body": chunk, + "more_body": True, + } + self.send_queue.append(response_body) + self.loop.call_soon_threadsafe(self.send_event.set) + + empty_body: HTTPResponseBodyEvent = { + "type": "http.response.body", + "body": b"", + "more_body": False, + } + self.send_queue.append(empty_body) + self.loop.call_soon_threadsafe(self.send_event.set) + + +try: + from a2wsgi import WSGIMiddleware +except ModuleNotFoundError: # pragma: no cover + WSGIMiddleware = _WSGIMiddleware # type: ignore[misc, assignment] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82b3203caf54ba8d108cd07a63bc1f728ffd0179 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/__pycache__/utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf676684da214349adf058463f6149621c031809 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/__pycache__/utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f02f96c318e9d67bd3a972f75e9cc1ab5c4914f5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/__pycache__/auto.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/__pycache__/auto.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb7e8f861a04266f4f854dcd035da20bf3c99aba Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/__pycache__/auto.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/__pycache__/flow_control.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/__pycache__/flow_control.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..376f37744d19cd867f5b51313b6578ea391b6928 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/__pycache__/flow_control.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/__pycache__/h11_impl.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/__pycache__/h11_impl.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..294e47d7d0e26d018552ca8de864a61ece6b107a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/__pycache__/h11_impl.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/__pycache__/httptools_impl.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/__pycache__/httptools_impl.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9835bb6eef8cba363bcc59978419a7ab733b67a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/__pycache__/httptools_impl.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/auto.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/auto.py new file mode 100644 index 0000000000000000000000000000000000000000..a14bec144a97a5e3718a768abe3b6a9e7e93d2c1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/auto.py @@ -0,0 +1,15 @@ +from __future__ import annotations + +import asyncio + +AutoHTTPProtocol: type[asyncio.Protocol] +try: + import httptools # noqa +except ImportError: # pragma: no cover + from uvicorn.protocols.http.h11_impl import H11Protocol + + AutoHTTPProtocol = H11Protocol +else: # pragma: no cover + from uvicorn.protocols.http.httptools_impl import HttpToolsProtocol + + AutoHTTPProtocol = HttpToolsProtocol diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/flow_control.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/flow_control.py new file mode 100644 index 0000000000000000000000000000000000000000..2d1b5fa2d3366fd6584181a26c8569a0207900cc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/flow_control.py @@ -0,0 +1,54 @@ +import asyncio + +from uvicorn._types import ASGIReceiveCallable, ASGISendCallable, Scope + +CLOSE_HEADER = (b"connection", b"close") + +HIGH_WATER_LIMIT = 65536 + + +class FlowControl: + def __init__(self, transport: asyncio.Transport) -> None: + self._transport = transport + self.read_paused = False + self.write_paused = False + self._is_writable_event = asyncio.Event() + self._is_writable_event.set() + + async def drain(self) -> None: + await self._is_writable_event.wait() # pragma: full coverage + + def pause_reading(self) -> None: + if not self.read_paused: + self.read_paused = True + self._transport.pause_reading() + + def resume_reading(self) -> None: + if self.read_paused: + self.read_paused = False + self._transport.resume_reading() + + def pause_writing(self) -> None: + if not self.write_paused: # pragma: full coverage + self.write_paused = True + self._is_writable_event.clear() + + def resume_writing(self) -> None: + if self.write_paused: # pragma: full coverage + self.write_paused = False + self._is_writable_event.set() + + +async def service_unavailable(scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None: + await send( + { + "type": "http.response.start", + "status": 503, + "headers": [ + (b"content-type", b"text/plain; charset=utf-8"), + (b"content-length", b"19"), + (b"connection", b"close"), + ], + } + ) + await send({"type": "http.response.body", "body": b"Service Unavailable", "more_body": False}) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/h11_impl.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/h11_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..cb68ea0eca449756f860cfea3996ecd158624f8f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/h11_impl.py @@ -0,0 +1,544 @@ +from __future__ import annotations + +import asyncio +import contextvars +import http +import logging +import sys +from collections.abc import Callable +from typing import Any, Literal +from urllib.parse import unquote + +import h11 +from h11._connection import DEFAULT_MAX_INCOMPLETE_EVENT_SIZE + +from uvicorn._types import ( + ASGI3Application, + ASGIReceiveEvent, + ASGISendEvent, + HTTPRequestEvent, + HTTPResponseBodyEvent, + HTTPResponseStartEvent, + HTTPScope, +) +from uvicorn.config import Config +from uvicorn.logging import TRACE_LOG_LEVEL +from uvicorn.protocols.http.flow_control import CLOSE_HEADER, HIGH_WATER_LIMIT, FlowControl, service_unavailable +from uvicorn.protocols.utils import get_client_addr, get_local_addr, get_path_with_query_string, get_remote_addr, is_ssl +from uvicorn.server import ServerState + + +def _get_status_phrase(status_code: int) -> bytes: + try: + return http.HTTPStatus(status_code).phrase.encode() + except ValueError: + return b"" + + +STATUS_PHRASES = {status_code: _get_status_phrase(status_code) for status_code in range(100, 600)} + + +class H11Protocol(asyncio.Protocol): + def __init__( + self, + config: Config, + server_state: ServerState, + app_state: dict[str, Any], + _loop: asyncio.AbstractEventLoop | None = None, + ) -> None: + if not config.loaded: + config.load() + + self.config = config + self.app = config.loaded_app + self.loop = _loop or asyncio.get_event_loop() + self.logger = logging.getLogger("uvicorn.error") + self.access_logger = logging.getLogger("uvicorn.access") + self.access_log = self.access_logger.hasHandlers() + self.conn = h11.Connection( + h11.SERVER, + config.h11_max_incomplete_event_size + if config.h11_max_incomplete_event_size is not None + else DEFAULT_MAX_INCOMPLETE_EVENT_SIZE, + ) + self.ws_protocol_class = config.ws_protocol_class + self.root_path = config.root_path + self.limit_concurrency = config.limit_concurrency + self.app_state = app_state + + # Timeouts + self.timeout_keep_alive_task: asyncio.TimerHandle | None = None + self.timeout_keep_alive = config.timeout_keep_alive + + # Shared server state + self.server_state = server_state + self.connections = server_state.connections + self.tasks = server_state.tasks + + # Per-connection state + self.transport: asyncio.Transport = None # type: ignore[assignment] + self.flow: FlowControl = None # type: ignore[assignment] + self.server: tuple[str, int | None] | None = None + self.client: tuple[str, int] | None = None + self.scheme: Literal["http", "https"] | None = None + + # Per-request state + self.scope: HTTPScope = None # type: ignore[assignment] + self.headers: list[tuple[bytes, bytes]] = None # type: ignore[assignment] + self.cycle: RequestResponseCycle = None # type: ignore[assignment] + + # Protocol interface + def connection_made( # type: ignore[override] + self, transport: asyncio.Transport + ) -> None: + self.connections.add(self) + + self.transport = transport + self.flow = FlowControl(transport) + self.server = get_local_addr(transport) + self.client = get_remote_addr(transport) + self.scheme = "https" if is_ssl(transport) else "http" + + if self.logger.level <= TRACE_LOG_LEVEL: + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sHTTP connection made", prefix) + + def connection_lost(self, exc: Exception | None) -> None: + self.connections.discard(self) + + if self.logger.level <= TRACE_LOG_LEVEL: + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sHTTP connection lost", prefix) + + if self.cycle and not self.cycle.response_complete: + self.cycle.disconnected = True + if self.conn.our_state != h11.ERROR: + event = h11.ConnectionClosed() + try: + self.conn.send(event) + except h11.LocalProtocolError: + # Premature client disconnect + pass + + if self.cycle is not None: + self.cycle.message_event.set() + if self.flow is not None: + self.flow.resume_writing() + if exc is None: + self.transport.close() + self._unset_keepalive_if_required() + + def eof_received(self) -> None: + pass + + def _unset_keepalive_if_required(self) -> None: + if self.timeout_keep_alive_task is not None: + self.timeout_keep_alive_task.cancel() + self.timeout_keep_alive_task = None + + def _get_upgrade(self) -> bytes | None: + connection = [] + upgrade = None + for name, value in self.headers: + if name == b"connection": + connection = [token.lower().strip() for token in value.split(b",")] + if name == b"upgrade": + upgrade = value.lower() + if b"upgrade" in connection: + return upgrade + return None + + def _should_upgrade_to_ws(self) -> bool: + if self.ws_protocol_class is None: + return False + return True + + def _unsupported_upgrade_warning(self) -> None: + msg = "Unsupported upgrade request." + self.logger.warning(msg) + if not self._should_upgrade_to_ws(): + msg = "No supported WebSocket library detected. Please use \"pip install 'uvicorn[standard]'\", or install 'websockets' or 'wsproto' manually." # noqa: E501 + self.logger.warning(msg) + + def _should_upgrade(self) -> bool: + upgrade = self._get_upgrade() + if upgrade == b"websocket" and self._should_upgrade_to_ws(): + return True + if upgrade is not None: + self._unsupported_upgrade_warning() + return False + + def data_received(self, data: bytes) -> None: + self._unset_keepalive_if_required() + + self.conn.receive_data(data) + self.handle_events() + + def handle_events(self) -> None: + while True: + try: + event = self.conn.next_event() + except h11.RemoteProtocolError: + msg = "Invalid HTTP request received." + self.logger.warning(msg) + self.send_400_response(msg) + return + + if event is h11.NEED_DATA: + break + + elif event is h11.PAUSED: + # This case can occur in HTTP pipelining, so we need to + # stop reading any more data, and ensure that at the end + # of the active request/response cycle we handle any + # events that have been buffered up. + self.flow.pause_reading() + break + + elif isinstance(event, h11.Request): + self.headers = [(key.lower(), value) for key, value in event.headers] + raw_path, _, query_string = event.target.partition(b"?") + path = unquote(raw_path.decode("ascii")) + full_path = self.root_path + path + full_raw_path = self.root_path.encode("ascii") + raw_path + self.scope = { + "type": "http", + "asgi": {"version": self.config.asgi_version, "spec_version": "2.3"}, + "http_version": event.http_version.decode("ascii"), + "server": self.server, + "client": self.client, + "scheme": self.scheme, # type: ignore[typeddict-item] + "method": event.method.decode("ascii"), + "root_path": self.root_path, + "path": full_path, + "raw_path": full_raw_path, + "query_string": query_string, + "headers": self.headers, + "state": self.app_state.copy(), + } + if self._should_upgrade(): + self.handle_websocket_upgrade(event) + return + + # Handle 503 responses when 'limit_concurrency' is exceeded. + if self.limit_concurrency is not None and ( + len(self.connections) >= self.limit_concurrency or len(self.tasks) >= self.limit_concurrency + ): + app = service_unavailable + message = "Exceeded concurrency limit." + self.logger.warning(message) + else: + app = self.app + + # When starting to process a request, disable the keep-alive + # timeout. Normally we disable this when receiving data from + # client and set back when finishing processing its request. + # However, for pipelined requests processing finishes after + # already receiving the next request and thus the timer may + # be set here, which we don't want. + self._unset_keepalive_if_required() + + self.cycle = RequestResponseCycle( + scope=self.scope, + conn=self.conn, + transport=self.transport, + flow=self.flow, + logger=self.logger, + access_logger=self.access_logger, + access_log=self.access_log, + default_headers=self.server_state.default_headers, + message_event=asyncio.Event(), + on_response=self.on_response_complete, + ) + if self.config.reset_contextvars: + # Opt-in workaround for https://github.com/python/cpython/issues/140947: + # asyncio can leak context vars between tasks. Hides context set in the + # lifespan or by external instrumentation. + if sys.version_info >= (3, 11): # pragma: py-lt-311 + task = self.loop.create_task(self.cycle.run_asgi(app), context=contextvars.Context()) + else: # pragma: py-gte-311 + task = contextvars.Context().run(self.loop.create_task, self.cycle.run_asgi(app)) + else: + task = self.loop.create_task(self.cycle.run_asgi(app)) + task.add_done_callback(self.tasks.discard) + self.tasks.add(task) + + elif isinstance(event, h11.Data): + if self.conn.our_state is h11.DONE: + continue + self.cycle.body += event.data + if len(self.cycle.body) > HIGH_WATER_LIMIT: + self.flow.pause_reading() + self.cycle.message_event.set() + + elif isinstance(event, h11.EndOfMessage): + if self.conn.our_state is h11.DONE: + self.transport.resume_reading() + self.conn.start_next_cycle() + continue + self.cycle.more_body = False + self.cycle.message_event.set() + if self.conn.their_state == h11.MUST_CLOSE: + break + + def handle_websocket_upgrade(self, event: h11.Request) -> None: + if self.logger.level <= TRACE_LOG_LEVEL: # pragma: full coverage + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sUpgrading to WebSocket", prefix) + + self.connections.discard(self) + output = [event.method, b" ", event.target, b" HTTP/1.1\r\n"] + for name, value in self.headers: + output += [name, b": ", value, b"\r\n"] + output.append(b"\r\n") + protocol = self.ws_protocol_class( # type: ignore[call-arg, misc] + config=self.config, + server_state=self.server_state, + app_state=self.app_state, + ) + protocol.connection_made(self.transport) + protocol.data_received(b"".join(output)) + self.transport.set_protocol(protocol) + + def send_400_response(self, msg: str) -> None: + reason = STATUS_PHRASES[400] + headers: list[tuple[bytes, bytes]] = [ + (b"content-type", b"text/plain; charset=utf-8"), + (b"connection", b"close"), + ] + event = h11.Response(status_code=400, headers=headers, reason=reason) + output = self.conn.send(event) + self.transport.write(output) + + output = self.conn.send(event=h11.Data(data=msg.encode("ascii"))) + self.transport.write(output) + + output = self.conn.send(event=h11.EndOfMessage()) + self.transport.write(output) + + self.transport.close() + + def on_response_complete(self) -> None: + self.server_state.total_requests += 1 + + if self.transport.is_closing(): + return + + # Set a short Keep-Alive timeout. + self._unset_keepalive_if_required() + + self.timeout_keep_alive_task = self.loop.call_later(self.timeout_keep_alive, self.timeout_keep_alive_handler) + + # Unpause data reads if needed. + self.flow.resume_reading() + + # Unblock any pipelined events. + if self.conn.our_state is h11.DONE and self.conn.their_state is h11.DONE: + self.conn.start_next_cycle() + self.handle_events() + + def shutdown(self) -> None: + """ + Called by the server to commence a graceful shutdown. + """ + if self.cycle is None or self.cycle.response_complete: + event = h11.ConnectionClosed() + self.conn.send(event) + self.transport.close() + else: + self.cycle.keep_alive = False + + def pause_writing(self) -> None: + """ + Called by the transport when the write buffer exceeds the high water mark. + """ + self.flow.pause_writing() # pragma: full coverage + + def resume_writing(self) -> None: + """ + Called by the transport when the write buffer drops below the low water mark. + """ + self.flow.resume_writing() # pragma: full coverage + + def timeout_keep_alive_handler(self) -> None: + """ + Called on a keep-alive connection if no new data is received after a short + delay. + """ + if not self.transport.is_closing(): + event = h11.ConnectionClosed() + self.conn.send(event) + self.transport.close() + + +class RequestResponseCycle: + def __init__( + self, + scope: HTTPScope, + conn: h11.Connection, + transport: asyncio.Transport, + flow: FlowControl, + logger: logging.Logger, + access_logger: logging.Logger, + access_log: bool, + default_headers: list[tuple[bytes, bytes]], + message_event: asyncio.Event, + on_response: Callable[..., None], + ) -> None: + self.scope = scope + self.conn = conn + self.transport = transport + self.flow = flow + self.logger = logger + self.access_logger = access_logger + self.access_log = access_log + self.default_headers = default_headers + self.message_event = message_event + self.on_response = on_response + + # Connection state + self.disconnected = False + self.keep_alive = True + self.waiting_for_100_continue = conn.they_are_waiting_for_100_continue + + # Request state + self.body = bytearray() + self.more_body = True + + # Response state + self.response_started = False + self.response_complete = False + + # ASGI exception wrapper + async def run_asgi(self, app: ASGI3Application) -> None: + try: + result = await app( # type: ignore[func-returns-value] + self.scope, self.receive, self.send + ) + except BaseException as exc: + msg = "Exception in ASGI application\n" + self.logger.error(msg, exc_info=exc) + if not self.response_started: + await self.send_500_response() + else: + self.transport.close() + else: + if result is not None: + msg = "ASGI callable should return None, but returned '%s'." + self.logger.error(msg, result) + self.transport.close() + elif not self.response_started and not self.disconnected: + msg = "ASGI callable returned without starting response." + self.logger.error(msg) + await self.send_500_response() + elif not self.response_complete and not self.disconnected: + msg = "ASGI callable returned without completing response." + self.logger.error(msg) + self.transport.close() + finally: + self.on_response = lambda: None + + async def send_500_response(self) -> None: + response_start_event: HTTPResponseStartEvent = { + "type": "http.response.start", + "status": 500, + "headers": [ + (b"content-type", b"text/plain; charset=utf-8"), + (b"connection", b"close"), + ], + } + await self.send(response_start_event) + response_body_event: HTTPResponseBodyEvent = { + "type": "http.response.body", + "body": b"Internal Server Error", + "more_body": False, + } + await self.send(response_body_event) + + # ASGI interface + async def send(self, message: ASGISendEvent) -> None: + if self.flow.write_paused and not self.disconnected: + await self.flow.drain() # pragma: full coverage + + if self.disconnected: + return # pragma: full coverage + + if not self.response_started: + # Sending response status line and headers + if message["type"] != "http.response.start": + raise RuntimeError(f"Expected ASGI message 'http.response.start', but got '{message['type']}'.") + + self.response_started = True + self.waiting_for_100_continue = False + + status = message["status"] + headers = self.default_headers + list(message.get("headers", [])) + + if CLOSE_HEADER in self.scope["headers"] and CLOSE_HEADER not in headers: + headers = headers + [CLOSE_HEADER] + + if self.access_log: + self.access_logger.info( + '%s - "%s %s HTTP/%s" %d', + get_client_addr(self.scope), + self.scope["method"], + get_path_with_query_string(self.scope), + self.scope["http_version"], + status, + ) + + # Write response status line and headers + reason = STATUS_PHRASES[status] + response = h11.Response(status_code=status, headers=headers, reason=reason) + output = self.conn.send(event=response) + self.transport.write(output) + + elif not self.response_complete: + # Sending response body + if message["type"] != "http.response.body": + raise RuntimeError(f"Expected ASGI message 'http.response.body', but got '{message['type']}'.") + + body = message.get("body", b"") + more_body = message.get("more_body", False) + + # Write response body + data = b"" if self.scope["method"] == "HEAD" else body + output = self.conn.send(event=h11.Data(data=data)) + self.transport.write(output) + + # Handle response completion + if not more_body: + self.response_complete = True + self.message_event.set() + output = self.conn.send(event=h11.EndOfMessage()) + self.transport.write(output) + + else: + # Response already sent + raise RuntimeError(f"Unexpected ASGI message '{message['type']}' sent, after response already completed.") + + if self.response_complete: + if self.conn.our_state is h11.MUST_CLOSE or not self.keep_alive: + self.conn.send(event=h11.ConnectionClosed()) + self.transport.close() + self.on_response() + + async def receive(self) -> ASGIReceiveEvent: + if self.waiting_for_100_continue and not self.transport.is_closing(): + headers: list[tuple[str, str]] = [] + event = h11.InformationalResponse(status_code=100, headers=headers, reason="Continue") + output = self.conn.send(event=event) + self.transport.write(output) + self.waiting_for_100_continue = False + + if not self.disconnected and not self.response_complete: + self.flow.resume_reading() + await self.message_event.wait() + self.message_event.clear() + + if self.disconnected or self.response_complete: + return {"type": "http.disconnect"} + + message: HTTPRequestEvent = {"type": "http.request", "body": bytes(self.body), "more_body": self.more_body} + self.body = bytearray() + return message diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/httptools_impl.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/httptools_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..1aa49d8523b773afac2c6fc7f0bd4db9f54aeacf --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/http/httptools_impl.py @@ -0,0 +1,576 @@ +from __future__ import annotations + +import asyncio +import contextvars +import http +import logging +import re +import sys +import urllib +from asyncio.events import TimerHandle +from collections import deque +from collections.abc import Callable +from typing import Any, Literal + +import httptools + +from uvicorn._types import ( + ASGI3Application, + ASGIReceiveEvent, + ASGISendEvent, + HTTPRequestEvent, + HTTPScope, +) +from uvicorn.config import Config +from uvicorn.logging import TRACE_LOG_LEVEL +from uvicorn.protocols.http.flow_control import CLOSE_HEADER, HIGH_WATER_LIMIT, FlowControl, service_unavailable +from uvicorn.protocols.utils import get_client_addr, get_local_addr, get_path_with_query_string, get_remote_addr, is_ssl +from uvicorn.server import ServerState + +HEADER_RE = re.compile(b'[\x00-\x1f\x7f()<>@,;:\\[\\]={} \t\\\\"]') +HEADER_VALUE_RE = re.compile(b"[\x00-\x08\x0a-\x1f\x7f]") + + +def _get_status_line(status_code: int) -> bytes: + try: + phrase = http.HTTPStatus(status_code).phrase.encode() + except ValueError: + phrase = b"" + return b"".join([b"HTTP/1.1 ", str(status_code).encode(), b" ", phrase, b"\r\n"]) + + +STATUS_LINE = {status_code: _get_status_line(status_code) for status_code in range(100, 600)} + + +class HttpToolsProtocol(asyncio.Protocol): + def __init__( + self, + config: Config, + server_state: ServerState, + app_state: dict[str, Any], + _loop: asyncio.AbstractEventLoop | None = None, + ) -> None: + if not config.loaded: + config.load() + + self.config = config + self.app = config.loaded_app + self.loop = _loop or asyncio.get_event_loop() + self.logger = logging.getLogger("uvicorn.error") + self.access_logger = logging.getLogger("uvicorn.access") + self.access_log = self.access_logger.hasHandlers() + self.parser = httptools.HttpRequestParser(self) + + try: + # Enable dangerous leniencies to allow server to a response on the first request from a pipelined request. + self.parser.set_dangerous_leniencies(lenient_data_after_close=True) + except AttributeError: # pragma: no cover + # httptools < 0.6.3 + pass + + self.ws_protocol_class = config.ws_protocol_class + self.root_path = config.root_path + self.limit_concurrency = config.limit_concurrency + self.app_state = app_state + + # Timeouts + self.timeout_keep_alive_task: TimerHandle | None = None + self.timeout_keep_alive = config.timeout_keep_alive + + # Global state + self.server_state = server_state + self.connections = server_state.connections + self.tasks = server_state.tasks + + # Per-connection state + self.transport: asyncio.Transport = None # type: ignore[assignment] + self.flow: FlowControl = None # type: ignore[assignment] + self.server: tuple[str, int | None] | None = None + self.client: tuple[str, int] | None = None + self.scheme: Literal["http", "https"] | None = None + self.pipeline: deque[tuple[RequestResponseCycle, ASGI3Application]] = deque() + + # Per-request state + self.scope: HTTPScope = None # type: ignore[assignment] + self.headers: list[tuple[bytes, bytes]] = None # type: ignore[assignment] + self.expect_100_continue = False + self.cycle: RequestResponseCycle = None # type: ignore[assignment] + + # Protocol interface + def connection_made( # type: ignore[override] + self, transport: asyncio.Transport + ) -> None: + self.connections.add(self) + + self.transport = transport + self.flow = FlowControl(transport) + self.server = get_local_addr(transport) + self.client = get_remote_addr(transport) + self.scheme = "https" if is_ssl(transport) else "http" + + if self.logger.level <= TRACE_LOG_LEVEL: + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sHTTP connection made", prefix) + + def connection_lost(self, exc: Exception | None) -> None: + self.connections.discard(self) + + if self.logger.level <= TRACE_LOG_LEVEL: + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sHTTP connection lost", prefix) + + if self.cycle and not self.cycle.response_complete: + self.cycle.disconnected = True + if self.cycle is not None: + self.cycle.message_event.set() + if self.flow is not None: + self.flow.resume_writing() + if exc is None: + self.transport.close() + self._unset_keepalive_if_required() + + self.parser = None + + def eof_received(self) -> None: + pass + + def _unset_keepalive_if_required(self) -> None: + if self.timeout_keep_alive_task is not None: + self.timeout_keep_alive_task.cancel() + self.timeout_keep_alive_task = None + + def _get_upgrade(self) -> bytes | None: + connection = [] + upgrade = None + for name, value in self.headers: + if name == b"connection": + connection = [token.lower().strip() for token in value.split(b",")] + if name == b"upgrade": + upgrade = value.lower() + if b"upgrade" in connection: + return upgrade + return None # pragma: full coverage + + def _should_upgrade_to_ws(self) -> bool: + if self.ws_protocol_class is None: + return False + return True + + def _unsupported_upgrade_warning(self) -> None: + self.logger.warning("Unsupported upgrade request.") + if not self._should_upgrade_to_ws(): + msg = "No supported WebSocket library detected. Please use \"pip install 'uvicorn[standard]'\", or install 'websockets' or 'wsproto' manually." # noqa: E501 + self.logger.warning(msg) + + def _should_upgrade(self) -> bool: + upgrade = self._get_upgrade() + return upgrade == b"websocket" and self._should_upgrade_to_ws() + + def data_received(self, data: bytes) -> None: + self._unset_keepalive_if_required() + + try: + self.parser.feed_data(data) + except httptools.HttpParserError: + msg = "Invalid HTTP request received." + self.logger.warning(msg) + self.send_400_response(msg) + return + except httptools.HttpParserUpgrade: + if self._should_upgrade(): + self.handle_websocket_upgrade() + else: + self._unsupported_upgrade_warning() + + def handle_websocket_upgrade(self) -> None: + if self.logger.level <= TRACE_LOG_LEVEL: + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sUpgrading to WebSocket", prefix) + + self.connections.discard(self) + method = self.scope["method"].encode() + output = [method, b" ", self.url, b" HTTP/1.1\r\n"] + for name, value in self.scope["headers"]: + output += [name, b": ", value, b"\r\n"] + output.append(b"\r\n") + protocol = self.ws_protocol_class( # type: ignore[call-arg, misc] + config=self.config, + server_state=self.server_state, + app_state=self.app_state, + ) + protocol.connection_made(self.transport) + protocol.data_received(b"".join(output)) + self.transport.set_protocol(protocol) + + def send_400_response(self, msg: str) -> None: + content = [STATUS_LINE[400]] + for name, value in self.server_state.default_headers: + content.extend([name, b": ", value, b"\r\n"]) # pragma: full coverage + content.extend( + [ + b"content-type: text/plain; charset=utf-8\r\n", + b"content-length: " + str(len(msg)).encode("ascii") + b"\r\n", + b"connection: close\r\n", + b"\r\n", + msg.encode("ascii"), + ] + ) + self.transport.write(b"".join(content)) + self.transport.close() + + def on_message_begin(self) -> None: + self.url = b"" + self.expect_100_continue = False + self.headers = [] + self.scope = { # type: ignore[typeddict-item] + "type": "http", + "asgi": {"version": self.config.asgi_version, "spec_version": "2.3"}, + "http_version": "1.1", + "server": self.server, + "client": self.client, + "scheme": self.scheme, # type: ignore[typeddict-item] + "root_path": self.root_path, + "headers": self.headers, + "state": self.app_state.copy(), + } + + # Parser callbacks + def on_url(self, url: bytes) -> None: + self.url += url + + def on_header(self, name: bytes, value: bytes) -> None: + name = name.lower() + if name == b"expect" and value.lower() == b"100-continue": + self.expect_100_continue = True + self.headers.append((name, value)) + + def on_headers_complete(self) -> None: + http_version = self.parser.get_http_version() + method = self.parser.get_method() + self.scope["method"] = method.decode("ascii") + if http_version != "1.1": + self.scope["http_version"] = http_version + if self.parser.should_upgrade() and self._should_upgrade(): + return + parsed_url = httptools.parse_url(self.url) + raw_path = parsed_url.path + path = raw_path.decode("ascii") + if "%" in path: + path = urllib.parse.unquote(path) + full_path = self.root_path + path + full_raw_path = self.root_path.encode("ascii") + raw_path + self.scope["path"] = full_path + self.scope["raw_path"] = full_raw_path + self.scope["query_string"] = parsed_url.query or b"" + + # Handle 503 responses when 'limit_concurrency' is exceeded. + if self.limit_concurrency is not None and ( + len(self.connections) >= self.limit_concurrency or len(self.tasks) >= self.limit_concurrency + ): + app = service_unavailable + message = "Exceeded concurrency limit." + self.logger.warning(message) + else: + app = self.app + + existing_cycle = self.cycle + self.cycle = RequestResponseCycle( + scope=self.scope, + transport=self.transport, + flow=self.flow, + logger=self.logger, + access_logger=self.access_logger, + access_log=self.access_log, + default_headers=self.server_state.default_headers, + message_event=asyncio.Event(), + expect_100_continue=self.expect_100_continue, + keep_alive=http_version != "1.0", + on_response=self.on_response_complete, + ) + if existing_cycle is None or existing_cycle.response_complete: + # Standard case - start processing the request. + self._start_asgi_task(self.cycle, app) + else: + # Pipelined HTTP requests need to be queued up. + self.flow.pause_reading() + self.pipeline.appendleft((self.cycle, app)) + + def _start_asgi_task(self, cycle: RequestResponseCycle, app: ASGI3Application) -> None: + if self.config.reset_contextvars: + # Opt-in workaround for https://github.com/python/cpython/issues/140947: + # asyncio can leak context vars between tasks. Hides context set in the + # lifespan or by external instrumentation. + if sys.version_info >= (3, 11): # pragma: py-lt-311 + task = self.loop.create_task(cycle.run_asgi(app), context=contextvars.Context()) + else: # pragma: py-gte-311 + task = contextvars.Context().run(self.loop.create_task, cycle.run_asgi(app)) + else: + task = self.loop.create_task(cycle.run_asgi(app)) + task.add_done_callback(self.tasks.discard) + self.tasks.add(task) + + def on_body(self, body: bytes) -> None: + if (self.parser.should_upgrade() and self._should_upgrade()) or self.cycle.response_complete: + return + self.cycle.body += body + if len(self.cycle.body) > HIGH_WATER_LIMIT: + self.flow.pause_reading() + self.cycle.message_event.set() + + def on_message_complete(self) -> None: + if (self.parser.should_upgrade() and self._should_upgrade()) or self.cycle.response_complete: + return + self.cycle.more_body = False + self.cycle.message_event.set() + + def on_response_complete(self) -> None: + # Callback for pipelined HTTP requests to be started. + self.server_state.total_requests += 1 + + if self.transport.is_closing(): + return + + self._unset_keepalive_if_required() + + # Unpause data reads if needed. + self.flow.resume_reading() + + # Unblock any pipelined events. If there are none, arm the + # Keep-Alive timeout instead. + if self.pipeline: + cycle, app = self.pipeline.pop() + self._start_asgi_task(cycle, app) + else: + self.timeout_keep_alive_task = self.loop.call_later( + self.timeout_keep_alive, self.timeout_keep_alive_handler + ) + + def shutdown(self) -> None: + """ + Called by the server to commence a graceful shutdown. + """ + if self.cycle is None or self.cycle.response_complete: + self.transport.close() + else: + self.cycle.keep_alive = False + + def pause_writing(self) -> None: + """ + Called by the transport when the write buffer exceeds the high water mark. + """ + self.flow.pause_writing() # pragma: full coverage + + def resume_writing(self) -> None: + """ + Called by the transport when the write buffer drops below the low water mark. + """ + self.flow.resume_writing() # pragma: full coverage + + def timeout_keep_alive_handler(self) -> None: + """ + Called on a keep-alive connection if no new data is received after a short + delay. + """ + if not self.transport.is_closing(): + self.transport.close() + + +class RequestResponseCycle: + def __init__( + self, + scope: HTTPScope, + transport: asyncio.Transport, + flow: FlowControl, + logger: logging.Logger, + access_logger: logging.Logger, + access_log: bool, + default_headers: list[tuple[bytes, bytes]], + message_event: asyncio.Event, + expect_100_continue: bool, + keep_alive: bool, + on_response: Callable[..., None], + ): + self.scope = scope + self.transport = transport + self.flow = flow + self.logger = logger + self.access_logger = access_logger + self.access_log = access_log + self.default_headers = default_headers + self.message_event = message_event + self.on_response = on_response + + # Connection state + self.disconnected = False + self.keep_alive = keep_alive + self.waiting_for_100_continue = expect_100_continue + + # Request state + self.body = bytearray() + self.more_body = True + + # Response state + self.response_started = False + self.response_complete = False + self.chunked_encoding: bool | None = None + self.expected_content_length = 0 + + # ASGI exception wrapper + async def run_asgi(self, app: ASGI3Application) -> None: + try: + result = await app( # type: ignore[func-returns-value] + self.scope, self.receive, self.send + ) + except BaseException as exc: + msg = "Exception in ASGI application\n" + self.logger.error(msg, exc_info=exc) + if not self.response_started: + await self.send_500_response() + else: + self.transport.close() + else: + if result is not None: + msg = "ASGI callable should return None, but returned '%s'." + self.logger.error(msg, result) + self.transport.close() + elif not self.response_started and not self.disconnected: + msg = "ASGI callable returned without starting response." + self.logger.error(msg) + await self.send_500_response() + elif not self.response_complete and not self.disconnected: + msg = "ASGI callable returned without completing response." + self.logger.error(msg) + self.transport.close() + finally: + self.on_response = lambda: None + + async def send_500_response(self) -> None: + await self.send( + { + "type": "http.response.start", + "status": 500, + "headers": [ + (b"content-type", b"text/plain; charset=utf-8"), + (b"content-length", b"21"), + (b"connection", b"close"), + ], + } + ) + await self.send({"type": "http.response.body", "body": b"Internal Server Error", "more_body": False}) + + # ASGI interface + async def send(self, message: ASGISendEvent) -> None: + if self.flow.write_paused and not self.disconnected: + await self.flow.drain() # pragma: full coverage + + if self.disconnected: + return # pragma: full coverage + + if not self.response_started: + # Sending response status line and headers + if message["type"] != "http.response.start": + raise RuntimeError(f"Expected ASGI message 'http.response.start', but got '{message['type']}'.") + + self.response_started = True + self.waiting_for_100_continue = False + + status_code = message["status"] + headers = self.default_headers + list(message.get("headers", [])) + + if CLOSE_HEADER in self.scope["headers"] and CLOSE_HEADER not in headers: + headers = headers + [CLOSE_HEADER] + + if self.access_log: + self.access_logger.info( + '%s - "%s %s HTTP/%s" %d', + get_client_addr(self.scope), + self.scope["method"], + get_path_with_query_string(self.scope), + self.scope["http_version"], + status_code, + ) + + # Write response status line and headers + content = [STATUS_LINE[status_code]] + + for name, value in headers: + if HEADER_RE.search(name): + raise RuntimeError("Invalid HTTP header name.") # pragma: full coverage + if HEADER_VALUE_RE.search(value): + raise RuntimeError("Invalid HTTP header value.") + + name = name.lower() + if name == b"content-length" and self.chunked_encoding is None: + self.expected_content_length = int(value.decode()) + self.chunked_encoding = False + elif name == b"transfer-encoding" and value.lower() == b"chunked": + self.expected_content_length = 0 + self.chunked_encoding = True + elif name == b"connection" and value.lower() == b"close": + self.keep_alive = False + content.extend([name, b": ", value, b"\r\n"]) + + if self.chunked_encoding is None and self.scope["method"] != "HEAD" and status_code not in (204, 304): + # Neither content-length nor transfer-encoding specified + self.chunked_encoding = True + content.append(b"transfer-encoding: chunked\r\n") + + content.append(b"\r\n") + self.transport.write(b"".join(content)) + + elif not self.response_complete: + # Sending response body + if message["type"] != "http.response.body": + raise RuntimeError(f"Expected ASGI message 'http.response.body', but got '{message['type']}'.") + + body = message.get("body", b"") + more_body = message.get("more_body", False) + + # Write response body + if self.scope["method"] == "HEAD": + self.expected_content_length = 0 + elif self.chunked_encoding: + if body: + content = [b"%x\r\n" % len(body), body, b"\r\n"] + else: + content = [] + if not more_body: + content.append(b"0\r\n\r\n") + self.transport.write(b"".join(content)) + else: + num_bytes = len(body) + if num_bytes > self.expected_content_length: + raise RuntimeError("Response content longer than Content-Length") + else: + self.expected_content_length -= num_bytes + self.transport.write(body) + + # Handle response completion + if not more_body: + if self.expected_content_length != 0: + raise RuntimeError("Response content shorter than Content-Length") + self.response_complete = True + self.message_event.set() + if not self.keep_alive: + self.transport.close() + self.on_response() + + else: + # Response already sent + raise RuntimeError(f"Unexpected ASGI message '{message['type']}' sent, after response already completed.") + + async def receive(self) -> ASGIReceiveEvent: + if self.waiting_for_100_continue and not self.transport.is_closing(): + self.transport.write(b"HTTP/1.1 100 Continue\r\n\r\n") + self.waiting_for_100_continue = False + + if not self.disconnected and not self.response_complete: + self.flow.resume_reading() + await self.message_event.wait() + self.message_event.clear() + + if self.disconnected or self.response_complete: + return {"type": "http.disconnect"} + message: HTTPRequestEvent = {"type": "http.request", "body": bytes(self.body), "more_body": self.more_body} + self.body = bytearray() + return message diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a9a89065c70d7a7905d4b44bc3c385a492cc0d70 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/utils.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +import asyncio +import socket +import urllib.parse + +from uvicorn._types import WWWScope + + +class ClientDisconnected(OSError): ... + + +def get_remote_addr(transport: asyncio.Transport) -> tuple[str, int] | None: + socket_info: socket.socket | None = transport.get_extra_info("socket") + if socket_info is not None: + try: + info = socket_info.getpeername() + return (str(info[0]), int(info[1])) if isinstance(info, tuple) else None + except OSError: # pragma: no cover + # This case appears to inconsistently occur with uvloop + # bound to a unix domain socket. + return None + + info = transport.get_extra_info("peername") + if info is not None and isinstance(info, list | tuple) and len(info) == 2: + return (str(info[0]), int(info[1])) + return None + + +def get_local_addr(transport: asyncio.Transport) -> tuple[str, int | None] | None: + socket_info: socket.socket | None = transport.get_extra_info("socket") + if socket_info is not None: + info = socket_info.getsockname() + if isinstance(info, tuple): + return (str(info[0]), int(info[1])) + if isinstance(info, str): + return (info, None) + return None + info = transport.get_extra_info("sockname") + if info is not None and isinstance(info, list | tuple) and len(info) == 2: + return (str(info[0]), int(info[1])) + if isinstance(info, str): + return (info, None) + return None + + +def is_ssl(transport: asyncio.Transport) -> bool: + return bool(transport.get_extra_info("sslcontext")) + + +def get_client_addr(scope: WWWScope) -> str: + client = scope.get("client") + if not client: + return "" + return "%s:%d" % client + + +def get_path_with_query_string(scope: WWWScope) -> str: + path_with_query_string = urllib.parse.quote(scope["path"]) + if scope["query_string"]: + path_with_query_string = "{}?{}".format(path_with_query_string, scope["query_string"].decode("ascii")) + return path_with_query_string diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a3c007f15fc791ee5c414c2c4243f8720cefde3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/auto.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/auto.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9328d72da3fb9aadc484bc6a6829d592b67c8849 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/auto.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/websockets_impl.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/websockets_impl.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b9010a07fc269dda3463783a4ec59affc27381b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/websockets_impl.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/websockets_sansio_impl.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/websockets_sansio_impl.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..014c0033fc5b1f22c3e90d8cf8ccb68251abfa52 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/websockets_sansio_impl.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/wsproto_impl.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/wsproto_impl.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c021aa2832595a2f3a8704c9c86430fbf033c794 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/__pycache__/wsproto_impl.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/auto.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/auto.py new file mode 100644 index 0000000000000000000000000000000000000000..7180ad39788c6fb14e15ae3fda379aba01c332f8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/auto.py @@ -0,0 +1,21 @@ +from __future__ import annotations + +import asyncio +from collections.abc import Callable + +AutoWebSocketsProtocol: Callable[..., asyncio.Protocol] | None +try: + import websockets # noqa +except ImportError: # pragma: no cover + try: + import wsproto # noqa + except ImportError: + AutoWebSocketsProtocol = None + else: + from uvicorn.protocols.websockets.wsproto_impl import WSProtocol + + AutoWebSocketsProtocol = WSProtocol +else: + from uvicorn.protocols.websockets.websockets_impl import WebSocketProtocol + + AutoWebSocketsProtocol = WebSocketProtocol diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/websockets_impl.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/websockets_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..e4139391a2d199e2f2d1f67c232693774875f57a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/websockets_impl.py @@ -0,0 +1,372 @@ +from __future__ import annotations + +import asyncio +import http +import logging +from collections.abc import Sequence +from typing import Any, Literal, cast +from urllib.parse import unquote + +import websockets +import websockets.legacy.handshake +from websockets.datastructures import Headers +from websockets.exceptions import ConnectionClosed +from websockets.extensions.base import ServerExtensionFactory +from websockets.extensions.permessage_deflate import ServerPerMessageDeflateFactory +from websockets.legacy.server import HTTPResponse +from websockets.server import WebSocketServerProtocol +from websockets.typing import Subprotocol + +from uvicorn._types import ( + ASGI3Application, + ASGISendEvent, + WebSocketConnectEvent, + WebSocketDisconnectEvent, + WebSocketReceiveEvent, + WebSocketScope, +) +from uvicorn.config import Config +from uvicorn.logging import TRACE_LOG_LEVEL +from uvicorn.protocols.utils import ( + ClientDisconnected, + get_client_addr, + get_local_addr, + get_path_with_query_string, + get_remote_addr, + is_ssl, +) +from uvicorn.server import ServerState + + +class Server: + closing = False + + def register(self, ws: WebSocketServerProtocol) -> None: + pass + + def unregister(self, ws: WebSocketServerProtocol) -> None: + pass + + def is_serving(self) -> bool: + return not self.closing + + +class WebSocketProtocol(WebSocketServerProtocol): + extra_headers: list[tuple[str, str]] + logger: logging.Logger | logging.LoggerAdapter[Any] + + def __init__( + self, + config: Config, + server_state: ServerState, + app_state: dict[str, Any], + _loop: asyncio.AbstractEventLoop | None = None, + ): + if not config.loaded: + config.load() + + self.config = config + self.app = cast(ASGI3Application, config.loaded_app) + self.loop = _loop or asyncio.get_event_loop() + self.root_path = config.root_path + self.app_state = app_state + + # Shared server state + self.connections = server_state.connections + self.tasks = server_state.tasks + + # Connection state + self.transport: asyncio.Transport = None # type: ignore[assignment] + self.server: tuple[str, int | None] | None = None + self.client: tuple[str, int] | None = None + self.scheme: Literal["wss", "ws"] = None # type: ignore[assignment] + + # Connection events + self.scope: WebSocketScope + self.handshake_started_event = asyncio.Event() + self.handshake_completed_event = asyncio.Event() + self.closed_event = asyncio.Event() + self.initial_response: HTTPResponse | None = None + self.connect_sent = False + self.lost_connection_before_handshake = False + self.accepted_subprotocol: Subprotocol | None = None + + self.ws_server: Server = Server() # type: ignore[assignment] + + extensions: list[ServerExtensionFactory] = [] + if self.config.ws_per_message_deflate: + extensions.append(ServerPerMessageDeflateFactory()) + + super().__init__( + ws_handler=self.ws_handler, + ws_server=self.ws_server, # type: ignore[arg-type] + max_size=self.config.ws_max_size, + max_queue=self.config.ws_max_queue, + ping_interval=self.config.ws_ping_interval, + ping_timeout=self.config.ws_ping_timeout, + extensions=extensions, + logger=logging.getLogger("uvicorn.error"), + ) + self.server_header = None + self.extra_headers = [ + (name.decode("latin-1"), value.decode("latin-1")) for name, value in server_state.default_headers + ] + + def connection_made( # type: ignore[override] + self, transport: asyncio.Transport + ) -> None: + self.connections.add(self) + self.transport = transport + self.server = get_local_addr(transport) + self.client = get_remote_addr(transport) + self.scheme = "wss" if is_ssl(transport) else "ws" + + if self.logger.isEnabledFor(TRACE_LOG_LEVEL): + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sWebSocket connection made", prefix) + + super().connection_made(transport) + + def connection_lost(self, exc: Exception | None) -> None: + self.connections.remove(self) + + if self.logger.isEnabledFor(TRACE_LOG_LEVEL): + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sWebSocket connection lost", prefix) + + self.lost_connection_before_handshake = not self.handshake_completed_event.is_set() + self.handshake_completed_event.set() + super().connection_lost(exc) + if exc is None: + self.transport.close() + + def shutdown(self) -> None: + self.ws_server.closing = True + if self.handshake_completed_event.is_set(): + self.fail_connection(1012) + else: + self.send_500_response() + self.transport.close() + + def on_task_complete(self, task: asyncio.Task[None]) -> None: + self.tasks.discard(task) + + async def process_request(self, path: str, request_headers: Headers) -> HTTPResponse | None: + """ + This hook is called to determine if the websocket should return + an HTTP response and close. + + Our behavior here is to start the ASGI application, and then wait + for either `accept` or `close` in order to determine if we should + close the connection. + """ + path_portion, _, query_string = path.partition("?") + + websockets.legacy.handshake.check_request(request_headers) + + subprotocols: list[str] = [] + for header in request_headers.get_all("Sec-WebSocket-Protocol"): + subprotocols.extend([token.strip() for token in header.split(",")]) + + asgi_headers = [ + (name.encode("ascii"), value.encode("ascii", errors="surrogateescape")) + for name, value in request_headers.raw_items() + ] + path = unquote(path_portion) + full_path = self.root_path + path + full_raw_path = self.root_path.encode("ascii") + path_portion.encode("ascii") + + self.scope = { + "type": "websocket", + "asgi": {"version": self.config.asgi_version, "spec_version": "2.4"}, + "http_version": "1.1", + "scheme": self.scheme, + "server": self.server, + "client": self.client, + "root_path": self.root_path, + "path": full_path, + "raw_path": full_raw_path, + "query_string": query_string.encode("ascii"), + "headers": asgi_headers, + "subprotocols": subprotocols, + "state": self.app_state.copy(), + "extensions": {"websocket.http.response": {}}, + } + task = self.loop.create_task(self.run_asgi()) + task.add_done_callback(self.on_task_complete) + self.tasks.add(task) + await self.handshake_started_event.wait() + return self.initial_response + + def process_subprotocol( + self, headers: Headers, available_subprotocols: Sequence[Subprotocol] | None + ) -> Subprotocol | None: + """ + We override the standard 'process_subprotocol' behavior here so that + we return whatever subprotocol is sent in the 'accept' message. + """ + return self.accepted_subprotocol + + def send_500_response(self) -> None: + msg = b"Internal Server Error" + content = [ + b"HTTP/1.1 500 Internal Server Error\r\ncontent-type: text/plain; charset=utf-8\r\n", + b"content-length: " + str(len(msg)).encode("ascii") + b"\r\n", + b"connection: close\r\n", + b"\r\n", + msg, + ] + self.transport.write(b"".join(content)) + # Allow handler task to terminate cleanly, as websockets doesn't cancel it by + # itself (see https://github.com/Kludex/uvicorn/issues/920) + self.handshake_started_event.set() + + async def ws_handler(self, protocol: WebSocketServerProtocol, path: str) -> Any: # type: ignore[override] + """ + This is the main handler function for the 'websockets' implementation + to call into. We just wait for close then return, and instead allow + 'send' and 'receive' events to drive the flow. + """ + self.handshake_completed_event.set() + await self.wait_closed() + + async def run_asgi(self) -> None: + """ + Wrapper around the ASGI callable, handling exceptions and unexpected + termination states. + """ + try: + result = await self.app(self.scope, self.asgi_receive, self.asgi_send) # type: ignore[func-returns-value] + except ClientDisconnected: # pragma: full coverage + self.closed_event.set() + except BaseException: + self.closed_event.set() + self.logger.exception("Exception in ASGI application\n") + if not self.handshake_started_event.is_set(): + self.send_500_response() + else: + await self.handshake_completed_event.wait() + else: + self.closed_event.set() + if not self.handshake_started_event.is_set(): + self.logger.error("ASGI callable returned without sending handshake.") + self.send_500_response() + elif result is not None: + self.logger.error("ASGI callable should return None, but returned '%s'.", result) + await self.handshake_completed_event.wait() + self.transport.close() + + async def asgi_send(self, message: ASGISendEvent) -> None: + if not self.handshake_started_event.is_set(): + if message["type"] == "websocket.accept": + self.logger.info( + '%s - "WebSocket %s" [accepted]', + get_client_addr(self.scope), + get_path_with_query_string(self.scope), + ) + self.initial_response = None + self.accepted_subprotocol = cast(Subprotocol | None, message.get("subprotocol")) + if "headers" in message: + self.extra_headers.extend( + # ASGI spec requires bytes + # But for compatibility we need to convert it to strings + (name.decode("latin-1"), value.decode("latin-1")) + for name, value in message["headers"] + ) + self.handshake_started_event.set() + + elif message["type"] == "websocket.close": + self.logger.info( + '%s - "WebSocket %s" 403', + get_client_addr(self.scope), + get_path_with_query_string(self.scope), + ) + self.initial_response = (http.HTTPStatus.FORBIDDEN, [], b"") + self.handshake_started_event.set() + self.closed_event.set() + + elif message["type"] == "websocket.http.response.start": + self.logger.info( + '%s - "WebSocket %s" %d', + get_client_addr(self.scope), + get_path_with_query_string(self.scope), + message["status"], + ) + # websockets requires the status to be an enum. look it up. + status = http.HTTPStatus(message["status"]) + headers = [ + (name.decode("latin-1"), value.decode("latin-1")) for name, value in message.get("headers", []) + ] + self.initial_response = (status, headers, b"") + self.handshake_started_event.set() + + else: + raise RuntimeError( + "Expected ASGI message 'websocket.accept', 'websocket.close', " + f"or 'websocket.http.response.start' but got '{message['type']}'." + ) + + elif not self.closed_event.is_set() and self.initial_response is None: + await self.handshake_completed_event.wait() + + try: + if message["type"] == "websocket.send": + bytes_data = message.get("bytes") + text_data = message.get("text") + data = text_data if bytes_data is None else bytes_data + await self.send(data) # type: ignore[arg-type] + + elif message["type"] == "websocket.close": + code = message.get("code", 1000) + reason = message.get("reason", "") or "" + await self.close(code, reason) + self.closed_event.set() + + else: + raise RuntimeError( + f"Expected ASGI message 'websocket.send' or 'websocket.close', but got '{message['type']}'." + ) + except ConnectionClosed as exc: + raise ClientDisconnected from exc + + elif self.initial_response is not None: + if message["type"] == "websocket.http.response.body": + body = self.initial_response[2] + message["body"] + self.initial_response = self.initial_response[:2] + (body,) + if not message.get("more_body", False): + self.closed_event.set() + else: + raise RuntimeError(f"Expected ASGI message 'websocket.http.response.body' but got '{message['type']}'.") + + else: + raise RuntimeError( + f"Unexpected ASGI message '{message['type']}', after sending 'websocket.close' " + "or response already completed." + ) + + async def asgi_receive(self) -> WebSocketDisconnectEvent | WebSocketConnectEvent | WebSocketReceiveEvent: + if not self.connect_sent: + self.connect_sent = True + return {"type": "websocket.connect"} + + await self.handshake_completed_event.wait() + + if self.lost_connection_before_handshake: + # If the handshake failed or the app closed before handshake completion, + # use 1006 Abnormal Closure. + return {"type": "websocket.disconnect", "code": 1006} + + if self.closed_event.is_set(): + return {"type": "websocket.disconnect", "code": 1005} + + try: + data = await self.recv() + except ConnectionClosed: + self.closed_event.set() + if self.ws_server.closing: + return {"type": "websocket.disconnect", "code": 1012} + return {"type": "websocket.disconnect", "code": self.close_code or 1005, "reason": self.close_reason} + + if isinstance(data, str): + return {"type": "websocket.receive", "text": data} + return {"type": "websocket.receive", "bytes": data} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/websockets_sansio_impl.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/websockets_sansio_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..036b6ee01e801a04c83b57d9577e72ec6905922e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/websockets_sansio_impl.py @@ -0,0 +1,477 @@ +from __future__ import annotations + +import asyncio +import logging +import random +import struct +import sys +from asyncio import TimerHandle +from asyncio.transports import BaseTransport, Transport +from http import HTTPStatus +from typing import Any, Literal, cast +from urllib.parse import unquote + +from websockets.exceptions import InvalidState +from websockets.extensions.permessage_deflate import ServerPerMessageDeflateFactory +from websockets.frames import Frame, Opcode +from websockets.http11 import Request +from websockets.server import ServerProtocol + +from uvicorn._types import ( + ASGIReceiveEvent, + ASGISendEvent, + WebSocketScope, +) +from uvicorn.config import Config +from uvicorn.logging import TRACE_LOG_LEVEL +from uvicorn.protocols.utils import ( + ClientDisconnected, + get_client_addr, + get_local_addr, + get_path_with_query_string, + get_remote_addr, + is_ssl, +) +from uvicorn.server import ServerState + +if sys.version_info >= (3, 11): # pragma: no cover + from typing import assert_never +else: # pragma: no cover + from typing_extensions import assert_never + + +class WebSocketsSansIOProtocol(asyncio.Protocol): + def __init__( + self, + config: Config, + server_state: ServerState, + app_state: dict[str, Any], + _loop: asyncio.AbstractEventLoop | None = None, + ) -> None: + if not config.loaded: + config.load() # pragma: no cover + + self.config = config + self.app = config.loaded_app + self.loop = _loop or asyncio.get_event_loop() + self.logger = logging.getLogger("uvicorn.error") + self.root_path = config.root_path + self.app_state = app_state + + # Shared server state + self.connections = server_state.connections + self.tasks = server_state.tasks + self.default_headers = server_state.default_headers + + # Connection state + self.transport: asyncio.Transport = None # type: ignore[assignment] + self.server: tuple[str, int | None] | None = None + self.client: tuple[str, int] | None = None + self.scheme: Literal["wss", "ws"] = None # type: ignore[assignment] + + # WebSocket state + self.queue: asyncio.Queue[ASGIReceiveEvent] = asyncio.Queue() + self.handshake_initiated = False + self.handshake_complete = False + self.close_sent = False + self.initial_response: tuple[int, list[tuple[str, str]], bytes] | None = None + + extensions = [] + if self.config.ws_per_message_deflate: + extensions = [ + ServerPerMessageDeflateFactory( + server_max_window_bits=12, + client_max_window_bits=12, + compress_settings={"memLevel": 5}, + ) + ] + self.conn = ServerProtocol( + extensions=extensions, + max_size=self.config.ws_max_size, + logger=logging.getLogger("uvicorn.error"), + ) + + self.read_paused = False + self.writable = asyncio.Event() + self.writable.set() + + # Keepalive state + self.ping_interval = config.ws_ping_interval + self.ping_timeout = config.ws_ping_timeout + self.ping_timer: TimerHandle | None = None + self.pong_timer: TimerHandle | None = None + self.pending_ping_payload: bytes | None = None + self.ping_sent_at: float = 0.0 + self.last_ping_rtt: float = 0.0 + + # Buffers + self.bytes = bytearray() + + def connection_made(self, transport: BaseTransport) -> None: + """Called when a connection is made.""" + transport = cast(Transport, transport) + self.connections.add(self) + self.transport = transport + self.server = get_local_addr(transport) + self.client = get_remote_addr(transport) + self.scheme = "wss" if is_ssl(transport) else "ws" + + if self.logger.level <= TRACE_LOG_LEVEL: + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sWebSocket connection made", prefix) + + def connection_lost(self, exc: Exception | None) -> None: + self.stop_keepalive() + code = 1005 if self.handshake_complete else 1006 + self.queue.put_nowait({"type": "websocket.disconnect", "code": code}) + self.connections.remove(self) + + if self.logger.level <= TRACE_LOG_LEVEL: + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sWebSocket connection lost", prefix) + + self.handshake_complete = True + if exc is None: + self.transport.close() + + def eof_received(self) -> None: + pass + + def shutdown(self) -> None: + self.stop_keepalive() + if self.handshake_complete: + self.queue.put_nowait({"type": "websocket.disconnect", "code": 1012}) + self.conn.send_close(1012) + output = self.conn.data_to_send() + self.transport.write(b"".join(output)) + else: + self.send_500_response() + self.transport.close() + + def data_received(self, data: bytes) -> None: + self.conn.receive_data(data) + if self.conn.parser_exc is not None: # pragma: no cover + self.handle_parser_exception() + return + self.handle_events() + + def handle_events(self) -> None: + for event in self.conn.events_received(): + if isinstance(event, Request): + self.handle_connect(event) + if isinstance(event, Frame): + if event.opcode == Opcode.CONT: + self.handle_cont(event) # pragma: no cover + elif event.opcode == Opcode.TEXT: + self.handle_text(event) + elif event.opcode == Opcode.BINARY: + self.handle_bytes(event) + elif event.opcode == Opcode.PING: + self.handle_ping() + elif event.opcode == Opcode.PONG: + self.handle_pong(event) + elif event.opcode == Opcode.CLOSE: + self.handle_close(event) + else: + assert_never(event.opcode) # pragma: no cover + + # Event handlers + + def handle_connect(self, event: Request) -> None: + self.request = event + self.response = self.conn.accept(event) + self.handshake_initiated = True + if self.response.status_code != 101: + self.handshake_complete = True + self.close_sent = True + self.conn.send_response(self.response) + output = self.conn.data_to_send() + self.transport.write(b"".join(output)) + self.transport.close() + return + + headers = [ + (key.encode("ascii"), value.encode("ascii", errors="surrogateescape")) + for key, value in event.headers.raw_items() + ] + raw_path, _, query_string = event.path.partition("?") + self.scope: WebSocketScope = { + "type": "websocket", + "asgi": {"version": self.config.asgi_version, "spec_version": "2.4"}, + "http_version": "1.1", + "scheme": self.scheme, + "server": self.server, + "client": self.client, + "root_path": self.root_path, + "path": self.root_path + unquote(raw_path), + "raw_path": self.root_path.encode("ascii") + raw_path.encode("ascii"), + "query_string": query_string.encode("ascii"), + "headers": headers, + "subprotocols": event.headers.get_all("Sec-WebSocket-Protocol"), + "state": self.app_state.copy(), + "extensions": {"websocket.http.response": {}}, + } + self.queue.put_nowait({"type": "websocket.connect"}) + task = self.loop.create_task(self.run_asgi()) + task.add_done_callback(self.on_task_complete) + self.tasks.add(task) + + def handle_cont(self, event: Frame) -> None: + self.bytes.extend(event.data) + if event.fin: + self.send_receive_event_to_app() + + def handle_text(self, event: Frame) -> None: + self.bytes = bytearray(event.data) + self.curr_msg_data_type: Literal["text", "bytes"] = "text" + if event.fin: + self.send_receive_event_to_app() + + def handle_bytes(self, event: Frame) -> None: + self.bytes = bytearray(event.data) + self.curr_msg_data_type = "bytes" + if event.fin: + self.send_receive_event_to_app() + + def send_receive_event_to_app(self) -> None: + if self.curr_msg_data_type == "text": + try: + self.queue.put_nowait({"type": "websocket.receive", "text": self.bytes.decode()}) + except UnicodeDecodeError: # pragma: no cover + self.logger.exception("Invalid UTF-8 sequence received from client.") + self.conn.send_close(1007) + self.handle_parser_exception() + return + else: + self.queue.put_nowait({"type": "websocket.receive", "bytes": bytes(self.bytes)}) + if not self.read_paused: + self.read_paused = True + self.transport.pause_reading() + + def handle_ping(self) -> None: + output = self.conn.data_to_send() + self.transport.write(b"".join(output)) + + def handle_pong(self, event: Frame) -> None: + # Ignore unsolicited pongs and stale pongs whose payload doesn't match the ping currently in flight + if self.pending_ping_payload is None or bytes(event.data) != self.pending_ping_payload: + return # pragma: no cover + + self.last_ping_rtt = self.loop.time() - self.ping_sent_at + self.pending_ping_payload = None + # The peer answered in time; cancel the pong deadline and chain the next ping. This `schedule_ping()` call is + # what keeps the keepalive loop running when ping_timeout is set. When ping_timeout is None the next ping is + # already scheduled by `send_keepalive_ping`, so we must not schedule a duplicate here. + if self.pong_timer is not None: + self.pong_timer.cancel() + self.pong_timer = None + self.schedule_ping() + + def start_keepalive(self) -> None: + if self.ping_interval is not None and self.ping_interval > 0: + self.schedule_ping() + + def stop_keepalive(self) -> None: + if self.ping_timer is not None: + self.ping_timer.cancel() + self.ping_timer = None + if self.pong_timer is not None: # pragma: no cover + self.pong_timer.cancel() + self.pong_timer = None + self.pending_ping_payload = None + + def schedule_ping(self) -> None: + assert self.ping_interval is not None + delay = max(0.0, self.ping_interval - self.last_ping_rtt) + self.ping_timer = self.loop.call_later(delay, self.send_keepalive_ping) + + def send_keepalive_ping(self) -> None: + self.ping_timer = None + if self.close_sent or self.transport.is_closing(): # pragma: no cover + return + # Random 4-byte payload identifies this ping; `handle_pong` uses it to ignore stale or unsolicited pongs. + # See https://github.com/python-websockets/websockets/blob/4d229bf9f583d593aa103287aee0a77c9fbc3a79/src/websockets/asyncio/connection.py#L624 + self.pending_ping_payload = struct.pack("!I", random.getrandbits(32)) + self.ping_sent_at = self.loop.time() + self.conn.send_ping(self.pending_ping_payload) + self.transport.write(b"".join(self.conn.data_to_send())) + if self.ping_timeout is not None: + self.pong_timer = self.loop.call_later(self.ping_timeout, self.keepalive_timeout) + else: # pragma: no cover + self.schedule_ping() + + def keepalive_timeout(self) -> None: + self.pong_timer = None + self.pending_ping_payload = None + if self.close_sent or self.transport.is_closing(): # pragma: no cover + return + if self.logger.level <= TRACE_LOG_LEVEL: + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sWebSocket keepalive ping timeout", prefix) + self.conn.fail(1011, "keepalive ping timeout") + self.transport.write(b"".join(self.conn.data_to_send())) + self.close_sent = True + self.transport.close() + + def handle_close(self, event: Frame) -> None: + if not self.close_sent and not self.transport.is_closing(): + assert self.conn.close_rcvd is not None + code = self.conn.close_rcvd.code + reason = self.conn.close_rcvd.reason + self.queue.put_nowait({"type": "websocket.disconnect", "code": code, "reason": reason}) + + output = self.conn.data_to_send() + self.transport.write(b"".join(output)) + self.transport.close() + + def handle_parser_exception(self) -> None: # pragma: no cover + assert self.conn.close_sent is not None + code = self.conn.close_sent.code + reason = self.conn.close_sent.reason + self.queue.put_nowait({"type": "websocket.disconnect", "code": code, "reason": reason}) + + output = self.conn.data_to_send() + self.transport.write(b"".join(output)) + self.close_sent = True + self.transport.close() + + def on_task_complete(self, task: asyncio.Task[None]) -> None: + self.tasks.discard(task) + + async def run_asgi(self) -> None: + try: + result = await self.app(self.scope, self.receive, self.send) + except ClientDisconnected: + pass # pragma: full coverage + except BaseException: + self.logger.exception("Exception in ASGI application\n") + self.send_500_response() + else: + if not self.handshake_complete: + self.logger.error("ASGI callable returned without completing handshake.") + self.send_500_response() + elif result is not None: + self.logger.error("ASGI callable should return None, but returned '%s'.", result) + self.transport.close() + + def send_500_response(self) -> None: + if self.initial_response or self.handshake_complete: + return + response = self.conn.reject(500, "Internal Server Error") + self.conn.send_response(response) + output = self.conn.data_to_send() + self.transport.write(b"".join(output)) + + async def send(self, message: ASGISendEvent) -> None: + await self.writable.wait() + + if not self.handshake_complete and self.initial_response is None: + if message["type"] == "websocket.accept": + self.logger.info( + '%s - "WebSocket %s" [accepted]', + get_client_addr(self.scope), + get_path_with_query_string(self.scope), + ) + headers = [ + (name.decode("latin-1").lower(), value.decode("latin-1")) + for name, value in (self.default_headers + list(message.get("headers", []))) + ] + accepted_subprotocol = message.get("subprotocol") + if accepted_subprotocol: + headers.append(("Sec-WebSocket-Protocol", accepted_subprotocol)) + self.response.headers.update(headers) + + if not self.transport.is_closing(): + self.handshake_complete = True + self.conn.send_response(self.response) + output = self.conn.data_to_send() + self.transport.write(b"".join(output)) + self.start_keepalive() + + elif message["type"] == "websocket.close": + self.queue.put_nowait({"type": "websocket.disconnect", "code": 1006}) + self.logger.info( + '%s - "WebSocket %s" 403', + get_client_addr(self.scope), + get_path_with_query_string(self.scope), + ) + response = self.conn.reject(HTTPStatus.FORBIDDEN, "") + self.conn.send_response(response) + output = self.conn.data_to_send() + self.close_sent = True + self.handshake_complete = True + self.transport.write(b"".join(output)) + self.transport.close() + elif message["type"] == "websocket.http.response.start" and self.initial_response is None: + if not (100 <= message["status"] < 600): + raise RuntimeError("Invalid HTTP status code '%d' in response." % message["status"]) + self.logger.info( + '%s - "WebSocket %s" %d', + get_client_addr(self.scope), + get_path_with_query_string(self.scope), + message["status"], + ) + headers = [ + (name.decode("latin-1"), value.decode("latin-1")) + for name, value in list(message.get("headers", [])) + ] + self.initial_response = (message["status"], headers, b"") + else: + raise RuntimeError( + "Expected ASGI message 'websocket.accept', 'websocket.close' " + f"or 'websocket.http.response.start' but got '{message['type']}'." + ) + + elif not self.close_sent and self.initial_response is None: + try: + if message["type"] == "websocket.send": + bytes_data = message.get("bytes") + text_data = message.get("text") + if bytes_data is not None: + self.conn.send_binary(bytes_data) + elif text_data is not None: + self.conn.send_text(text_data.encode()) + output = self.conn.data_to_send() + self.transport.write(b"".join(output)) + + elif message["type"] == "websocket.close": + if not self.transport.is_closing(): + code = message.get("code", 1000) + reason = message.get("reason", "") or "" + self.queue.put_nowait({"type": "websocket.disconnect", "code": code, "reason": reason}) + self.conn.send_close(code, reason) + output = self.conn.data_to_send() + self.transport.write(b"".join(output)) + self.close_sent = True + self.transport.close() + else: + raise RuntimeError( + f"Expected ASGI message 'websocket.send' or 'websocket.close', but got '{message['type']}'." + ) + except InvalidState: + raise ClientDisconnected() + elif self.initial_response is not None: + if message["type"] == "websocket.http.response.body": + body = self.initial_response[2] + message["body"] + self.initial_response = self.initial_response[:2] + (body,) + if not message.get("more_body", False): + response = self.conn.reject(self.initial_response[0], body.decode()) + response.headers.update(self.initial_response[1]) + self.queue.put_nowait({"type": "websocket.disconnect", "code": 1006}) + self.conn.send_response(response) + output = self.conn.data_to_send() + self.close_sent = True + self.transport.write(b"".join(output)) + self.transport.close() + else: # pragma: no cover + raise RuntimeError(f"Expected ASGI message 'websocket.http.response.body' but got '{message['type']}'.") + + else: + raise RuntimeError(f"Unexpected ASGI message '{message['type']}', after sending 'websocket.close'.") + + async def receive(self) -> ASGIReceiveEvent: + message = await self.queue.get() + if self.read_paused and self.queue.empty(): + self.read_paused = False + self.transport.resume_reading() + return message diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/wsproto_impl.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/wsproto_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..adca63f9df595983d4f9d43d395a8b5042269110 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/protocols/websockets/wsproto_impl.py @@ -0,0 +1,458 @@ +from __future__ import annotations + +import asyncio +import logging +import random +import struct +from asyncio import TimerHandle +from io import BytesIO, StringIO +from typing import Any, Literal, cast +from urllib.parse import unquote + +import wsproto +from wsproto import ConnectionType, events +from wsproto.connection import ConnectionState +from wsproto.extensions import Extension, PerMessageDeflate +from wsproto.utilities import LocalProtocolError, RemoteProtocolError + +from uvicorn._types import ASGI3Application, ASGISendEvent, WebSocketEvent, WebSocketReceiveEvent, WebSocketScope +from uvicorn.config import Config +from uvicorn.logging import TRACE_LOG_LEVEL +from uvicorn.protocols.utils import ( + ClientDisconnected, + get_client_addr, + get_local_addr, + get_path_with_query_string, + get_remote_addr, + is_ssl, +) +from uvicorn.server import ServerState + + +class FrameTooLargeError(Exception): + """Raised when accumulated websocket message bytes exceed `ws_max_size`.""" + + +class WebsocketBuffer: + def __init__(self, max_length: int) -> None: + self.value: BytesIO | StringIO | None = None + self.length = 0 + self.max_length = max_length + + def extend(self, event: events.TextMessage | events.BytesMessage) -> None: + if self.value is None: + self.value = StringIO() if isinstance(event, events.TextMessage) else BytesIO() + self.value.write(event.data) # type: ignore[arg-type] + # `ws_max_size` is a byte budget, so count UTF-8 bytes for text. + self.length += len(event.data.encode()) if isinstance(event, events.TextMessage) else len(event.data) + if self.length > self.max_length: + raise FrameTooLargeError + + def clear(self) -> None: + self.value = None + self.length = 0 + + def to_message(self) -> WebSocketReceiveEvent: + if isinstance(self.value, StringIO): + return {"type": "websocket.receive", "text": self.value.getvalue()} + assert isinstance(self.value, BytesIO) + return {"type": "websocket.receive", "bytes": self.value.getvalue()} + + +class WSProtocol(asyncio.Protocol): + def __init__( + self, + config: Config, + server_state: ServerState, + app_state: dict[str, Any], + _loop: asyncio.AbstractEventLoop | None = None, + ) -> None: + if not config.loaded: + config.load() # pragma: full coverage + + self.config = config + self.app = cast(ASGI3Application, config.loaded_app) + self.loop = _loop or asyncio.get_event_loop() + self.logger = logging.getLogger("uvicorn.error") + self.root_path = config.root_path + self.app_state = app_state + + # Shared server state + self.connections = server_state.connections + self.tasks = server_state.tasks + self.default_headers = server_state.default_headers + + # Connection state + self.transport: asyncio.Transport = None # type: ignore[assignment] + self.server: tuple[str, int | None] | None = None + self.client: tuple[str, int] | None = None + self.scheme: Literal["wss", "ws"] = None # type: ignore[assignment] + + # WebSocket state + self.queue: asyncio.Queue[WebSocketEvent] = asyncio.Queue() + self.handshake_complete = False + self.close_sent = False + + # Rejection state + self.response_started = False + + self.conn = wsproto.WSConnection(connection_type=ConnectionType.SERVER) + + self.read_paused = False + self.writable = asyncio.Event() + self.writable.set() + + # Keepalive state + self.ping_interval = config.ws_ping_interval + self.ping_timeout = config.ws_ping_timeout + self.ping_timer: TimerHandle | None = None + self.pong_timer: TimerHandle | None = None + self.pending_ping_payload: bytes | None = None + self.ping_sent_at: float = 0.0 + self.last_ping_rtt: float = 0.0 + + # Buffer + self.buffer = WebsocketBuffer(self.config.ws_max_size) + + # Protocol interface + + def connection_made(self, transport: asyncio.Transport) -> None: # type: ignore[override] + self.connections.add(self) + self.transport = transport + self.server = get_local_addr(transport) + self.client = get_remote_addr(transport) + self.scheme = "wss" if is_ssl(transport) else "ws" + + if self.logger.level <= TRACE_LOG_LEVEL: + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sWebSocket connection made", prefix) + + def connection_lost(self, exc: Exception | None) -> None: + self.stop_keepalive() + code = 1005 if self.handshake_complete else 1006 + self.queue.put_nowait({"type": "websocket.disconnect", "code": code}) + self.connections.remove(self) + + if self.logger.level <= TRACE_LOG_LEVEL: + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sWebSocket connection lost", prefix) + + self.handshake_complete = True + if exc is None: + self.transport.close() + + def eof_received(self) -> None: + pass + + def data_received(self, data: bytes) -> None: + try: + self.conn.receive_data(data) + except RemoteProtocolError as err: + # TODO: Remove `type: ignore` when wsproto fixes the type annotation. + self.transport.write(self.conn.send(err.event_hint)) # type: ignore[arg-type] # noqa: E501 + self.transport.close() + else: + self.handle_events() + + def handle_events(self) -> None: + for event in self.conn.events(): + if self.close_sent: + return + if isinstance(event, events.Request): + self.handle_connect(event) + elif isinstance(event, (events.TextMessage, events.BytesMessage)): + self.handle_message(event) + elif isinstance(event, events.CloseConnection): + self.handle_close(event) + elif isinstance(event, events.Ping): + self.handle_ping(event) + elif isinstance(event, events.Pong): + self.handle_pong(event) + + def pause_writing(self) -> None: + """ + Called by the transport when the write buffer exceeds the high water mark. + """ + self.writable.clear() # pragma: full coverage + + def resume_writing(self) -> None: + """ + Called by the transport when the write buffer drops below the low water mark. + """ + self.writable.set() # pragma: full coverage + + def shutdown(self) -> None: + self.stop_keepalive() + if self.handshake_complete: + self.queue.put_nowait({"type": "websocket.disconnect", "code": 1012}) + output = self.conn.send(wsproto.events.CloseConnection(code=1012)) + self.transport.write(output) + else: + self.send_500_response() + self.transport.close() + + def on_task_complete(self, task: asyncio.Task[None]) -> None: + self.tasks.discard(task) + + # Event handlers + + def handle_connect(self, event: events.Request) -> None: + headers = [(b"host", event.host.encode())] + headers += [(key.lower(), value) for key, value in event.extra_headers] + raw_path, _, query_string = event.target.partition("?") + path = unquote(raw_path) + full_path = self.root_path + path + full_raw_path = self.root_path.encode("ascii") + raw_path.encode("ascii") + self.scope: WebSocketScope = { + "type": "websocket", + "asgi": {"version": self.config.asgi_version, "spec_version": "2.4"}, + "http_version": "1.1", + "scheme": self.scheme, + "server": self.server, + "client": self.client, + "root_path": self.root_path, + "path": full_path, + "raw_path": full_raw_path, + "query_string": query_string.encode("ascii"), + "headers": headers, + "subprotocols": event.subprotocols, + "state": self.app_state.copy(), + "extensions": {"websocket.http.response": {}}, + } + self.queue.put_nowait({"type": "websocket.connect"}) + task = self.loop.create_task(self.run_asgi()) + task.add_done_callback(self.on_task_complete) + self.tasks.add(task) + + def handle_message(self, event: events.TextMessage | events.BytesMessage) -> None: + try: + self.buffer.extend(event) + except FrameTooLargeError: + self.close_sent = True + reason = f"Message exceeds the maximum size ({self.config.ws_max_size} bytes)" + self.queue.put_nowait({"type": "websocket.disconnect", "code": 1009, "reason": reason}) + if not self.transport.is_closing(): + self.transport.write(self.conn.send(wsproto.events.CloseConnection(code=1009, reason=reason))) + self.transport.close() + return + if event.message_finished: + self.queue.put_nowait(self.buffer.to_message()) + self.buffer.clear() + if not self.read_paused: + self.read_paused = True + self.transport.pause_reading() + + def handle_close(self, event: events.CloseConnection) -> None: + if self.conn.state == ConnectionState.REMOTE_CLOSING: + self.transport.write(self.conn.send(event.response())) + self.queue.put_nowait({"type": "websocket.disconnect", "code": event.code, "reason": event.reason}) + self.transport.close() + + def handle_ping(self, event: events.Ping) -> None: + self.transport.write(self.conn.send(event.response())) + + def handle_pong(self, event: events.Pong) -> None: + # Ignore unsolicited pongs and stale pongs whose payload doesn't match the ping currently in flight. + if self.pending_ping_payload is None or bytes(event.payload) != self.pending_ping_payload: + return # pragma: no cover + + self.last_ping_rtt = self.loop.time() - self.ping_sent_at + self.pending_ping_payload = None + # The peer answered in time; cancel the pong deadline and chain the next ping. This `schedule_ping()` call is + # what keeps the keepalive loop running when ping_timeout is set. When ping_timeout is None the next ping is + # already scheduled by `send_keepalive_ping`, so we must not schedule a duplicate here. + if self.pong_timer is not None: + self.pong_timer.cancel() + self.pong_timer = None + self.schedule_ping() + + def start_keepalive(self) -> None: + if self.ping_interval is not None and self.ping_interval > 0: + self.schedule_ping() + + def stop_keepalive(self) -> None: + if self.ping_timer is not None: + self.ping_timer.cancel() + self.ping_timer = None + if self.pong_timer is not None: # pragma: no cover + self.pong_timer.cancel() + self.pong_timer = None + self.pending_ping_payload = None + + def schedule_ping(self) -> None: + assert self.ping_interval is not None + delay = max(0.0, self.ping_interval - self.last_ping_rtt) + self.ping_timer = self.loop.call_later(delay, self.send_keepalive_ping) + + def send_keepalive_ping(self) -> None: + self.ping_timer = None + if self.close_sent or self.transport.is_closing(): # pragma: no cover + return + # Random 4-byte payload identifies this ping; `handle_pong` uses it to ignore stale or unsolicited pongs. + self.pending_ping_payload = struct.pack("!I", random.getrandbits(32)) + self.ping_sent_at = self.loop.time() + self.transport.write(self.conn.send(wsproto.events.Ping(payload=self.pending_ping_payload))) + if self.ping_timeout is not None: + self.pong_timer = self.loop.call_later(self.ping_timeout, self.keepalive_timeout) + else: # pragma: no cover + self.schedule_ping() + + def keepalive_timeout(self) -> None: + self.pong_timer = None + self.pending_ping_payload = None + if self.close_sent or self.transport.is_closing(): # pragma: no cover + return + if self.logger.level <= TRACE_LOG_LEVEL: + prefix = "%s:%d - " % self.client if self.client else "" + self.logger.log(TRACE_LOG_LEVEL, "%sWebSocket keepalive ping timeout", prefix) + reason = "keepalive ping timeout" + self.transport.write(self.conn.send(wsproto.events.CloseConnection(code=1011, reason=reason))) + self.close_sent = True + self.transport.close() + + def send_500_response(self) -> None: + if self.response_started or self.handshake_complete: + return # we cannot send responses anymore + headers: list[tuple[bytes, bytes]] = [ + (b"content-type", b"text/plain; charset=utf-8"), + (b"connection", b"close"), + (b"content-length", b"21"), + ] + output = self.conn.send(wsproto.events.RejectConnection(status_code=500, headers=headers, has_body=True)) + output += self.conn.send(wsproto.events.RejectData(data=b"Internal Server Error")) + self.transport.write(output) + + async def run_asgi(self) -> None: + try: + result = await self.app(self.scope, self.receive, self.send) # type: ignore[func-returns-value] + except ClientDisconnected: + pass # pragma: full coverage + except BaseException: + self.logger.exception("Exception in ASGI application\n") + self.send_500_response() + else: + if not self.handshake_complete: + self.logger.error("ASGI callable returned without completing handshake.") + self.send_500_response() + elif result is not None: + self.logger.error("ASGI callable should return None, but returned '%s'.", result) + self.transport.close() + + async def send(self, message: ASGISendEvent) -> None: + await self.writable.wait() + + if not self.handshake_complete: + if message["type"] == "websocket.accept": + self.logger.info( + '%s - "WebSocket %s" [accepted]', + get_client_addr(self.scope), + get_path_with_query_string(self.scope), + ) + subprotocol = message.get("subprotocol") + extra_headers = self.default_headers + list(message.get("headers", [])) + extensions: list[Extension] = [] + if self.config.ws_per_message_deflate: + extensions.append(PerMessageDeflate()) + if not self.transport.is_closing(): + self.handshake_complete = True + output = self.conn.send( + wsproto.events.AcceptConnection( + subprotocol=subprotocol, + extensions=extensions, + extra_headers=extra_headers, + ) + ) + self.transport.write(output) + self.start_keepalive() + + elif message["type"] == "websocket.close": + self.queue.put_nowait({"type": "websocket.disconnect", "code": 1006}) + self.logger.info( + '%s - "WebSocket %s" 403', + get_client_addr(self.scope), + get_path_with_query_string(self.scope), + ) + self.handshake_complete = True + self.close_sent = True + event = events.RejectConnection(status_code=403, headers=[]) + output = self.conn.send(event) + self.transport.write(output) + self.transport.close() + + elif message["type"] == "websocket.http.response.start": + # ensure status code is in the valid range + if not (100 <= message["status"] < 600): + msg = "Invalid HTTP status code '%d' in response." + raise RuntimeError(msg % message["status"]) + self.logger.info( + '%s - "WebSocket %s" %d', + get_client_addr(self.scope), + get_path_with_query_string(self.scope), + message["status"], + ) + self.handshake_complete = True + event = events.RejectConnection( + status_code=message["status"], + headers=list(message["headers"]), + has_body=True, + ) + output = self.conn.send(event) + self.transport.write(output) + self.response_started = True + + else: + raise RuntimeError( + "Expected ASGI message 'websocket.accept', 'websocket.close' " + f"or 'websocket.http.response.start' but got '{message['type']}'." + ) + + elif not self.close_sent and not self.response_started: + try: + if message["type"] == "websocket.send": + bytes_data = message.get("bytes") + text_data = message.get("text") + data = text_data if bytes_data is None else bytes_data + output = self.conn.send(wsproto.events.Message(data=data)) # type: ignore + if not self.transport.is_closing(): + self.transport.write(output) + + elif message["type"] == "websocket.close": + self.close_sent = True + code = message.get("code", 1000) + reason = message.get("reason", "") or "" + self.queue.put_nowait({"type": "websocket.disconnect", "code": code, "reason": reason}) + output = self.conn.send(wsproto.events.CloseConnection(code=code, reason=reason)) + if not self.transport.is_closing(): + self.transport.write(output) + self.transport.close() + + else: + raise RuntimeError( + f"Expected ASGI message 'websocket.send' or 'websocket.close', but got '{message['type']}'." + ) + except LocalProtocolError as exc: + raise ClientDisconnected from exc + elif self.response_started: + if message["type"] == "websocket.http.response.body": + body_finished = not message.get("more_body", False) + reject_data = events.RejectData(data=message["body"], body_finished=body_finished) + output = self.conn.send(reject_data) + self.transport.write(output) + + if body_finished: + self.queue.put_nowait({"type": "websocket.disconnect", "code": 1006}) + self.close_sent = True + self.transport.close() + + else: + raise RuntimeError(f"Expected ASGI message 'websocket.http.response.body' but got '{message['type']}'.") + + else: + raise RuntimeError(f"Unexpected ASGI message '{message['type']}', after sending 'websocket.close'.") + + async def receive(self) -> WebSocketEvent: + message = await self.queue.get() + if self.read_paused and self.queue.empty(): + self.read_paused = False + self.transport.resume_reading() + return message diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cfceb6b94ce36dad006b1f81b816d45ce70ab3d6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/__init__.py @@ -0,0 +1,16 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from uvicorn.supervisors.basereload import BaseReload +from uvicorn.supervisors.multiprocess import Multiprocess + +if TYPE_CHECKING: + ChangeReload: type[BaseReload] +else: + try: + from uvicorn.supervisors.watchfilesreload import WatchFilesReload as ChangeReload + except ImportError: # pragma: no cover + from uvicorn.supervisors.statreload import StatReload as ChangeReload + +__all__ = ["Multiprocess", "ChangeReload"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10e6292a88716a04268098476a20d3141fbad2d2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/__pycache__/basereload.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/__pycache__/basereload.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..339529d735c76a8fc7904b6a89feb097220cf215 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/__pycache__/basereload.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/__pycache__/multiprocess.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/__pycache__/multiprocess.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0587172749c2f60e0da6acd292185748d402ed22 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/__pycache__/multiprocess.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/__pycache__/statreload.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/__pycache__/statreload.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84e5613736c49ca9c0bf5fd17c2d76f4e0bd23dd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/__pycache__/statreload.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/__pycache__/watchfilesreload.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/__pycache__/watchfilesreload.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92cd9f6867da811099c1729e1f3172b43c9e50b7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/__pycache__/watchfilesreload.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/basereload.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/basereload.py new file mode 100644 index 0000000000000000000000000000000000000000..66e34f53ffe62df65284d914bbf7d44a268b4917 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/basereload.py @@ -0,0 +1,125 @@ +from __future__ import annotations + +import logging +import os +import signal +import sys +import threading +from collections.abc import Callable, Iterator +from pathlib import Path +from socket import socket +from types import FrameType + +import click + +from uvicorn._subprocess import get_subprocess +from uvicorn.config import Config + +HANDLED_SIGNALS = ( + signal.SIGINT, # Unix signal 2. Sent by Ctrl+C. + signal.SIGTERM, # Unix signal 15. Sent by `kill `. +) + +logger = logging.getLogger("uvicorn.error") + + +class BaseReload: + def __init__( + self, + config: Config, + target: Callable[[list[socket] | None], None], + sockets: list[socket], + ) -> None: + self.config = config + self.target = target + self.sockets = sockets + self.should_exit = threading.Event() + self.pid = os.getpid() + self.is_restarting = False + self.reloader_name: str | None = None + + def signal_handler(self, sig: int, frame: FrameType | None) -> None: # pragma: full coverage + """ + A signal handler that is registered with the parent process. + """ + if sys.platform == "win32" and self.is_restarting: + self.is_restarting = False + else: + self.should_exit.set() + + def run(self) -> None: + self.startup() + for changes in self: + if changes: + logger.warning( + "%s detected changes in %s. Reloading...", + self.reloader_name, + ", ".join(map(_display_path, changes)), + ) + self.restart() + + self.shutdown() + + def pause(self) -> None: + if self.should_exit.wait(self.config.reload_delay): + raise StopIteration() + + def __iter__(self) -> Iterator[list[Path] | None]: + return self + + def __next__(self) -> list[Path] | None: + return self.should_restart() + + def startup(self) -> None: + message = f"Started reloader process [{self.pid}] using {self.reloader_name}" + color_message = "Started reloader process [{}] using {}".format( + click.style(str(self.pid), fg="cyan", bold=True), + click.style(str(self.reloader_name), fg="cyan", bold=True), + ) + logger.info(message, extra={"color_message": color_message}) + + for sig in HANDLED_SIGNALS: + signal.signal(sig, self.signal_handler) + + self.process = get_subprocess(config=self.config, target=self.target, sockets=self.sockets) + self.process.start() + + def restart(self) -> None: + if sys.platform == "win32": # pragma: py-not-win32 + self.is_restarting = True + assert self.process.pid is not None + os.kill(self.process.pid, signal.CTRL_C_EVENT) + + # This is a workaround to ensure the Ctrl+C event is processed + sys.stdout.write(" ") # This has to be a non-empty string + sys.stdout.flush() + else: # pragma: py-win32 + self.process.terminate() + self.process.join() + + self.process = get_subprocess(config=self.config, target=self.target, sockets=self.sockets) + self.process.start() + + def shutdown(self) -> None: + if sys.platform == "win32": + self.should_exit.set() # pragma: py-not-win32 + else: + self.process.terminate() # pragma: py-win32 + self.process.join() + + for sock in self.sockets: + sock.close() + + message = f"Stopping reloader process [{str(self.pid)}]" + color_message = "Stopping reloader process [{}]".format(click.style(str(self.pid), fg="cyan", bold=True)) + logger.info(message, extra={"color_message": color_message}) + + def should_restart(self) -> list[Path] | None: + raise NotImplementedError("Reload strategies should override should_restart()") + + +def _display_path(path: Path) -> str: + try: + return f"'{path.relative_to(Path.cwd())}'" + except ValueError: + return f"'{path}'" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/multiprocess.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/multiprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..3ad98afab2bd5f6d6d729b7d3ad7c50ed5c6b941 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/multiprocess.py @@ -0,0 +1,223 @@ +from __future__ import annotations + +import logging +import os +import signal +import threading +from collections.abc import Callable +from multiprocessing import Pipe +from socket import socket +from typing import Any + +import click + +from uvicorn._subprocess import get_subprocess +from uvicorn.config import Config + +SIGNALS = { + getattr(signal, f"SIG{x}"): x + for x in "INT TERM BREAK HUP QUIT TTIN TTOU USR1 USR2 WINCH".split() + if hasattr(signal, f"SIG{x}") +} + +logger = logging.getLogger("uvicorn.error") + + +class Process: + def __init__( + self, + config: Config, + target: Callable[[list[socket] | None], None], + sockets: list[socket], + ) -> None: + self.real_target = target + + self.parent_conn, self.child_conn = Pipe() + self.process = get_subprocess(config, self.target, sockets) + + def ping(self, timeout: float = 5) -> bool: + self.parent_conn.send(b"ping") + if self.parent_conn.poll(timeout): + self.parent_conn.recv() + return True + return False + + def pong(self) -> None: + self.child_conn.recv() + self.child_conn.send(b"pong") + + def always_pong(self) -> None: + while True: + self.pong() + + def target(self, sockets: list[socket] | None = None) -> Any: # pragma: no cover + if os.name == "nt": # pragma: py-not-win32 + # Windows doesn't support SIGTERM, so we use SIGBREAK instead. + # And then we raise SIGTERM when SIGBREAK is received. + # https://learn.microsoft.com/zh-cn/cpp/c-runtime-library/reference/signal?view=msvc-170 + signal.signal( + signal.SIGBREAK, # type: ignore[attr-defined] + lambda sig, frame: signal.raise_signal(signal.SIGTERM), + ) + + threading.Thread(target=self.always_pong, daemon=True).start() + return self.real_target(sockets) + + def is_alive(self, timeout: float = 5) -> bool: + if not self.process.is_alive(): + return False # pragma: full coverage + + return self.ping(timeout) + + def start(self) -> None: + self.process.start() + + def terminate(self) -> None: + if self.process.exitcode is None: # Process is still running + assert self.process.pid is not None + if os.name == "nt": # pragma: py-not-win32 + # Windows doesn't support SIGTERM. + # So send SIGBREAK, and then in process raise SIGTERM. + os.kill(self.process.pid, signal.CTRL_BREAK_EVENT) # type: ignore[attr-defined] + else: + os.kill(self.process.pid, signal.SIGTERM) + logger.info(f"Terminated child process [{self.process.pid}]") + + self.parent_conn.close() + self.child_conn.close() + + def kill(self) -> None: + # In Windows, the method will call `TerminateProcess` to kill the process. + # In Unix, the method will send SIGKILL to the process. + self.process.kill() + + def join(self) -> None: + logger.info(f"Waiting for child process [{self.process.pid}]") + self.process.join() + + @property + def pid(self) -> int | None: + return self.process.pid + + +class Multiprocess: + def __init__( + self, + config: Config, + target: Callable[[list[socket] | None], None], + sockets: list[socket], + ) -> None: + self.config = config + self.target = target + self.sockets = sockets + + self.processes_num = config.workers + self.processes: list[Process] = [] + + self.should_exit = threading.Event() + + self.signal_queue: list[int] = [] + for sig in SIGNALS: + signal.signal(sig, lambda sig, frame: self.signal_queue.append(sig)) + + def init_processes(self) -> None: + for _ in range(self.processes_num): + process = Process(self.config, self.target, self.sockets) + process.start() + self.processes.append(process) + + def terminate_all(self) -> None: + for process in self.processes: + process.terminate() + + def join_all(self) -> None: + for process in self.processes: + process.join() + + def restart_all(self) -> None: + for idx, process in enumerate(self.processes): + process.terminate() + process.join() + new_process = Process(self.config, self.target, self.sockets) + new_process.start() + self.processes[idx] = new_process + + def run(self) -> None: + message = f"Started parent process [{os.getpid()}]" + color_message = "Started parent process [{}]".format(click.style(str(os.getpid()), fg="cyan", bold=True)) + logger.info(message, extra={"color_message": color_message}) + + self.init_processes() + + while not self.should_exit.wait(0.5): + self.handle_signals() + self.keep_subprocess_alive() + + self.terminate_all() + self.join_all() + + message = f"Stopping parent process [{os.getpid()}]" + color_message = "Stopping parent process [{}]".format(click.style(str(os.getpid()), fg="cyan", bold=True)) + logger.info(message, extra={"color_message": color_message}) + + def keep_subprocess_alive(self) -> None: + if self.should_exit.is_set(): + return # parent process is exiting, no need to keep subprocess alive + + for idx, process in enumerate(self.processes): + if process.is_alive(timeout=self.config.timeout_worker_healthcheck): + continue + + process.kill() # process is hung, kill it + process.join() + + if self.should_exit.is_set(): + return # pragma: full coverage + + logger.info(f"Child process [{process.pid}] died") + process = Process(self.config, self.target, self.sockets) + process.start() + self.processes[idx] = process + + def handle_signals(self) -> None: + for sig in tuple(self.signal_queue): + self.signal_queue.remove(sig) + sig_name = SIGNALS[sig] + sig_handler = getattr(self, f"handle_{sig_name.lower()}", None) + if sig_handler is not None: + sig_handler() + else: # pragma: no cover + logger.debug(f"Received signal {sig_name}, but no handler is defined for it.") + + def handle_int(self) -> None: + logger.info("Received SIGINT, exiting.") + self.should_exit.set() + + def handle_term(self) -> None: + logger.info("Received SIGTERM, exiting.") + self.should_exit.set() + + def handle_break(self) -> None: # pragma: py-not-win32 + logger.info("Received SIGBREAK, exiting.") + self.should_exit.set() + + def handle_hup(self) -> None: # pragma: py-win32 + logger.info("Received SIGHUP, restarting processes.") + self.restart_all() + + def handle_ttin(self) -> None: # pragma: py-win32 + logger.info("Received SIGTTIN, increasing the number of processes.") + self.processes_num += 1 + process = Process(self.config, self.target, self.sockets) + process.start() + self.processes.append(process) + + def handle_ttou(self) -> None: # pragma: py-win32 + logger.info("Received SIGTTOU, decreasing number of processes.") + if self.processes_num <= 1: + logger.info("Already reached one process, cannot decrease the number of processes anymore.") + return + self.processes_num -= 1 + process = self.processes.pop() + process.terminate() + process.join() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/statreload.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/statreload.py new file mode 100644 index 0000000000000000000000000000000000000000..28693f9cc6d14ed8ea98518a78162e8c84f51c72 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/statreload.py @@ -0,0 +1,52 @@ +from __future__ import annotations + +import logging +from collections.abc import Callable, Iterator +from pathlib import Path +from socket import socket + +from uvicorn.config import Config +from uvicorn.supervisors.basereload import BaseReload + +logger = logging.getLogger("uvicorn.error") + + +class StatReload(BaseReload): + def __init__( + self, + config: Config, + target: Callable[[list[socket] | None], None], + sockets: list[socket], + ) -> None: + super().__init__(config, target, sockets) + self.reloader_name = "StatReload" + self.mtimes: dict[Path, float] = {} + + if config.reload_excludes or config.reload_includes: + logger.warning("--reload-include and --reload-exclude have no effect unless watchfiles is installed.") + + def should_restart(self) -> list[Path] | None: + self.pause() + + for file in self.iter_py_files(): + try: + mtime = file.stat().st_mtime + except OSError: # pragma: nocover + continue + + old_time = self.mtimes.get(file) + if old_time is None: + self.mtimes[file] = mtime + continue + elif mtime > old_time: + return [file] + return None + + def restart(self) -> None: + self.mtimes = {} + return super().restart() + + def iter_py_files(self) -> Iterator[Path]: + for reload_dir in self.config.reload_dirs: + for path in list(reload_dir.rglob("*.py")): + yield path.resolve() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/watchfilesreload.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/watchfilesreload.py new file mode 100644 index 0000000000000000000000000000000000000000..600990595274dbc649176247c0c15840e59e0105 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/uvicorn/supervisors/watchfilesreload.py @@ -0,0 +1,86 @@ +from __future__ import annotations + +from collections.abc import Callable +from pathlib import Path +from socket import socket + +from watchfiles import watch + +from uvicorn.config import Config +from uvicorn.supervisors.basereload import BaseReload + + +class FileFilter: + def __init__(self, config: Config): + default_includes = ["*.py"] + self.includes = [default for default in default_includes if default not in config.reload_excludes] + self.includes.extend(config.reload_includes) + self.includes = list(set(self.includes)) + + default_excludes = [".*", ".py[cod]", ".sw.*", "~*"] + self.excludes = [default for default in default_excludes if default not in config.reload_includes] + self.exclude_dirs = [] + for e in config.reload_excludes: + p = Path(e) + try: + is_dir = p.is_dir() + except OSError: # pragma: no cover + # gets raised on Windows for values like "*.py" + is_dir = False + + if is_dir: + self.exclude_dirs.append(p) + else: + self.excludes.append(e) # pragma: full coverage + self.excludes = list(set(self.excludes)) + + def __call__(self, path: Path) -> bool: + for include_pattern in self.includes: + if path.match(include_pattern): + if str(path).endswith(include_pattern): + return True # pragma: full coverage + + for exclude_dir in self.exclude_dirs: + if exclude_dir in path.parents: + return False + + for exclude_pattern in self.excludes: + if path.match(exclude_pattern): + return False # pragma: full coverage + + return True + return False + + +class WatchFilesReload(BaseReload): + def __init__( + self, + config: Config, + target: Callable[[list[socket] | None], None], + sockets: list[socket], + ) -> None: + super().__init__(config, target, sockets) + self.reloader_name = "WatchFiles" + self.reload_dirs: list[Path] = [] + for directory in config.reload_dirs: + self.reload_dirs.append(directory) + + self.watch_filter = FileFilter(config) + self.watcher = watch( + *self.reload_dirs, + watch_filter=None, + stop_event=self.should_exit, + # using yield_on_timeout here mostly to make sure tests don't + # hang forever, won't affect the class's behavior + yield_on_timeout=True, + ignore_permission_denied=True, + ) + + def should_restart(self) -> list[Path] | None: + self.pause() + + changes = next(self.watcher) + if changes: + unique_paths = {Path(c[1]) for c in changes} + return [p for p in unique_paths if self.watch_filter(p)] + return None diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/watchfiles-1.1.1.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/watchfiles-1.1.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..00d225b9afba369ce9899cfaee48bf406ff8da40 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/watchfiles-1.1.1.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 to present Samuel Colvin + +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/micromamba_root/envs/pytorch_env/Lib/site-packages/watchfiles/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/watchfiles/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69ea6d0c3b735199b9f7b29b01f85bcfb302b2f9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/watchfiles/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/watchfiles/__pycache__/__main__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/watchfiles/__pycache__/__main__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20be1fc19069295d31cf7b7f53e71b2eb639781e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/watchfiles/__pycache__/__main__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/watchfiles/__pycache__/cli.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/watchfiles/__pycache__/cli.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f2325858126f5871cf503301cef47e4fe62ea50 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/watchfiles/__pycache__/cli.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/watchfiles/__pycache__/filters.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/watchfiles/__pycache__/filters.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e78e03cf0e803bc26ad66ffda7ce1c2fd9e1ffee Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/watchfiles/__pycache__/filters.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/watchfiles/__pycache__/main.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/watchfiles/__pycache__/main.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..309aa24600bc12521d99e8217a1b8a88dfb03423 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/watchfiles/__pycache__/main.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/watchfiles/__pycache__/run.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/watchfiles/__pycache__/run.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17b6ed5e4a818132e2b1fc28809825562643b0e0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/watchfiles/__pycache__/run.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/watchfiles/__pycache__/version.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/watchfiles/__pycache__/version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed54a3dba7f85a825720d9660aeaef6ea6f0e392 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/watchfiles/__pycache__/version.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..05f565d4c996bf550352f4fad032199168691c58 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__init__.py @@ -0,0 +1,30 @@ +""" +__init__.py +websocket - WebSocket client library for Python + +Copyright 2025 engn33r + +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. +""" + +from ._abnf import * # noqa: F401,F403 +from ._app import ( # noqa: F401 + WebSocketApp as WebSocketApp, + set_reconnect as set_reconnect, +) +from ._core import * # noqa: F401,F403 +from ._exceptions import * # noqa: F401,F403 +from ._logging import * # noqa: F401,F403 +from ._socket import * # noqa: F401,F403 + +__version__ = "1.9.0" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1fbcda5e281d45648c723391d1620b34a798417 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_abnf.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_abnf.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3760e052762312301fcdfee0655676c55b31b010 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_abnf.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_app.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_app.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea3f792046e40bf616f615be099cf364e26601e1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_app.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_cookiejar.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_cookiejar.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7029d79589cfb3db57484769b14b2793e7a0c289 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_cookiejar.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_core.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_core.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4656742fdd19b4f9c1b09d8fdab8b687cc24edb9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_core.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_dispatcher.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_dispatcher.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..738d20dd19d53e33370c5342576450b35fd47db4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_dispatcher.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_exceptions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_exceptions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f65f5b48198a8ef1cb3b9cdcac3913b3fdc18d2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_exceptions.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_handshake.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_handshake.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eca2f27587af86dc6d9335843f80d71836e2c4b6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_handshake.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_http.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_http.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c218fc8ed548f3177e1c3eef474cc743f6176692 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_http.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_logging.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_logging.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70f14a21a7c96dd40413675748ee9f14e4d33034 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_logging.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_socket.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_socket.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d95254898e9a49c32dd897c0ee1b75a9f32350cc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_socket.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_ssl_compat.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_ssl_compat.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c757b35ba8711eb88592cb0aa4478f43ca6fcfa9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_ssl_compat.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_url.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_url.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eec788bf6c66ea9d316692f54a10dd44b076769e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_url.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..829a6d8062cca7294328cb71472a2b42b301f777 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_wsdump.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_wsdump.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f97a9e0a86d393405eb5d4fab5121ad5c9c05500 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/__pycache__/_wsdump.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..726a2f3e583beb64cc0bbd6c66b54d603925fabb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/_utils.py @@ -0,0 +1,460 @@ +from typing import Union, Optional + +""" +_utils.py +websocket - WebSocket client library for Python + +Copyright 2025 engn33r + +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. +""" +__all__ = ["NoLock", "validate_utf8", "extract_err_message", "extract_error_code"] + + +class NoLock: + def __enter__(self) -> None: + pass + + def __exit__(self, exc_type, exc_value, traceback) -> None: + pass + + +try: + # If wsaccel is available we use compiled routines to validate UTF-8 + # strings. + from wsaccel.utf8validator import Utf8Validator + + def _validate_utf8(utfbytes: Union[str, bytes]) -> bool: + result: bool = Utf8Validator().validate(utfbytes)[0] + return result + +except ImportError: + # UTF-8 validator + # python implementation of http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ + + _UTF8_ACCEPT = 0 + _UTF8_REJECT = 12 + + _UTF8D = [ + # The first part of the table maps bytes to character classes that + # to reduce the size of the transition table and create bitmasks. + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 9, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 8, + 8, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 10, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 4, + 3, + 3, + 11, + 6, + 6, + 6, + 5, + 8, + 8, + 8, + 8, + 8, + 8, + 8, + 8, + 8, + 8, + 8, + # The second part is a transition table that maps a combination + # of a state of the automaton and a character class to a state. + 0, + 12, + 24, + 36, + 60, + 96, + 84, + 12, + 12, + 12, + 48, + 72, + 12, + 12, + 12, + 12, + 12, + 12, + 12, + 12, + 12, + 12, + 12, + 12, + 12, + 0, + 12, + 12, + 12, + 12, + 12, + 0, + 12, + 0, + 12, + 12, + 12, + 24, + 12, + 12, + 12, + 12, + 12, + 24, + 12, + 24, + 12, + 12, + 12, + 12, + 12, + 12, + 12, + 12, + 12, + 24, + 12, + 12, + 12, + 12, + 12, + 24, + 12, + 12, + 12, + 12, + 12, + 12, + 12, + 24, + 12, + 12, + 12, + 12, + 12, + 12, + 12, + 12, + 12, + 36, + 12, + 36, + 12, + 12, + 12, + 36, + 12, + 12, + 12, + 12, + 12, + 36, + 12, + 36, + 12, + 12, + 12, + 36, + 12, + 12, + 12, + 12, + 12, + 12, + 12, + 12, + 12, + 12, + ] + + def _decode(state: int, codep: int, ch: int) -> tuple: + tp = _UTF8D[ch] + + codep = ( + (ch & 0x3F) | (codep << 6) if (state != _UTF8_ACCEPT) else (0xFF >> tp) & ch + ) + state = _UTF8D[256 + state + tp] + + return state, codep + + def _validate_utf8(utfbytes: Union[str, bytes]) -> bool: + state = _UTF8_ACCEPT + codep = 0 + for i in utfbytes: + state, codep = _decode(state, codep, int(i)) + if state == _UTF8_REJECT: + return False + + return True + + +def validate_utf8(utfbytes: Union[str, bytes]) -> bool: + """ + validate utf8 byte string. + utfbytes: utf byte string to check. + return value: if valid utf8 string, return true. Otherwise, return false. + """ + return _validate_utf8(utfbytes) + + +def extract_err_message(exception: Exception) -> Optional[str]: + if exception.args: + exception_message: str = exception.args[0] + return exception_message + else: + return None + + +def extract_error_code(exception: Exception) -> Optional[int]: + if exception.args and len(exception.args) > 1: + return exception.args[0] if isinstance(exception.args[0], int) else None + return None diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/_wsdump.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/_wsdump.py new file mode 100644 index 0000000000000000000000000000000000000000..81be2521561afd9b418800ea5b30226754d2a358 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/_wsdump.py @@ -0,0 +1,244 @@ +#!/usr/bin/env python3 + +""" +_wsdump.py +websocket - WebSocket client library for Python + +Copyright 2025 engn33r + +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. +""" + +import argparse +import code +import gzip +import ssl +import sys +import threading +import time +import zlib +from urllib.parse import urlparse + +import websocket + +try: + import readline # noqa: F401 +except ImportError: + pass + + +def get_encoding() -> str: + encoding = getattr(sys.stdin, "encoding", "") + if not encoding: + return "utf-8" + else: + return encoding.lower() + + +OPCODE_DATA = (websocket.ABNF.OPCODE_TEXT, websocket.ABNF.OPCODE_BINARY) +ENCODING = get_encoding() + + +class VAction(argparse.Action): + def __call__( + self, + parser: argparse.Namespace, + args: tuple, + values: str, + option_string: str = None, + ) -> None: + if values is None: + values = "1" + try: + values = int(values) + except ValueError: + values = values.count("v") + 1 + setattr(args, self.dest, values) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="WebSocket Simple Dump Tool") + parser.add_argument( + "url", metavar="ws_url", help="websocket url. ex. ws://echo.websocket.events/" + ) + parser.add_argument("-p", "--proxy", help="proxy url. ex. http://127.0.0.1:8080") + parser.add_argument( + "-v", + "--verbose", + default=0, + nargs="?", + action=VAction, + dest="verbose", + help="set verbose mode. If set to 1, show opcode. " + "If set to 2, enable to trace websocket module", + ) + parser.add_argument( + "-n", "--nocert", action="store_true", help="Ignore invalid SSL cert" + ) + parser.add_argument("-r", "--raw", action="store_true", help="raw output") + parser.add_argument("-s", "--subprotocols", nargs="*", help="Set subprotocols") + parser.add_argument("-o", "--origin", help="Set origin") + parser.add_argument( + "--eof-wait", + default=0, + type=int, + help="wait time(second) after 'EOF' received.", + ) + parser.add_argument("-t", "--text", help="Send initial text") + parser.add_argument( + "--timings", action="store_true", help="Print timings in seconds" + ) + parser.add_argument("--headers", help="Set custom headers. Use ',' as separator") + + return parser.parse_args() + + +class RawInput: + def raw_input(self, prompt: str = "") -> str: + line = input(prompt) + + if ENCODING and ENCODING != "utf-8" and not isinstance(line, str): + line = line.decode(ENCODING).encode("utf-8") + elif isinstance(line, str): + line = line.encode("utf-8") + + return line + + +class InteractiveConsole(RawInput, code.InteractiveConsole): + def write(self, data: str) -> None: + sys.stdout.write("\033[2K\033[E") + # sys.stdout.write("\n") + sys.stdout.write("\033[34m< " + data + "\033[39m") + sys.stdout.write("\n> ") + sys.stdout.flush() + + def read(self) -> str: + return self.raw_input("> ") + + +class NonInteractive(RawInput): + def write(self, data: str) -> None: + sys.stdout.write(data) + sys.stdout.write("\n") + sys.stdout.flush() + + def read(self) -> str: + return self.raw_input("") + + +def main() -> None: + start_time = time.time() + args = parse_args() + if args.verbose > 1: + websocket.enableTrace(True) + options = {} + if args.proxy: + p = urlparse(args.proxy) + options["http_proxy_host"] = p.hostname + options["http_proxy_port"] = p.port + if args.origin: + options["origin"] = args.origin + if args.subprotocols: + options["subprotocols"] = args.subprotocols + opts = {} + if args.nocert: + opts = {"cert_reqs": ssl.CERT_NONE, "check_hostname": False} + if args.headers: + options["header"] = list(map(str.strip, args.headers.split(","))) + ws = websocket.create_connection(args.url, sslopt=opts, **options) + if args.raw: + console = NonInteractive() + else: + console = InteractiveConsole() + print("Press Ctrl+C to quit") + + def recv() -> tuple: + try: + frame = ws.recv_frame() + except websocket.WebSocketException: + return websocket.ABNF.OPCODE_CLOSE, "" + if not frame: + raise websocket.WebSocketException(f"Not a valid frame {frame}") + elif frame.opcode in OPCODE_DATA: + return frame.opcode, frame.data + elif frame.opcode == websocket.ABNF.OPCODE_CLOSE: + ws.send_close() + return frame.opcode, "" + elif frame.opcode == websocket.ABNF.OPCODE_PING: + ws.pong(frame.data) + return frame.opcode, frame.data + + return frame.opcode, frame.data + + def recv_ws() -> None: + while True: + opcode, data = recv() + msg = None + if opcode == websocket.ABNF.OPCODE_TEXT and isinstance(data, bytes): + data = str(data, "utf-8") + if ( + isinstance(data, bytes) and len(data) > 2 and data[:2] == b"\037\213" + ): # gzip magick + try: + data = "[gzip] " + str(gzip.decompress(data), "utf-8") + except: + pass + elif isinstance(data, bytes): + try: + data = "[zlib] " + str( + zlib.decompress(data, -zlib.MAX_WBITS), "utf-8" + ) + except: + pass + + if isinstance(data, bytes): + data = repr(data) + + if args.verbose: + msg = f"{websocket.ABNF.OPCODE_MAP.get(opcode)}: {data}" + else: + msg = data + + if msg is not None: + if args.timings: + console.write(f"{time.time() - start_time}: {msg}") + else: + console.write(msg) + + if opcode == websocket.ABNF.OPCODE_CLOSE: + break + + thread = threading.Thread(target=recv_ws) + thread.daemon = True + thread.start() + + if args.text: + ws.send(args.text) + + while True: + try: + message = console.read() + ws.send(message) + except KeyboardInterrupt: + return + except EOFError: + time.sleep(args.eof_wait) + return + + +if __name__ == "__main__": + try: + main() + except Exception as e: + print(e) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e29f055571af10e1c1b548970e2af24e6c93e9c0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/echo-server.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/echo-server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eaee8640a282be1fd112a6f8850f3e9b23c6a77f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/echo-server.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_abnf.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_abnf.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ead5deaf2d9bcc159f8ba3080fdae0153f4ea3a6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_abnf.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_app.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_app.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06e0cb456115a66464461368960a4ff29e81ad04 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_app.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_cookiejar.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_cookiejar.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57af54a0396d273cf1ea8fe5d3ccc1de8d320245 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_cookiejar.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_dispatcher.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_dispatcher.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9bc6e17706c31622dee5b194fae73ba464a2a110 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_dispatcher.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_handshake_large_response.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_handshake_large_response.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b526b0f25d205252f99381bb5d415bacb25af45 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_handshake_large_response.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_http.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_http.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa5e1942b7e215039f1faceffc7693650ef445a9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_http.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_large_payloads.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_large_payloads.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8bbf01977f8ed0a14902aa51156543b7b2087c2b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_large_payloads.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_socket.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_socket.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01713a331ec47f593ad0febce1b8ef215b52c1aa Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_socket.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_socket_bugs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_socket_bugs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da9c2fe592f460d758e0a58c4c4acb0d2d6b3216 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_socket_bugs.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_ssl_compat.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_ssl_compat.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67313dbaf388ed5fb4a21af289765a9cd014fde8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_ssl_compat.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_ssl_edge_cases.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_ssl_edge_cases.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3c99acf6f5c446700831477cd354364af81520c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_ssl_edge_cases.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_url.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_url.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08054b3a360567744eda55e68fbeb3183ad418e8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_url.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1cef0679b4ae9aa136ffc34e5d17ed1d08a9a84 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_websocket.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_websocket.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5dfd571cd80df928b126804de058c3a738b4bccc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/__pycache__/test_websocket.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/data/header01.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/data/header01.txt new file mode 100644 index 0000000000000000000000000000000000000000..3142b43b303e3601170246c77215b4c7c0053b35 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/data/header01.txt @@ -0,0 +1,6 @@ +HTTP/1.1 101 WebSocket Protocol Handshake +Connection: Upgrade +Upgrade: WebSocket +Sec-WebSocket-Accept: Kxep+hNu9n51529fGidYu7a3wO0= +some_header: something + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/data/header02.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/data/header02.txt new file mode 100644 index 0000000000000000000000000000000000000000..a9dd2ce3e397bff94682555248cd6b169a7d071b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/data/header02.txt @@ -0,0 +1,6 @@ +HTTP/1.1 101 WebSocket Protocol Handshake +Connection: Upgrade +Upgrade WebSocket +Sec-WebSocket-Accept: Kxep+hNu9n51529fGidYu7a3wO0= +some_header: something + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/data/header03.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/data/header03.txt new file mode 100644 index 0000000000000000000000000000000000000000..1a81dc70ce5952e94e0bacd896ed600784d6d505 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/data/header03.txt @@ -0,0 +1,8 @@ +HTTP/1.1 101 WebSocket Protocol Handshake +Connection: Upgrade, Keep-Alive +Upgrade: WebSocket +Sec-WebSocket-Accept: Kxep+hNu9n51529fGidYu7a3wO0= +Set-Cookie: Token=ABCDE +Set-Cookie: Token=FGHIJ +some_header: something + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/echo-server.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/echo-server.py new file mode 100644 index 0000000000000000000000000000000000000000..5d1e87087b63663f9f240d7b34f521e34372073e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/echo-server.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python + +# From https://github.com/aaugustin/websockets/blob/main/example/echo.py + +import asyncio +import os + +import websockets + +LOCAL_WS_SERVER_PORT = int(os.environ.get("LOCAL_WS_SERVER_PORT", "8765")) + + +async def echo(websocket): + async for message in websocket: + await websocket.send(message) + + +async def main(): + async with websockets.serve(echo, "localhost", LOCAL_WS_SERVER_PORT): + await asyncio.Future() # run forever + + +asyncio.run(main()) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_abnf.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_abnf.py new file mode 100644 index 0000000000000000000000000000000000000000..664ea3b314cb30f1f994399ce2937a61688e1346 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_abnf.py @@ -0,0 +1,125 @@ +# -*- coding: utf-8 -*- +# +import unittest + +from websocket._abnf import ABNF, frame_buffer +from websocket._exceptions import WebSocketProtocolException + +""" +test_abnf.py +websocket - WebSocket client library for Python + +Copyright 2025 engn33r + +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. +""" + + +class ABNFTest(unittest.TestCase): + def test_init(self): + a = ABNF(0, 0, 0, 0, opcode=ABNF.OPCODE_PING) + self.assertEqual(a.fin, 0) + self.assertEqual(a.rsv1, 0) + self.assertEqual(a.rsv2, 0) + self.assertEqual(a.rsv3, 0) + self.assertEqual(a.opcode, 9) + self.assertEqual(a.data, "") + a_bad = ABNF(0, 1, 0, 0, opcode=77) + self.assertEqual(a_bad.rsv1, 1) + self.assertEqual(a_bad.opcode, 77) + + def test_validate(self): + a_invalid_ping = ABNF(0, 0, 0, 0, opcode=ABNF.OPCODE_PING) + self.assertRaises( + WebSocketProtocolException, + a_invalid_ping.validate, + skip_utf8_validation=False, + ) + a_bad_rsv_value = ABNF(0, 1, 0, 0, opcode=ABNF.OPCODE_TEXT) + self.assertRaises( + WebSocketProtocolException, + a_bad_rsv_value.validate, + skip_utf8_validation=False, + ) + a_bad_opcode = ABNF(0, 0, 0, 0, opcode=77) + self.assertRaises( + WebSocketProtocolException, + a_bad_opcode.validate, + skip_utf8_validation=False, + ) + a_bad_close_frame = ABNF(0, 0, 0, 0, opcode=ABNF.OPCODE_CLOSE, data=b"\x01") + self.assertRaises( + WebSocketProtocolException, + a_bad_close_frame.validate, + skip_utf8_validation=False, + ) + a_bad_close_frame_2 = ABNF( + 0, 0, 0, 0, opcode=ABNF.OPCODE_CLOSE, data=b"\x01\x8a\xaa\xff\xdd" + ) + self.assertRaises( + WebSocketProtocolException, + a_bad_close_frame_2.validate, + skip_utf8_validation=False, + ) + a_bad_close_frame_3 = ABNF( + 0, 0, 0, 0, opcode=ABNF.OPCODE_CLOSE, data=b"\x03\xe7" + ) + self.assertRaises( + WebSocketProtocolException, + a_bad_close_frame_3.validate, + skip_utf8_validation=True, + ) + + def test_mask(self): + abnf_none_data = ABNF( + 0, 0, 0, 0, opcode=ABNF.OPCODE_PING, mask_value=1, data=None + ) + bytes_val = b"aaaa" + self.assertEqual(abnf_none_data._get_masked(bytes_val), bytes_val) + abnf_str_data = ABNF( + 0, 0, 0, 0, opcode=ABNF.OPCODE_PING, mask_value=1, data="a" + ) + self.assertEqual(abnf_str_data._get_masked(bytes_val), b"aaaa\x00") + + def test_format(self): + abnf_bad_rsv_bits = ABNF(2, 0, 0, 0, opcode=ABNF.OPCODE_TEXT) + self.assertRaises(ValueError, abnf_bad_rsv_bits.format) + abnf_bad_opcode = ABNF(0, 0, 0, 0, opcode=5) + self.assertRaises(ValueError, abnf_bad_opcode.format) + abnf_length_10 = ABNF(0, 0, 0, 0, opcode=ABNF.OPCODE_TEXT, data="abcdefghij") + self.assertEqual(b"\x01", abnf_length_10.format()[0].to_bytes(1, "big")) + self.assertEqual(b"\x8a", abnf_length_10.format()[1].to_bytes(1, "big")) + self.assertEqual("fin=0 opcode=1 data=abcdefghij", abnf_length_10.__str__()) + abnf_length_20 = ABNF( + 0, 0, 0, 0, opcode=ABNF.OPCODE_BINARY, data="abcdefghijabcdefghij" + ) + self.assertEqual(b"\x02", abnf_length_20.format()[0].to_bytes(1, "big")) + self.assertEqual(b"\x94", abnf_length_20.format()[1].to_bytes(1, "big")) + abnf_no_mask = ABNF( + 0, 0, 0, 0, opcode=ABNF.OPCODE_TEXT, mask_value=0, data=b"\x01\x8a\xcc" + ) + self.assertEqual(b"\x01\x03\x01\x8a\xcc", abnf_no_mask.format()) + + def test_frame_buffer(self): + fb = frame_buffer(0, True) + self.assertEqual(fb.recv, 0) + self.assertEqual(fb.skip_utf8_validation, True) + fb.clear + self.assertEqual(fb.header, None) + self.assertEqual(fb.length, None) + self.assertEqual(fb.mask_value, None) + self.assertEqual(fb.has_mask(), False) + + +if __name__ == "__main__": + unittest.main() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_app.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_app.py new file mode 100644 index 0000000000000000000000000000000000000000..c127e5c9e7e23fe22e4df2b742cd027635744226 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_app.py @@ -0,0 +1,395 @@ +# -*- coding: utf-8 -*- +# +import os +import os.path +import ssl +import threading +import unittest + +import websocket as ws + +""" +test_app.py +websocket - WebSocket client library for Python + +Copyright 2025 engn33r + +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. +""" + +# Skip test to access the internet unless TEST_WITH_INTERNET == 1 +TEST_WITH_INTERNET = os.environ.get("TEST_WITH_INTERNET", "0") == "1" +# Skip tests relying on local websockets server unless LOCAL_WS_SERVER_PORT != -1 +LOCAL_WS_SERVER_PORT = os.environ.get("LOCAL_WS_SERVER_PORT", "-1") +TEST_WITH_LOCAL_SERVER = LOCAL_WS_SERVER_PORT != "-1" +TRACEABLE = True + + +class WebSocketAppTest(unittest.TestCase): + class NotSetYet: + """A marker class for signalling that a value hasn't been set yet.""" + + def setUp(self): + ws.enableTrace(TRACEABLE) + + WebSocketAppTest.keep_running_open = WebSocketAppTest.NotSetYet() + WebSocketAppTest.keep_running_close = WebSocketAppTest.NotSetYet() + WebSocketAppTest.get_mask_key_id = WebSocketAppTest.NotSetYet() + WebSocketAppTest.on_error_data = WebSocketAppTest.NotSetYet() + + def tearDown(self): + WebSocketAppTest.keep_running_open = WebSocketAppTest.NotSetYet() + WebSocketAppTest.keep_running_close = WebSocketAppTest.NotSetYet() + WebSocketAppTest.get_mask_key_id = WebSocketAppTest.NotSetYet() + WebSocketAppTest.on_error_data = WebSocketAppTest.NotSetYet() + + def close(self): + pass + + @unittest.skipUnless( + TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled" + ) + def test_keep_running(self): + """A WebSocketApp should keep running as long as its self.keep_running + is not False (in the boolean context). + """ + + def on_open(self, *args, **kwargs): + """Set the keep_running flag for later inspection and immediately + close the connection. + """ + self.send("hello!") + WebSocketAppTest.keep_running_open = self.keep_running + self.keep_running = False + + def on_message(_, message): + print(message) + self.close() + + def on_close(self, *args, **kwargs): + """Set the keep_running flag for the test to use.""" + WebSocketAppTest.keep_running_close = self.keep_running + + app = ws.WebSocketApp( + f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}", + on_open=on_open, + on_close=on_close, + on_message=on_message, + ) + app.run_forever() + + # @unittest.skipUnless(TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled") + @unittest.skipUnless(False, "Test disabled for now (requires rel)") + def test_run_forever_dispatcher(self): + """A WebSocketApp should keep running as long as its self.keep_running + is not False (in the boolean context). + """ + + def on_open(self, *args, **kwargs): + """Send a message, receive, and send one more""" + self.send("hello!") + self.recv() + self.send("goodbye!") + + def on_message(_, message): + print(message) + self.close() + + app = ws.WebSocketApp( + f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}", + on_open=on_open, + on_message=on_message, + ) + app.run_forever(dispatcher="Dispatcher") # doesn't work + + # app.run_forever(dispatcher=rel) # would work + # rel.dispatch() + + @unittest.skipUnless( + TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled" + ) + def test_run_forever_teardown_clean_exit(self): + """The WebSocketApp.run_forever() method should return `False` when the application ends gracefully.""" + app = ws.WebSocketApp(f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}") + threading.Timer(interval=0.2, function=app.close).start() + teardown = app.run_forever() + self.assertEqual(teardown, False) + + @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") + def test_sock_mask_key(self): + """A WebSocketApp should forward the received mask_key function down + to the actual socket. + """ + + def my_mask_key_func(): + return "\x00\x00\x00\x00" + + app = ws.WebSocketApp( + "wss://api-pub.bitfinex.com/ws/1", get_mask_key=my_mask_key_func + ) + + # if numpy is installed, this assertion fail + # Note: We can't use 'is' for comparing the functions directly, need to use 'id'. + self.assertEqual(id(app.get_mask_key), id(my_mask_key_func)) + + @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") + def test_invalid_ping_interval_ping_timeout(self): + """Test exception handling if ping_interval < ping_timeout""" + + def on_ping(app, _): + print("Got a ping!") + app.close() + + def on_pong(app, _): + print("Got a pong! No need to respond") + app.close() + + app = ws.WebSocketApp( + "wss://api-pub.bitfinex.com/ws/1", on_ping=on_ping, on_pong=on_pong + ) + self.assertRaises( + ws.WebSocketException, + app.run_forever, + ping_interval=1, + ping_timeout=2, + sslopt={"cert_reqs": ssl.CERT_NONE}, + ) + + @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") + def test_ping_interval(self): + """Test WebSocketApp proper ping functionality""" + + def on_ping(app, _): + print("Got a ping!") + app.close() + + def on_pong(app, _): + print("Got a pong! No need to respond") + app.close() + + app = ws.WebSocketApp( + "wss://api-pub.bitfinex.com/ws/1", on_ping=on_ping, on_pong=on_pong + ) + app.run_forever( + ping_interval=2, ping_timeout=1, sslopt={"cert_reqs": ssl.CERT_NONE} + ) + + @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") + def test_opcode_close(self): + """Test WebSocketApp close opcode""" + + app = ws.WebSocketApp("wss://tsock.us1.twilio.com/v3/wsconnect") + app.run_forever(ping_interval=2, ping_timeout=1, ping_payload="Ping payload") + + # This is commented out because the URL no longer responds in the expected way + # @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") + # def testOpcodeBinary(self): + # """ Test WebSocketApp binary opcode + # """ + # app = ws.WebSocketApp('wss://streaming.vn.teslamotors.com/streaming/') + # app.run_forever(ping_interval=2, ping_timeout=1, ping_payload="Ping payload") + + @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") + def test_bad_ping_interval(self): + """A WebSocketApp handling of negative ping_interval""" + app = ws.WebSocketApp("wss://api-pub.bitfinex.com/ws/1") + self.assertRaises( + ws.WebSocketException, + app.run_forever, + ping_interval=-5, + sslopt={"cert_reqs": ssl.CERT_NONE}, + ) + + @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") + def test_bad_ping_timeout(self): + """A WebSocketApp handling of negative ping_timeout""" + app = ws.WebSocketApp("wss://api-pub.bitfinex.com/ws/1") + self.assertRaises( + ws.WebSocketException, + app.run_forever, + ping_timeout=-3, + sslopt={"cert_reqs": ssl.CERT_NONE}, + ) + + @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") + def test_close_status_code(self): + """Test extraction of close frame status code and close reason in WebSocketApp""" + + def on_close(wsapp, close_status_code, close_msg): + print("on_close reached") + + app = ws.WebSocketApp( + "wss://tsock.us1.twilio.com/v3/wsconnect", on_close=on_close + ) + closeframe = ws.ABNF( + opcode=ws.ABNF.OPCODE_CLOSE, data=b"\x03\xe8no-init-from-client" + ) + self.assertEqual([1000, "no-init-from-client"], app._get_close_args(closeframe)) + + closeframe = ws.ABNF(opcode=ws.ABNF.OPCODE_CLOSE, data=b"") + self.assertEqual([None, None], app._get_close_args(closeframe)) + + app2 = ws.WebSocketApp("wss://tsock.us1.twilio.com/v3/wsconnect") + closeframe = ws.ABNF(opcode=ws.ABNF.OPCODE_CLOSE, data=b"") + self.assertEqual([None, None], app2._get_close_args(closeframe)) + + self.assertRaises( + ws.WebSocketConnectionClosedException, + app.send, + data="test if connection is closed", + ) + + @unittest.skipUnless( + TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled" + ) + def test_callback_function_exception(self): + """Test callback function exception handling""" + + exc = None + passed_app = None + + def on_open(app): + raise RuntimeError("Callback failed") + + def on_error(app, err): + nonlocal passed_app + passed_app = app + nonlocal exc + exc = err + + def on_pong(app, _): + app.close() + + app = ws.WebSocketApp( + f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}", + on_open=on_open, + on_error=on_error, + on_pong=on_pong, + ) + app.run_forever(ping_interval=2, ping_timeout=1) + + self.assertEqual(passed_app, app) + self.assertIsInstance(exc, RuntimeError) + self.assertEqual(str(exc), "Callback failed") + + @unittest.skipUnless( + TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled" + ) + def test_callback_method_exception(self): + """Test callback method exception handling""" + + class Callbacks: + def __init__(self): + self.exc = None + self.passed_app = None + self.app = ws.WebSocketApp( + f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}", + on_open=self.on_open, + on_error=self.on_error, + on_pong=self.on_pong, + ) + self.app.run_forever(ping_interval=2, ping_timeout=1) + + def on_open(self, _): + raise RuntimeError("Callback failed") + + def on_error(self, app, err): + self.passed_app = app + self.exc = err + + def on_pong(self, app, _): + app.close() + + callbacks = Callbacks() + + self.assertEqual(callbacks.passed_app, callbacks.app) + self.assertIsInstance(callbacks.exc, RuntimeError) + self.assertEqual(str(callbacks.exc), "Callback failed") + + @unittest.skipUnless( + TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled" + ) + def test_reconnect(self): + """Test reconnect""" + pong_count = 0 + exc = None + + def on_error(_, err): + nonlocal exc + exc = err + + def on_pong(app, _): + nonlocal pong_count + pong_count += 1 + if pong_count == 1: + # First pong, shutdown socket, enforce read error + app.sock.shutdown() + if pong_count >= 2: + # Got second pong after reconnect + app.close() + + app = ws.WebSocketApp( + f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}", on_pong=on_pong, on_error=on_error + ) + app.run_forever(ping_interval=2, ping_timeout=1, reconnect=3) + + self.assertEqual(pong_count, 2) + self.assertIsInstance(exc, ws.WebSocketTimeoutException) + self.assertEqual(str(exc), "ping/pong timed out") + + def test_dispatcher_selection_default(self): + """Test default dispatcher selection""" + app = ws.WebSocketApp("ws://example.com") + + # Test default dispatcher (non-SSL) + dispatcher = app.create_dispatcher(ping_timeout=10, is_ssl=False) + self.assertIsInstance(dispatcher, ws._dispatcher.Dispatcher) + + def test_dispatcher_selection_ssl(self): + """Test SSL dispatcher selection""" + app = ws.WebSocketApp("wss://example.com") + + # Test SSL dispatcher + dispatcher = app.create_dispatcher(ping_timeout=10, is_ssl=True) + self.assertIsInstance(dispatcher, ws._dispatcher.SSLDispatcher) + + def test_dispatcher_selection_custom(self): + """Test custom dispatcher selection""" + from unittest.mock import Mock + + app = ws.WebSocketApp("ws://example.com") + custom_dispatcher = Mock() + handle_disconnect = Mock() + + # Test wrapped dispatcher with custom dispatcher + dispatcher = app.create_dispatcher( + ping_timeout=10, + dispatcher=custom_dispatcher, + handleDisconnect=handle_disconnect, + ) + self.assertIsInstance(dispatcher, ws._dispatcher.WrappedDispatcher) + self.assertEqual(dispatcher.dispatcher, custom_dispatcher) + self.assertEqual(dispatcher.handleDisconnect, handle_disconnect) + + def test_dispatcher_selection_no_ping_timeout(self): + """Test dispatcher selection without ping timeout""" + app = ws.WebSocketApp("ws://example.com") + + # Test with None ping_timeout (should default to 10) + dispatcher = app.create_dispatcher(ping_timeout=None, is_ssl=False) + self.assertIsInstance(dispatcher, ws._dispatcher.Dispatcher) + self.assertEqual(dispatcher.ping_timeout, 10) + + +if __name__ == "__main__": + unittest.main() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_cookiejar.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_cookiejar.py new file mode 100644 index 0000000000000000000000000000000000000000..7590f0caa73c9fd0e51d3793d76606302cd33a5a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_cookiejar.py @@ -0,0 +1,123 @@ +import unittest + +from websocket._cookiejar import SimpleCookieJar + +""" +test_cookiejar.py +websocket - WebSocket client library for Python + +Copyright 2025 engn33r + +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. +""" + + +class CookieJarTest(unittest.TestCase): + def test_add(self): + cookie_jar = SimpleCookieJar() + cookie_jar.add("") + self.assertFalse( + cookie_jar.jar, "Cookie with no domain should not be added to the jar" + ) + + cookie_jar = SimpleCookieJar() + cookie_jar.add("a=b") + self.assertFalse( + cookie_jar.jar, "Cookie with no domain should not be added to the jar" + ) + + cookie_jar = SimpleCookieJar() + cookie_jar.add("a=b; domain=.abc") + self.assertTrue(".abc" in cookie_jar.jar) + + cookie_jar = SimpleCookieJar() + cookie_jar.add("a=b; domain=abc") + self.assertTrue(".abc" in cookie_jar.jar) + self.assertTrue("abc" not in cookie_jar.jar) + + cookie_jar = SimpleCookieJar() + cookie_jar.add("a=b; c=d; domain=abc") + self.assertEqual(cookie_jar.get("abc"), "a=b; c=d") + self.assertEqual(cookie_jar.get(None), "") + + cookie_jar = SimpleCookieJar() + cookie_jar.add("a=b; c=d; domain=abc") + cookie_jar.add("e=f; domain=abc") + self.assertEqual(cookie_jar.get("abc"), "a=b; c=d; e=f") + + cookie_jar = SimpleCookieJar() + cookie_jar.add("a=b; c=d; domain=abc") + cookie_jar.add("e=f; domain=.abc") + self.assertEqual(cookie_jar.get("abc"), "a=b; c=d; e=f") + + cookie_jar = SimpleCookieJar() + cookie_jar.add("a=b; c=d; domain=abc") + cookie_jar.add("e=f; domain=xyz") + self.assertEqual(cookie_jar.get("abc"), "a=b; c=d") + self.assertEqual(cookie_jar.get("xyz"), "e=f") + self.assertEqual(cookie_jar.get("something"), "") + + def test_set(self): + cookie_jar = SimpleCookieJar() + cookie_jar.set("a=b") + self.assertFalse( + cookie_jar.jar, "Cookie with no domain should not be added to the jar" + ) + + cookie_jar = SimpleCookieJar() + cookie_jar.set("a=b; domain=.abc") + self.assertTrue(".abc" in cookie_jar.jar) + + cookie_jar = SimpleCookieJar() + cookie_jar.set("a=b; domain=abc") + self.assertTrue(".abc" in cookie_jar.jar) + self.assertTrue("abc" not in cookie_jar.jar) + + cookie_jar = SimpleCookieJar() + cookie_jar.set("a=b; c=d; domain=abc") + self.assertEqual(cookie_jar.get("abc"), "a=b; c=d") + + cookie_jar = SimpleCookieJar() + cookie_jar.set("a=b; c=d; domain=abc") + cookie_jar.set("e=f; domain=abc") + self.assertEqual(cookie_jar.get("abc"), "e=f") + + cookie_jar = SimpleCookieJar() + cookie_jar.set("a=b; c=d; domain=abc") + cookie_jar.set("e=f; domain=.abc") + self.assertEqual(cookie_jar.get("abc"), "e=f") + + cookie_jar = SimpleCookieJar() + cookie_jar.set("a=b; c=d; domain=abc") + cookie_jar.set("e=f; domain=xyz") + self.assertEqual(cookie_jar.get("abc"), "a=b; c=d") + self.assertEqual(cookie_jar.get("xyz"), "e=f") + self.assertEqual(cookie_jar.get("something"), "") + + def test_get(self): + cookie_jar = SimpleCookieJar() + cookie_jar.set("a=b; c=d; domain=abc.com") + self.assertEqual(cookie_jar.get("abc.com"), "a=b; c=d") + self.assertEqual(cookie_jar.get("x.abc.com"), "a=b; c=d") + self.assertEqual(cookie_jar.get("abc.com.es"), "") + self.assertEqual(cookie_jar.get("xabc.com"), "") + + cookie_jar.set("a=b; c=d; domain=.abc.com") + self.assertEqual(cookie_jar.get("abc.com"), "a=b; c=d") + self.assertEqual(cookie_jar.get("x.abc.com"), "a=b; c=d") + self.assertEqual(cookie_jar.get("abc.com.es"), "") + self.assertEqual(cookie_jar.get("xabc.com"), "") + + +if __name__ == "__main__": + unittest.main() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_dispatcher.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_dispatcher.py new file mode 100644 index 0000000000000000000000000000000000000000..457bed6cb46f09e670f74ab20673ff428200775b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_dispatcher.py @@ -0,0 +1,385 @@ +# -*- coding: utf-8 -*- +import socket +import unittest +from unittest.mock import Mock, patch, MagicMock +import threading +import time + +import websocket +from websocket._dispatcher import ( + Dispatcher, + DispatcherBase, + SSLDispatcher, + WrappedDispatcher, +) + +""" +test_dispatcher.py +websocket - WebSocket client library for Python + +Copyright 2025 engn33r + +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. +""" + +class MockApp: + """Mock WebSocketApp for testing""" + + def __init__(self): + self.keep_running = True + self.sock = Mock() + self.sock.sock = Mock() + + +class MockSocket: + """Mock socket for testing""" + + def __init__(self): + self.pending_return = False + + def pending(self): + return self.pending_return + + +class MockDispatcher: + """Mock external dispatcher for WrappedDispatcher testing""" + + def __init__(self): + self.signal_calls = [] + self.abort_calls = [] + self.read_calls = [] + self.buffwrite_calls = [] + self.timeout_calls = [] + + def signal(self, sig, handler): + self.signal_calls.append((sig, handler)) + + def abort(self): + self.abort_calls.append(True) + + def read(self, sock, callback): + self.read_calls.append((sock, callback)) + + def buffwrite(self, sock, data, send_func, disconnect_handler): + self.buffwrite_calls.append((sock, data, send_func, disconnect_handler)) + + def timeout(self, seconds, callback, *args): + self.timeout_calls.append((seconds, callback, args)) + + +class DispatcherTest(unittest.TestCase): + def setUp(self): + self.app = MockApp() + + def test_dispatcher_base_init(self): + """Test DispatcherBase initialization""" + dispatcher = DispatcherBase(self.app, 30.0) + + self.assertEqual(dispatcher.app, self.app) + self.assertEqual(dispatcher.ping_timeout, 30.0) + + def test_dispatcher_base_timeout(self): + """Test DispatcherBase timeout method""" + dispatcher = DispatcherBase(self.app, 30.0) + callback = Mock() + + # Test with seconds=None (should call callback immediately) + dispatcher.timeout(None, callback) + callback.assert_called_once() + + # Test with seconds > 0 (would sleep in real implementation) + callback.reset_mock() + start_time = time.time() + dispatcher.timeout(0.1, callback) + elapsed = time.time() - start_time + + callback.assert_called_once() + self.assertGreaterEqual(elapsed, 0.05) # Allow some tolerance + + def test_dispatcher_base_reconnect(self): + """Test DispatcherBase reconnect method""" + dispatcher = DispatcherBase(self.app, 30.0) + reconnector = Mock() + + # Test normal reconnect + dispatcher.reconnect(1, reconnector) + reconnector.assert_called_once_with(reconnecting=True) + + # Test reconnect with KeyboardInterrupt + reconnector.reset_mock() + reconnector.side_effect = KeyboardInterrupt("User interrupted") + + with self.assertRaises(KeyboardInterrupt): + dispatcher.reconnect(1, reconnector) + + def test_dispatcher_base_send(self): + """Test DispatcherBase send method""" + dispatcher = DispatcherBase(self.app, 30.0) + mock_sock = Mock() + test_data = b"test data" + + with patch("websocket._dispatcher.send") as mock_send: + mock_send.return_value = len(test_data) + result = dispatcher.send(mock_sock, test_data) + + mock_send.assert_called_once_with(mock_sock, test_data) + self.assertEqual(result, len(test_data)) + + def test_dispatcher_read(self): + """Test Dispatcher read method""" + dispatcher = Dispatcher(self.app, 5.0) + read_callback = Mock(return_value=True) + check_callback = Mock() + mock_sock = Mock() + + # Mock the selector to control the loop + with patch("selectors.DefaultSelector") as mock_selector_class: + mock_selector = Mock() + mock_selector_class.return_value = mock_selector + + # Make select return immediately (timeout) + mock_selector.select.return_value = [] + + # Stop after first iteration + def side_effect(*args): + self.app.keep_running = False + return [] + + mock_selector.select.side_effect = side_effect + + dispatcher.read(mock_sock, read_callback, check_callback) + + # Verify selector was used correctly + mock_selector.register.assert_called() + mock_selector.select.assert_called_with(5.0) + mock_selector.close.assert_called() + check_callback.assert_called() + + def test_dispatcher_read_with_data(self): + """Test Dispatcher read method when data is available""" + dispatcher = Dispatcher(self.app, 5.0) + read_callback = Mock(return_value=True) + check_callback = Mock() + mock_sock = Mock() + + with patch("selectors.DefaultSelector") as mock_selector_class: + mock_selector = Mock() + mock_selector_class.return_value = mock_selector + + # First call returns data, second call stops the loop + call_count = 0 + + def select_side_effect(*args): + nonlocal call_count + call_count += 1 + if call_count == 1: + return [True] # Data available + else: + self.app.keep_running = False + return [] + + mock_selector.select.side_effect = select_side_effect + + dispatcher.read(mock_sock, read_callback, check_callback) + + read_callback.assert_called() + check_callback.assert_called() + + def test_ssl_dispatcher_read(self): + """Test SSLDispatcher read method""" + dispatcher = SSLDispatcher(self.app, 5.0) + read_callback = Mock(return_value=True) + check_callback = Mock() + + # Mock socket with pending data + mock_ssl_sock = MockSocket() + self.app.sock.sock = mock_ssl_sock + + with patch("selectors.DefaultSelector") as mock_selector_class: + mock_selector = Mock() + mock_selector_class.return_value = mock_selector + mock_selector.select.return_value = [] + + # Stop after first iteration + def side_effect(*args): + self.app.keep_running = False + return [] + + mock_selector.select.side_effect = side_effect + + dispatcher.read(None, read_callback, check_callback) + + mock_selector.register.assert_called() + check_callback.assert_called() + + def test_ssl_dispatcher_select_with_pending(self): + """Test SSLDispatcher select method with pending data""" + dispatcher = SSLDispatcher(self.app, 5.0) + mock_ssl_sock = MockSocket() + mock_ssl_sock.pending_return = True + self.app.sock.sock = mock_ssl_sock + mock_selector = Mock() + + result = dispatcher.select(None, mock_selector) + + # When pending() returns True, should return [sock] + self.assertEqual(result, [mock_ssl_sock]) + + def test_ssl_dispatcher_select_without_pending(self): + """Test SSLDispatcher select method without pending data""" + dispatcher = SSLDispatcher(self.app, 5.0) + mock_ssl_sock = MockSocket() + mock_ssl_sock.pending_return = False + self.app.sock.sock = mock_ssl_sock + mock_selector = Mock() + mock_selector.select.return_value = [(mock_ssl_sock, None)] + + result = dispatcher.select(None, mock_selector) + + # Should return the first element of first result tuple + self.assertEqual(result, mock_ssl_sock) + mock_selector.select.assert_called_with(5.0) + + def test_ssl_dispatcher_select_no_results(self): + """Test SSLDispatcher select method with no results""" + dispatcher = SSLDispatcher(self.app, 5.0) + mock_ssl_sock = MockSocket() + mock_ssl_sock.pending_return = False + self.app.sock.sock = mock_ssl_sock + mock_selector = Mock() + mock_selector.select.return_value = [] + + result = dispatcher.select(None, mock_selector) + + # Should return None when no results (function doesn't return anything when len(r) == 0) + self.assertIsNone(result) + + def test_wrapped_dispatcher_init(self): + """Test WrappedDispatcher initialization""" + mock_dispatcher = MockDispatcher() + handle_disconnect = Mock() + + wrapped = WrappedDispatcher(self.app, 10.0, mock_dispatcher, handle_disconnect) + + self.assertEqual(wrapped.app, self.app) + self.assertEqual(wrapped.ping_timeout, 10.0) + self.assertEqual(wrapped.dispatcher, mock_dispatcher) + self.assertEqual(wrapped.handleDisconnect, handle_disconnect) + + # Should have set up signal handler + self.assertEqual(len(mock_dispatcher.signal_calls), 1) + sig, handler = mock_dispatcher.signal_calls[0] + self.assertEqual(sig, 2) # SIGINT + self.assertEqual(handler, mock_dispatcher.abort) + + def test_wrapped_dispatcher_read(self): + """Test WrappedDispatcher read method""" + mock_dispatcher = MockDispatcher() + handle_disconnect = Mock() + wrapped = WrappedDispatcher(self.app, 10.0, mock_dispatcher, handle_disconnect) + + mock_sock = Mock() + read_callback = Mock() + check_callback = Mock() + + wrapped.read(mock_sock, read_callback, check_callback) + + # Should delegate to wrapped dispatcher + self.assertEqual(len(mock_dispatcher.read_calls), 1) + self.assertEqual(mock_dispatcher.read_calls[0], (mock_sock, read_callback)) + + # Should call timeout for ping_timeout + self.assertEqual(len(mock_dispatcher.timeout_calls), 1) + timeout_call = mock_dispatcher.timeout_calls[0] + self.assertEqual(timeout_call[0], 10.0) # timeout seconds + self.assertEqual(timeout_call[1], check_callback) # callback + + def test_wrapped_dispatcher_read_no_ping_timeout(self): + """Test WrappedDispatcher read method without ping timeout""" + mock_dispatcher = MockDispatcher() + handle_disconnect = Mock() + wrapped = WrappedDispatcher(self.app, None, mock_dispatcher, handle_disconnect) + + mock_sock = Mock() + read_callback = Mock() + check_callback = Mock() + + wrapped.read(mock_sock, read_callback, check_callback) + + # Should delegate to wrapped dispatcher + self.assertEqual(len(mock_dispatcher.read_calls), 1) + + # Should NOT call timeout when ping_timeout is None + self.assertEqual(len(mock_dispatcher.timeout_calls), 0) + + def test_wrapped_dispatcher_send(self): + """Test WrappedDispatcher send method""" + mock_dispatcher = MockDispatcher() + handle_disconnect = Mock() + wrapped = WrappedDispatcher(self.app, 10.0, mock_dispatcher, handle_disconnect) + + mock_sock = Mock() + test_data = b"test data" + + with patch("websocket._dispatcher.send") as mock_send: + result = wrapped.send(mock_sock, test_data) + + # Should delegate to dispatcher.buffwrite + self.assertEqual(len(mock_dispatcher.buffwrite_calls), 1) + call = mock_dispatcher.buffwrite_calls[0] + self.assertEqual(call[0], mock_sock) + self.assertEqual(call[1], test_data) + self.assertEqual(call[2], mock_send) + self.assertEqual(call[3], handle_disconnect) + + # Should return data length + self.assertEqual(result, len(test_data)) + + def test_wrapped_dispatcher_timeout(self): + """Test WrappedDispatcher timeout method""" + mock_dispatcher = MockDispatcher() + handle_disconnect = Mock() + wrapped = WrappedDispatcher(self.app, 10.0, mock_dispatcher, handle_disconnect) + + callback = Mock() + args = ("arg1", "arg2") + + wrapped.timeout(5.0, callback, *args) + + # Should delegate to wrapped dispatcher + self.assertEqual(len(mock_dispatcher.timeout_calls), 1) + call = mock_dispatcher.timeout_calls[0] + self.assertEqual(call[0], 5.0) + self.assertEqual(call[1], callback) + self.assertEqual(call[2], args) + + def test_wrapped_dispatcher_reconnect(self): + """Test WrappedDispatcher reconnect method""" + mock_dispatcher = MockDispatcher() + handle_disconnect = Mock() + wrapped = WrappedDispatcher(self.app, 10.0, mock_dispatcher, handle_disconnect) + + reconnector = Mock() + + wrapped.reconnect(3, reconnector) + + # Should delegate to timeout method with reconnect=True + self.assertEqual(len(mock_dispatcher.timeout_calls), 1) + call = mock_dispatcher.timeout_calls[0] + self.assertEqual(call[0], 3) + self.assertEqual(call[1], reconnector) + self.assertEqual(call[2], (True,)) + + +if __name__ == "__main__": + unittest.main() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_handshake_large_response.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_handshake_large_response.py new file mode 100644 index 0000000000000000000000000000000000000000..3ca415a09bb0e456cee9983bf67f2c8162c86457 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_handshake_large_response.py @@ -0,0 +1,158 @@ +# -*- coding: utf-8 -*- +import unittest +from unittest.mock import Mock, patch + +from websocket._handshake import _get_resp_headers +from websocket._exceptions import WebSocketBadStatusException +from websocket._ssl_compat import SSLError + +""" +test_handshake_large_response.py +websocket - WebSocket client library for Python + +Copyright 2025 engn33r + +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. +""" + +class HandshakeLargeResponseTest(unittest.TestCase): + def test_large_error_response_chunked_reading(self): + """Test that large HTTP error responses during handshake are read in chunks""" + + # Mock socket + mock_sock = Mock() + + # Create a large error response body (> 16KB) + large_response = b"Error details: " + b"A" * 20000 # 20KB+ response + + # Track recv calls to ensure chunking + recv_calls = [] + + def mock_recv(sock, bufsize): + recv_calls.append(bufsize) + # Simulate SSL error if trying to read > 16KB at once + if bufsize > 16384: + raise SSLError("[SSL: BAD_LENGTH] unknown error") + return large_response[:bufsize] + + # Mock read_headers to return error status with large content-length + with patch("websocket._handshake.read_headers") as mock_read_headers: + mock_read_headers.return_value = ( + 400, # Bad request status + {"content-length": str(len(large_response))}, + "Bad Request", + ) + + # Mock the recv function to track calls + with patch("websocket._socket.recv", side_effect=mock_recv): + # This should not raise SSLError, but should raise WebSocketBadStatusException + with self.assertRaises(WebSocketBadStatusException) as cm: + _get_resp_headers(mock_sock) + + # Verify the response body was included in the exception + self.assertIn( + b"Error details:", + ( + cm.exception.args[0].encode() + if isinstance(cm.exception.args[0], str) + else cm.exception.args[0] + ), + ) + + # Verify chunked reading was used (multiple recv calls, none > 16KB) + self.assertGreater(len(recv_calls), 1) + self.assertTrue(all(call <= 16384 for call in recv_calls)) + + def test_handshake_ssl_large_response_protection(self): + """Test that the fix prevents SSL BAD_LENGTH errors during handshake""" + + mock_sock = Mock() + + # Large content that would trigger SSL error if read all at once + large_content = b"X" * 32768 # 32KB + + chunks_returned = 0 + + def mock_recv_chunked(sock, bufsize): + nonlocal chunks_returned + # Return data in chunks, simulating successful chunked reading + chunk_start = chunks_returned * 16384 + chunk_end = min(chunk_start + bufsize, len(large_content)) + result = large_content[chunk_start:chunk_end] + chunks_returned += 1 if result else 0 + return result + + with patch("websocket._handshake.read_headers") as mock_read_headers: + mock_read_headers.return_value = ( + 500, # Server error + {"content-length": str(len(large_content))}, + "Internal Server Error", + ) + + with patch("websocket._socket.recv", side_effect=mock_recv_chunked): + # Should handle large response without SSL errors + with self.assertRaises(WebSocketBadStatusException) as cm: + _get_resp_headers(mock_sock) + + # Verify the complete response was captured + exception_str = str(cm.exception) + # Response body should be in the exception message + self.assertIn("XXXXX", exception_str) # Part of the large content + + def test_handshake_normal_small_response(self): + """Test that normal small responses still work correctly""" + + mock_sock = Mock() + small_response = b"Small error message" + + def mock_recv(sock, bufsize): + return small_response + + with patch("websocket._handshake.read_headers") as mock_read_headers: + mock_read_headers.return_value = ( + 404, # Not found + {"content-length": str(len(small_response))}, + "Not Found", + ) + + with patch("websocket._socket.recv", side_effect=mock_recv): + with self.assertRaises(WebSocketBadStatusException) as cm: + _get_resp_headers(mock_sock) + + # Verify small response is handled correctly + self.assertIn("Small error message", str(cm.exception)) + + def test_handshake_no_content_length(self): + """Test handshake error response without content-length header""" + + mock_sock = Mock() + + with patch("websocket._handshake.read_headers") as mock_read_headers: + mock_read_headers.return_value = ( + 403, # Forbidden + {}, # No content-length header + "Forbidden", + ) + + # Should raise exception without trying to read response body + with self.assertRaises(WebSocketBadStatusException) as cm: + _get_resp_headers(mock_sock) + + # Should mention status but not have response body + exception_str = str(cm.exception) + self.assertIn("403", exception_str) + self.assertIn("Forbidden", exception_str) + + +if __name__ == "__main__": + unittest.main() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_http.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_http.py new file mode 100644 index 0000000000000000000000000000000000000000..99f9155341174cd6282592b64fd0400b848e4fd8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_http.py @@ -0,0 +1,370 @@ +# -*- coding: utf-8 -*- +# +import os +import os.path +import socket +import ssl +import unittest + +import websocket +from websocket._exceptions import WebSocketProxyException, WebSocketException +from websocket._http import ( + _get_addrinfo_list, + _start_proxied_socket, + _tunnel, + connect, + proxy_info, + read_headers, + HAVE_PYTHON_SOCKS, +) + +""" +test_http.py +websocket - WebSocket client library for Python + +Copyright 2025 engn33r + +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. +""" + +try: + from python_socks._errors import ProxyConnectionError, ProxyError, ProxyTimeoutError +except: + from websocket._http import ProxyConnectionError, ProxyError, ProxyTimeoutError + +# Skip test to access the internet unless TEST_WITH_INTERNET == 1 +TEST_WITH_INTERNET = os.environ.get("TEST_WITH_INTERNET", "0") == "1" +TEST_WITH_PROXY = os.environ.get("TEST_WITH_PROXY", "0") == "1" +# Skip tests relying on local websockets server unless LOCAL_WS_SERVER_PORT != -1 +LOCAL_WS_SERVER_PORT = os.environ.get("LOCAL_WS_SERVER_PORT", "-1") +TEST_WITH_LOCAL_SERVER = LOCAL_WS_SERVER_PORT != "-1" + + +class SockMock: + def __init__(self): + self.data = [] + self.sent = [] + + def add_packet(self, data): + self.data.append(data) + + def gettimeout(self): + return None + + def recv(self, bufsize): + if self.data: + e = self.data.pop(0) + if isinstance(e, Exception): + raise e + if len(e) > bufsize: + self.data.insert(0, e[bufsize:]) + return e[:bufsize] + + def send(self, data): + self.sent.append(data) + return len(data) + + def close(self): + pass + + +class HeaderSockMock(SockMock): + def __init__(self, fname): + SockMock.__init__(self) + path = os.path.join(os.path.dirname(__file__), fname) + with open(path, "rb") as f: + self.add_packet(f.read()) + + +class OptsList: + def __init__(self): + self.timeout = 1 + self.sockopt = [] + self.sslopt = {"cert_reqs": ssl.CERT_NONE} + + +class HttpTest(unittest.TestCase): + def test_read_header(self): + status, header, _ = read_headers(HeaderSockMock("data/header01.txt")) + self.assertEqual(status, 101) + self.assertEqual(header["connection"], "Upgrade") + # header02.txt is intentionally malformed + self.assertRaises( + WebSocketException, read_headers, HeaderSockMock("data/header02.txt") + ) + + def test_tunnel(self): + self.assertRaises( + WebSocketProxyException, + _tunnel, + HeaderSockMock("data/header01.txt"), + "example.com", + 80, + ("username", "password"), + ) + self.assertRaises( + WebSocketProxyException, + _tunnel, + HeaderSockMock("data/header02.txt"), + "example.com", + 80, + ("username", "password"), + ) + + @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") + def test_connect(self): + # Not currently testing an actual proxy connection, so just check whether proxy errors are raised. This requires internet for a DNS lookup + if HAVE_PYTHON_SOCKS: + # Need this check, otherwise case where python_socks is not installed triggers + # websocket._exceptions.WebSocketException: Python Socks is needed for SOCKS proxying but is not available + self.assertRaises( + (ProxyTimeoutError, OSError), + _start_proxied_socket, + "wss://example.com", + OptsList(), + proxy_info( + http_proxy_host="example.com", + http_proxy_port="8080", + proxy_type="socks4", + http_proxy_timeout=1, + ), + ) + self.assertRaises( + (ProxyTimeoutError, OSError), + _start_proxied_socket, + "wss://example.com", + OptsList(), + proxy_info( + http_proxy_host="example.com", + http_proxy_port="8080", + proxy_type="socks4a", + http_proxy_timeout=1, + ), + ) + self.assertRaises( + (ProxyTimeoutError, OSError), + _start_proxied_socket, + "wss://example.com", + OptsList(), + proxy_info( + http_proxy_host="example.com", + http_proxy_port="8080", + proxy_type="socks5", + http_proxy_timeout=1, + ), + ) + self.assertRaises( + (ProxyTimeoutError, OSError), + _start_proxied_socket, + "wss://example.com", + OptsList(), + proxy_info( + http_proxy_host="example.com", + http_proxy_port="8080", + proxy_type="socks5h", + http_proxy_timeout=1, + ), + ) + self.assertRaises( + ProxyConnectionError, + connect, + "wss://example.com", + OptsList(), + proxy_info( + http_proxy_host="127.0.0.1", + http_proxy_port=9999, + proxy_type="socks4", + http_proxy_timeout=1, + ), + None, + ) + + self.assertRaises( + TypeError, + _get_addrinfo_list, + None, + 80, + True, + proxy_info( + http_proxy_host="127.0.0.1", http_proxy_port="9999", proxy_type="http" + ), + ) + self.assertRaises( + TypeError, + _get_addrinfo_list, + None, + 80, + True, + proxy_info( + http_proxy_host="127.0.0.1", http_proxy_port="9999", proxy_type="http" + ), + ) + self.assertRaises( + socket.timeout, + connect, + "wss://google.com", + OptsList(), + proxy_info( + http_proxy_host="8.8.8.8", + http_proxy_port=9999, + proxy_type="http", + http_proxy_timeout=1, + ), + None, + ) + self.assertEqual( + connect( + "wss://google.com", + OptsList(), + proxy_info( + http_proxy_host="8.8.8.8", http_proxy_port=8080, proxy_type="http" + ), + True, + ), + (True, ("google.com", 443, "/")), + ) + # The following test fails on Mac OS with a gaierror, not an OverflowError + # self.assertRaises(OverflowError, connect, "wss://example.com", OptsList(), proxy_info(http_proxy_host="127.0.0.1", http_proxy_port=99999, proxy_type="socks4", timeout=2), False) + + @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") + @unittest.skipUnless( + TEST_WITH_PROXY, "This test requires a HTTP proxy to be running on port 8899" + ) + @unittest.skipUnless( + TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled" + ) + def test_proxy_connect(self): + ws = websocket.WebSocket() + ws.connect( + f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}", + http_proxy_host="127.0.0.1", + http_proxy_port="8899", + proxy_type="http", + ) + ws.send("Hello, Server") + server_response = ws.recv() + self.assertEqual(server_response, "Hello, Server") + # self.assertEqual(_start_proxied_socket("wss://api.bitfinex.com/ws/2", OptsList(), proxy_info(http_proxy_host="127.0.0.1", http_proxy_port="8899", proxy_type="http"))[1], ("api.bitfinex.com", 443, '/ws/2')) + self.assertEqual( + _get_addrinfo_list( + "api.bitfinex.com", + 443, + True, + proxy_info( + http_proxy_host="127.0.0.1", + http_proxy_port="8899", + proxy_type="http", + ), + ), + ( + socket.getaddrinfo( + "127.0.0.1", 8899, 0, socket.SOCK_STREAM, socket.SOL_TCP + ), + True, + None, + ), + ) + self.assertEqual( + connect( + "wss://api.bitfinex.com/ws/2", + OptsList(), + proxy_info( + http_proxy_host="127.0.0.1", http_proxy_port=8899, proxy_type="http" + ), + None, + )[1], + ("api.bitfinex.com", 443, "/ws/2"), + ) + # TODO: Test SOCKS4 and SOCK5 proxies with unit tests + + @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") + def test_sslopt(self): + ssloptions = { + "check_hostname": False, + "server_hostname": "ServerName", + "ssl_version": ssl.PROTOCOL_TLS_CLIENT, + "ciphers": "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:\ + TLS_AES_128_GCM_SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:\ + ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:\ + ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:\ + DHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:\ + ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-GCM-SHA256:\ + ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:\ + DHE-RSA-AES256-SHA256:ECDHE-ECDSA-AES128-SHA256:\ + ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:\ + ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA", + "ecdh_curve": "prime256v1", + } + ws_ssl1 = websocket.WebSocket(sslopt=ssloptions) + ws_ssl1.connect("wss://api.bitfinex.com/ws/2") + ws_ssl1.send("Hello") + ws_ssl1.close() + + ws_ssl2 = websocket.WebSocket(sslopt={"check_hostname": True}) + ws_ssl2.connect("wss://api.bitfinex.com/ws/2") + ws_ssl2.close + + def test_proxy_info(self): + self.assertEqual( + proxy_info( + http_proxy_host="127.0.0.1", http_proxy_port="8080", proxy_type="http" + ).proxy_protocol, + "http", + ) + self.assertRaises( + ProxyError, + proxy_info, + http_proxy_host="127.0.0.1", + http_proxy_port="8080", + proxy_type="badval", + ) + self.assertEqual( + proxy_info( + http_proxy_host="example.com", http_proxy_port="8080", proxy_type="http" + ).proxy_host, + "example.com", + ) + self.assertEqual( + proxy_info( + http_proxy_host="127.0.0.1", http_proxy_port="8080", proxy_type="http" + ).proxy_port, + "8080", + ) + self.assertEqual( + proxy_info( + http_proxy_host="127.0.0.1", http_proxy_port="8080", proxy_type="http" + ).auth, + None, + ) + self.assertEqual( + proxy_info( + http_proxy_host="127.0.0.1", + http_proxy_port="8080", + proxy_type="http", + http_proxy_auth=("my_username123", "my_pass321"), + ).auth[0], + "my_username123", + ) + self.assertEqual( + proxy_info( + http_proxy_host="127.0.0.1", + http_proxy_port="8080", + proxy_type="http", + http_proxy_auth=("my_username123", "my_pass321"), + ).auth[1], + "my_pass321", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_large_payloads.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_large_payloads.py new file mode 100644 index 0000000000000000000000000000000000000000..4d69c635f111bd0436e7bc4b3368e82990dcd9e0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_large_payloads.py @@ -0,0 +1,273 @@ +# -*- coding: utf-8 -*- +import unittest +import struct +from unittest.mock import Mock, patch, MagicMock + +from websocket._abnf import ABNF +from websocket._core import WebSocket +from websocket._exceptions import WebSocketProtocolException, WebSocketPayloadException +from websocket._ssl_compat import SSLError + +""" +test_large_payloads.py +websocket - WebSocket client library for Python + +Copyright 2025 engn33r + +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. +""" + +class LargePayloadTest(unittest.TestCase): + def test_frame_length_encoding_boundaries(self): + """Test WebSocket frame length encoding at various boundaries""" + + # Test length encoding boundaries as per RFC 6455 + test_cases = [ + (125, "Single byte length"), # Max for 7-bit length + (126, "Two byte length start"), # Start of 16-bit length + (127, "Two byte length"), + (65535, "Two byte length max"), # Max for 16-bit length + (65536, "Eight byte length start"), # Start of 64-bit length + (16384, "16KB boundary"), # The problematic size + (16385, "Just over 16KB"), + (32768, "32KB"), + (131072, "128KB"), + ] + + for length, description in test_cases: + with self.subTest(length=length, description=description): + # Create payload of specified length + payload = b"A" * length + + # Create frame + frame = ABNF.create_frame(payload, ABNF.OPCODE_BINARY) + + # Verify frame can be formatted without error + formatted = frame.format() + + # Verify the frame header is correctly structured + self.assertIsInstance(formatted, bytes) + self.assertTrue(len(formatted) >= length) # Header + payload + + # Verify payload length is preserved + self.assertEqual(len(frame.data), length) + + def test_recv_large_payload_chunked(self): + """Test receiving large payloads in chunks (simulating the 16KB recv issue)""" + + # Create a large payload that would trigger chunked reading + large_payload = b"B" * 32768 # 32KB + + # Mock recv function that returns data in 16KB chunks + chunks = [] + chunk_size = 16384 + for i in range(0, len(large_payload), chunk_size): + chunks.append(large_payload[i : i + chunk_size]) + + call_count = 0 + + def mock_recv(bufsize): + nonlocal call_count + if call_count >= len(chunks): + return b"" + result = chunks[call_count] + call_count += 1 + return result + + # Test the frame buffer's recv_strict method + from websocket._abnf import frame_buffer + + fb = frame_buffer(mock_recv, skip_utf8_validation=True) + + # This should handle large payloads by chunking + result = fb.recv_strict(len(large_payload)) + + self.assertEqual(result, large_payload) + # Verify multiple recv calls were made + self.assertGreater(call_count, 1) + + def test_ssl_large_payload_simulation(self): + """Simulate SSL BAD_LENGTH error scenario""" + + # This test demonstrates that the 16KB limit in frame buffer protects against SSL issues + payload_size = 16385 + + recv_calls = [] + + def mock_recv_with_ssl_limit(bufsize): + recv_calls.append(bufsize) + # This simulates the SSL issue: BAD_LENGTH when trying to recv > 16KB + if bufsize > 16384: + raise SSLError("[SSL: BAD_LENGTH] unknown error") + return b"C" * min(bufsize, 16384) + + from websocket._abnf import frame_buffer + + fb = frame_buffer(mock_recv_with_ssl_limit, skip_utf8_validation=True) + + # The frame buffer handles this correctly by chunking recv calls + result = fb.recv_strict(payload_size) + + # Verify it worked and chunked the calls properly + self.assertEqual(len(result), payload_size) + # Verify no single recv call was > 16KB + self.assertTrue(all(call <= 16384 for call in recv_calls)) + # Verify multiple calls were made + self.assertGreater(len(recv_calls), 1) + + def test_frame_format_large_payloads(self): + """Test frame formatting with various large payload sizes""" + + # Test sizes around potential problem areas + test_sizes = [16383, 16384, 16385, 32768, 65535, 65536] + + for size in test_sizes: + with self.subTest(size=size): + payload = b"D" * size + frame = ABNF.create_frame(payload, ABNF.OPCODE_BINARY) + + # Should not raise any exceptions + formatted = frame.format() + + # Verify structure + self.assertIsInstance(formatted, bytes) + self.assertEqual(len(frame.data), size) + + # Verify length encoding is correct based on size + # Note: frames from create_frame() include masking by default (4 extra bytes) + mask_size = 4 # WebSocket frames are masked by default + if size < ABNF.LENGTH_7: # < 126 + # Length should be encoded in single byte + expected_header_size = ( + 2 + mask_size + ) # 1 byte opcode + 1 byte length + 4 byte mask + elif size < ABNF.LENGTH_16: # < 65536 + # Length should be encoded in 2 bytes + expected_header_size = ( + 4 + mask_size + ) # 1 byte opcode + 1 byte marker + 2 bytes length + 4 byte mask + else: + # Length should be encoded in 8 bytes + expected_header_size = ( + 10 + mask_size + ) # 1 byte opcode + 1 byte marker + 8 bytes length + 4 byte mask + + self.assertEqual(len(formatted), expected_header_size + size) + + def test_send_large_payload_chunking(self): + """Test that large payloads are sent in chunks to avoid SSL issues""" + + mock_sock = Mock() + + # Track how data is sent + sent_chunks = [] + + def mock_send(data): + sent_chunks.append(len(data)) + return len(data) + + mock_sock.send = mock_send + mock_sock.gettimeout.return_value = 30.0 + + # Create WebSocket with mocked socket + ws = WebSocket() + ws.sock = mock_sock + ws.connected = True + + # Create large payload + large_payload = b"E" * 32768 # 32KB + + # Send the payload + with patch("websocket._core.send") as mock_send_func: + mock_send_func.side_effect = lambda sock, data: len(data) + + # This should work without SSL errors + result = ws.send_binary(large_payload) + + # Verify payload was accepted + self.assertGreater(result, 0) + + def test_utf8_validation_large_text(self): + """Test UTF-8 validation with large text payloads""" + + # Create large valid UTF-8 text + large_text = "Hello 世界! " * 2000 # About 26KB with Unicode + + # Test frame creation + frame = ABNF.create_frame(large_text, ABNF.OPCODE_TEXT) + + # Should not raise validation errors + formatted = frame.format() + self.assertIsInstance(formatted, bytes) + + # Test with close frame that has invalid UTF-8 (this is what validate() actually checks) + invalid_utf8_close_data = struct.pack("!H", 1000) + b"\xff\xfe invalid utf8" + + # Create close frame with invalid UTF-8 data + frame = ABNF(1, 0, 0, 0, ABNF.OPCODE_CLOSE, 1, invalid_utf8_close_data) + + # Validation should catch the invalid UTF-8 in close frame reason + with self.assertRaises(WebSocketProtocolException): + frame.validate(skip_utf8_validation=False) + + def test_frame_buffer_edge_cases(self): + """Test frame buffer with edge cases that could trigger bugs""" + + # Test scenario: exactly 16KB payload split across recv calls + payload_16k = b"F" * 16384 + + # Simulate receiving in smaller chunks + chunks = [payload_16k[i : i + 4096] for i in range(0, len(payload_16k), 4096)] + + call_count = 0 + + def mock_recv(bufsize): + nonlocal call_count + if call_count >= len(chunks): + return b"" + result = chunks[call_count] + call_count += 1 + return result + + from websocket._abnf import frame_buffer + + fb = frame_buffer(mock_recv, skip_utf8_validation=True) + result = fb.recv_strict(16384) + + self.assertEqual(result, payload_16k) + # Verify multiple recv calls were made + self.assertEqual(call_count, 4) # 16KB / 4KB = 4 chunks + + def test_max_frame_size_limits(self): + """Test behavior at WebSocket maximum frame size limits""" + + # Test just under the maximum theoretical frame size + # (This is a very large test, so we'll use a smaller representative size) + + # Test with a reasonably large payload that represents the issue + large_size = 1024 * 1024 # 1MB + payload = b"G" * large_size + + # This should work without issues + frame = ABNF.create_frame(payload, ABNF.OPCODE_BINARY) + + # Verify the frame can be formatted + formatted = frame.format() + self.assertIsInstance(formatted, bytes) + + # Verify payload is preserved + self.assertEqual(len(frame.data), large_size) + + +if __name__ == "__main__": + unittest.main() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_socket.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_socket.py new file mode 100644 index 0000000000000000000000000000000000000000..5b8b65bd6b5b62aa10ec5d38d34f981e4350b3d0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_socket.py @@ -0,0 +1,357 @@ +# -*- coding: utf-8 -*- +import errno +import socket +import unittest +from unittest.mock import Mock, patch, MagicMock +import time + +from websocket._socket import recv, recv_line, send, DEFAULT_SOCKET_OPTION +from websocket._ssl_compat import ( + SSLError, + SSLEOFError, + SSLWantWriteError, + SSLWantReadError, +) +from websocket._exceptions import ( + WebSocketTimeoutException, + WebSocketConnectionClosedException, +) + +""" +test_socket.py +websocket - WebSocket client library for Python + +Copyright 2025 engn33r + +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. +""" + +class SocketTest(unittest.TestCase): + def test_default_socket_option(self): + """Test DEFAULT_SOCKET_OPTION contains expected options""" + self.assertIsInstance(DEFAULT_SOCKET_OPTION, list) + self.assertGreater(len(DEFAULT_SOCKET_OPTION), 0) + + # Should contain TCP_NODELAY option + tcp_nodelay_found = any( + opt[1] == socket.TCP_NODELAY for opt in DEFAULT_SOCKET_OPTION + ) + self.assertTrue(tcp_nodelay_found) + + def test_recv_normal(self): + """Test normal recv operation""" + mock_sock = Mock() + mock_sock.recv.return_value = b"test data" + + result = recv(mock_sock, 9) + + self.assertEqual(result, b"test data") + mock_sock.recv.assert_called_once_with(9) + + def test_recv_timeout_error(self): + """Test recv with TimeoutError""" + mock_sock = Mock() + mock_sock.recv.side_effect = TimeoutError("Connection timed out") + + with self.assertRaises(WebSocketTimeoutException) as cm: + recv(mock_sock, 9) + + self.assertEqual(str(cm.exception), "Connection timed out") + + def test_recv_socket_timeout(self): + """Test recv with socket.timeout""" + mock_sock = Mock() + timeout_exc = socket.timeout("Socket timed out") + timeout_exc.args = ("Socket timed out",) + mock_sock.recv.side_effect = timeout_exc + mock_sock.gettimeout.return_value = 30.0 + + with self.assertRaises(WebSocketTimeoutException) as cm: + recv(mock_sock, 9) + + # In Python 3.10+, socket.timeout is a subclass of TimeoutError + # so it's caught by the TimeoutError handler with hardcoded message + # In Python 3.9, socket.timeout is caught by socket.timeout handler + # which preserves the original message + import sys + + if sys.version_info >= (3, 10): + self.assertEqual(str(cm.exception), "Connection timed out") + else: + self.assertEqual(str(cm.exception), "Socket timed out") + + def test_recv_ssl_timeout(self): + """Test recv with SSL timeout error""" + mock_sock = Mock() + ssl_exc = SSLError("The operation timed out") + ssl_exc.args = ("The operation timed out",) + mock_sock.recv.side_effect = ssl_exc + + with self.assertRaises(WebSocketTimeoutException) as cm: + recv(mock_sock, 9) + + self.assertEqual(str(cm.exception), "The operation timed out") + + def test_recv_ssl_non_timeout_error(self): + """Test recv with SSL non-timeout error""" + mock_sock = Mock() + ssl_exc = SSLError("SSL certificate error") + ssl_exc.args = ("SSL certificate error",) + mock_sock.recv.side_effect = ssl_exc + + # Should re-raise the original SSL error + with self.assertRaises(SSLError): + recv(mock_sock, 9) + + def test_recv_empty_response(self): + """Test recv with empty response (connection closed)""" + mock_sock = Mock() + mock_sock.recv.return_value = b"" + + with self.assertRaises(WebSocketConnectionClosedException) as cm: + recv(mock_sock, 9) + + self.assertEqual(str(cm.exception), "Connection to remote host was lost.") + + def test_recv_ssl_want_read_error(self): + """Test recv with SSLWantReadError (should retry)""" + mock_sock = Mock() + + # First call raises SSLWantReadError, second call succeeds + mock_sock.recv.side_effect = [SSLWantReadError(), b"data after retry"] + + with patch("selectors.DefaultSelector") as mock_selector_class: + mock_selector = Mock() + mock_selector_class.return_value = mock_selector + mock_selector.select.return_value = [True] # Ready to read + + result = recv(mock_sock, 100) + + self.assertEqual(result, b"data after retry") + mock_selector.register.assert_called() + mock_selector.close.assert_called() + + def test_recv_ssl_want_read_timeout(self): + """Test recv with SSLWantReadError that times out""" + mock_sock = Mock() + mock_sock.recv.side_effect = SSLWantReadError() + mock_sock.gettimeout.return_value = 1.0 + + with patch("selectors.DefaultSelector") as mock_selector_class: + mock_selector = Mock() + mock_selector_class.return_value = mock_selector + mock_selector.select.return_value = [] # Timeout + + with self.assertRaises(WebSocketTimeoutException): + recv(mock_sock, 100) + + def test_recv_line(self): + """Test recv_line functionality""" + mock_sock = Mock() + + # Mock recv to return one character at a time + recv_calls = [b"H", b"e", b"l", b"l", b"o", b"\n"] + + with patch("websocket._socket.recv", side_effect=recv_calls) as mock_recv: + result = recv_line(mock_sock) + + self.assertEqual(result, b"Hello\n") + self.assertEqual(mock_recv.call_count, 6) + + def test_send_normal(self): + """Test normal send operation""" + mock_sock = Mock() + mock_sock.send.return_value = 9 + mock_sock.gettimeout.return_value = 30.0 + + result = send(mock_sock, b"test data") + + self.assertEqual(result, 9) + mock_sock.send.assert_called_with(b"test data") + + def test_send_zero_timeout(self): + """Test send with zero timeout (non-blocking)""" + mock_sock = Mock() + mock_sock.send.return_value = 9 + mock_sock.gettimeout.return_value = 0 + + result = send(mock_sock, b"test data") + + self.assertEqual(result, 9) + mock_sock.send.assert_called_once_with(b"test data") + + def test_send_ssl_eof_error(self): + """Test send with SSLEOFError""" + mock_sock = Mock() + mock_sock.gettimeout.return_value = 30.0 + mock_sock.send.side_effect = SSLEOFError("Connection closed") + + with self.assertRaises(WebSocketConnectionClosedException) as cm: + send(mock_sock, b"test data") + + self.assertEqual(str(cm.exception), "socket is already closed.") + + def test_send_ssl_want_write_error(self): + """Test send with SSLWantWriteError (should retry)""" + mock_sock = Mock() + mock_sock.gettimeout.return_value = 30.0 + + # First call raises SSLWantWriteError, second call succeeds + mock_sock.send.side_effect = [SSLWantWriteError(), 9] + + with patch("selectors.DefaultSelector") as mock_selector_class: + mock_selector = Mock() + mock_selector_class.return_value = mock_selector + mock_selector.select.return_value = [True] # Ready to write + + result = send(mock_sock, b"test data") + + self.assertEqual(result, 9) + mock_selector.register.assert_called() + mock_selector.close.assert_called() + + def test_send_socket_eagain_error(self): + """Test send with EAGAIN error (should retry)""" + mock_sock = Mock() + mock_sock.gettimeout.return_value = 30.0 + + # Create socket error with EAGAIN + eagain_error = socket.error("Resource temporarily unavailable") + eagain_error.errno = errno.EAGAIN + eagain_error.args = (errno.EAGAIN, "Resource temporarily unavailable") + + # First call raises EAGAIN, second call succeeds + mock_sock.send.side_effect = [eagain_error, 9] + + with patch("selectors.DefaultSelector") as mock_selector_class: + mock_selector = Mock() + mock_selector_class.return_value = mock_selector + mock_selector.select.return_value = [True] # Ready to write + + result = send(mock_sock, b"test data") + + self.assertEqual(result, 9) + + def test_send_socket_ewouldblock_error(self): + """Test send with EWOULDBLOCK error (should retry)""" + mock_sock = Mock() + mock_sock.gettimeout.return_value = 30.0 + + # Create socket error with EWOULDBLOCK + ewouldblock_error = socket.error("Operation would block") + ewouldblock_error.errno = errno.EWOULDBLOCK + ewouldblock_error.args = (errno.EWOULDBLOCK, "Operation would block") + + # First call raises EWOULDBLOCK, second call succeeds + mock_sock.send.side_effect = [ewouldblock_error, 9] + + with patch("selectors.DefaultSelector") as mock_selector_class: + mock_selector = Mock() + mock_selector_class.return_value = mock_selector + mock_selector.select.return_value = [True] # Ready to write + + result = send(mock_sock, b"test data") + + self.assertEqual(result, 9) + + def test_send_socket_other_error(self): + """Test send with other socket error (should raise)""" + mock_sock = Mock() + mock_sock.gettimeout.return_value = 30.0 + + # Create socket error with different errno + other_error = socket.error("Connection reset by peer") + other_error.errno = errno.ECONNRESET + other_error.args = (errno.ECONNRESET, "Connection reset by peer") + + mock_sock.send.side_effect = other_error + + with self.assertRaises(socket.error): + send(mock_sock, b"test data") + + def test_send_socket_error_no_errno(self): + """Test send with socket error that has no errno""" + mock_sock = Mock() + mock_sock.gettimeout.return_value = 30.0 + + # Create socket error without errno attribute + no_errno_error = socket.error("Generic socket error") + no_errno_error.args = ("Generic socket error",) + + mock_sock.send.side_effect = no_errno_error + + with self.assertRaises(socket.error): + send(mock_sock, b"test data") + + def test_send_write_timeout(self): + """Test send write operation timeout""" + mock_sock = Mock() + mock_sock.gettimeout.return_value = 30.0 + + # First call raises EAGAIN + eagain_error = socket.error("Resource temporarily unavailable") + eagain_error.errno = errno.EAGAIN + eagain_error.args = (errno.EAGAIN, "Resource temporarily unavailable") + + mock_sock.send.side_effect = eagain_error + + with patch("selectors.DefaultSelector") as mock_selector_class: + mock_selector = Mock() + mock_selector_class.return_value = mock_selector + mock_selector.select.return_value = [] # Timeout - nothing ready + + result = send(mock_sock, b"test data") + + # Should return 0 when write times out + self.assertEqual(result, 0) + + def test_send_string_data(self): + """Test send with string data (should be encoded)""" + mock_sock = Mock() + mock_sock.send.return_value = 9 + mock_sock.gettimeout.return_value = 30.0 + + result = send(mock_sock, "test data") + + self.assertEqual(result, 9) + mock_sock.send.assert_called_with(b"test data") + + def test_send_partial_send_retry(self): + """Test send retry mechanism""" + mock_sock = Mock() + mock_sock.gettimeout.return_value = 30.0 + + # Create a scenario where send succeeds after selector retry + eagain_error = socket.error("Resource temporarily unavailable") + eagain_error.errno = errno.EAGAIN + eagain_error.args = (errno.EAGAIN, "Resource temporarily unavailable") + + # Mock the internal _send function behavior + mock_sock.send.side_effect = [eagain_error, 9] + + with patch("selectors.DefaultSelector") as mock_selector_class: + mock_selector = Mock() + mock_selector_class.return_value = mock_selector + mock_selector.select.return_value = [True] # Socket ready for writing + + result = send(mock_sock, b"test data") + + self.assertEqual(result, 9) + # Verify selector was used for retry mechanism + mock_selector.register.assert_called() + mock_selector.select.assert_called() + mock_selector.close.assert_called() + + +if __name__ == "__main__": + unittest.main() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_socket_bugs.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_socket_bugs.py new file mode 100644 index 0000000000000000000000000000000000000000..72f222f5c4ce9d3d44c46db6442ec173ed0e572f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_socket_bugs.py @@ -0,0 +1,160 @@ +# -*- coding: utf-8 -*- +import errno +import socket +import unittest +from unittest.mock import Mock, patch + +from websocket._socket import recv +from websocket._ssl_compat import SSLWantReadError +from websocket._exceptions import ( + WebSocketTimeoutException, + WebSocketConnectionClosedException, +) + +""" +test_socket_bugs.py +websocket - WebSocket client library for Python + +Copyright 2025 engn33r + +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. +""" + +class SocketBugsTest(unittest.TestCase): + """Test bugs found in socket handling logic""" + + def test_bug_implicit_none_return_from_ssl_want_read_fixed(self): + """ + BUG #5 FIX VERIFICATION: Test SSLWantReadError timeout now raises correct exception + + Bug was in _socket.py:100-101 - SSLWantReadError except block returned None implicitly + Fixed: Now properly handles timeout with WebSocketTimeoutException + """ + mock_sock = Mock() + mock_sock.recv.side_effect = SSLWantReadError() + mock_sock.gettimeout.return_value = 1.0 + + with patch("selectors.DefaultSelector") as mock_selector_class: + mock_selector = Mock() + mock_selector_class.return_value = mock_selector + mock_selector.select.return_value = [] # Timeout - no data ready + + with self.assertRaises(WebSocketTimeoutException) as cm: + recv(mock_sock, 100) + + # Verify correct timeout exception and message + self.assertIn("Connection timed out waiting for data", str(cm.exception)) + + def test_bug_implicit_none_return_from_socket_error_fixed(self): + """ + BUG #5 FIX VERIFICATION: Test that socket.error with EAGAIN now handles timeout correctly + + Bug was in _socket.py:102-105 - socket.error except block returned None implicitly + Fixed: Now properly handles timeout with WebSocketTimeoutException + """ + mock_sock = Mock() + + # Create socket error with EAGAIN (should be retried) + eagain_error = OSError(errno.EAGAIN, "Resource temporarily unavailable") + + # First call raises EAGAIN, selector times out on retry + mock_sock.recv.side_effect = eagain_error + mock_sock.gettimeout.return_value = 1.0 + + with patch("selectors.DefaultSelector") as mock_selector_class: + mock_selector = Mock() + mock_selector_class.return_value = mock_selector + mock_selector.select.return_value = [] # Timeout - no data ready + + with self.assertRaises(WebSocketTimeoutException) as cm: + recv(mock_sock, 100) + + # Verify correct timeout exception and message + self.assertIn("Connection timed out waiting for data", str(cm.exception)) + + def test_bug_wrong_exception_for_selector_timeout_fixed(self): + """ + BUG #6 FIX VERIFICATION: Test that selector timeout now raises correct exception type + + Bug was in _socket.py:115 returning None for timeout, treated as connection error + Fixed: Now raises WebSocketTimeoutException directly + """ + mock_sock = Mock() + mock_sock.recv.side_effect = SSLWantReadError() # Trigger retry path + mock_sock.gettimeout.return_value = 1.0 + + with patch("selectors.DefaultSelector") as mock_selector_class: + mock_selector = Mock() + mock_selector_class.return_value = mock_selector + mock_selector.select.return_value = [] # TIMEOUT - this is key! + + with self.assertRaises(WebSocketTimeoutException) as cm: + recv(mock_sock, 100) + + # Verify it's the correct timeout exception with proper message + self.assertIn("Connection timed out waiting for data", str(cm.exception)) + + # This proves the fix works: + # 1. selector.select() returns [] (timeout) + # 2. _recv() now raises WebSocketTimeoutException directly + # 3. No more misclassification as connection closed error! + + def test_socket_timeout_exception_handling(self): + """ + Test that socket.timeout exceptions are properly handled + """ + mock_sock = Mock() + mock_sock.gettimeout.return_value = 1.0 + + # Simulate a real socket.timeout scenario + mock_sock.recv.side_effect = socket.timeout("Operation timed out") + + # This works correctly - socket.timeout raises WebSocketTimeoutException + with self.assertRaises(WebSocketTimeoutException) as cm: + recv(mock_sock, 100) + + # In Python 3.10+, socket.timeout is a subclass of TimeoutError + # so it's caught by the TimeoutError handler with hardcoded message + # In Python 3.9, socket.timeout is caught by socket.timeout handler + # which preserves the original message + import sys + + if sys.version_info >= (3, 10): + self.assertIn("Connection timed out", str(cm.exception)) + else: + self.assertIn("Operation timed out", str(cm.exception)) + + def test_correct_ssl_want_read_retry_behavior(self): + """Test the correct behavior when SSLWantReadError is properly handled""" + mock_sock = Mock() + + # First call raises SSLWantReadError, second call succeeds + mock_sock.recv.side_effect = [SSLWantReadError(), b"data after retry"] + mock_sock.gettimeout.return_value = 1.0 + + with patch("selectors.DefaultSelector") as mock_selector_class: + mock_selector = Mock() + mock_selector_class.return_value = mock_selector + mock_selector.select.return_value = [True] # Data ready after wait + + # This should work correctly + result = recv(mock_sock, 100) + self.assertEqual(result, b"data after retry") + + # Selector should be used for retry + mock_selector.register.assert_called() + mock_selector.select.assert_called() + + +if __name__ == "__main__": + unittest.main() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_ssl_compat.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_ssl_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..9dcd674b0f0be01bef0749699101b3dce3af92cf --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_ssl_compat.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +import sys +import unittest +from unittest.mock import patch + +""" +test_ssl_compat.py +websocket - WebSocket client library for Python + +Copyright 2025 engn33r + +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. +""" + +class SSLCompatTest(unittest.TestCase): + def test_ssl_available(self): + """Test that SSL is available in normal conditions""" + import websocket._ssl_compat as ssl_compat + + # In normal conditions, SSL should be available + self.assertTrue(ssl_compat.HAVE_SSL) + self.assertIsNotNone(ssl_compat.ssl) + + # SSL exception classes should be available + self.assertTrue(hasattr(ssl_compat, "SSLError")) + self.assertTrue(hasattr(ssl_compat, "SSLEOFError")) + self.assertTrue(hasattr(ssl_compat, "SSLWantReadError")) + self.assertTrue(hasattr(ssl_compat, "SSLWantWriteError")) + + def test_ssl_not_available(self): + """Test fallback behavior when SSL is not available""" + # Remove ssl_compat from modules to force reimport + if "websocket._ssl_compat" in sys.modules: + del sys.modules["websocket._ssl_compat"] + + # Mock the ssl module to not be available + import builtins + + original_import = builtins.__import__ + + def mock_import(name, *args, **kwargs): + if name == "ssl": + raise ImportError("No module named 'ssl'") + return original_import(name, *args, **kwargs) + + with patch("builtins.__import__", side_effect=mock_import): + import websocket._ssl_compat as ssl_compat + + # SSL should not be available + self.assertFalse(ssl_compat.HAVE_SSL) + self.assertIsNone(ssl_compat.ssl) + + # Fallback exception classes should be available and functional + self.assertTrue(issubclass(ssl_compat.SSLError, Exception)) + self.assertTrue(issubclass(ssl_compat.SSLEOFError, Exception)) + self.assertTrue(issubclass(ssl_compat.SSLWantReadError, Exception)) + self.assertTrue(issubclass(ssl_compat.SSLWantWriteError, Exception)) + + # Test that exceptions can be instantiated + ssl_error = ssl_compat.SSLError("test error") + self.assertIsInstance(ssl_error, Exception) + self.assertEqual(str(ssl_error), "test error") + + ssl_eof_error = ssl_compat.SSLEOFError("test eof") + self.assertIsInstance(ssl_eof_error, Exception) + + ssl_want_read = ssl_compat.SSLWantReadError("test read") + self.assertIsInstance(ssl_want_read, Exception) + + ssl_want_write = ssl_compat.SSLWantWriteError("test write") + self.assertIsInstance(ssl_want_write, Exception) + + def tearDown(self): + """Clean up after tests""" + # Ensure ssl_compat is reimported fresh for next test + if "websocket._ssl_compat" in sys.modules: + del sys.modules["websocket._ssl_compat"] + + +if __name__ == "__main__": + unittest.main() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_ssl_edge_cases.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_ssl_edge_cases.py new file mode 100644 index 0000000000000000000000000000000000000000..a8e14d3f4ed31a3b1ea61511931948f613213017 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_ssl_edge_cases.py @@ -0,0 +1,638 @@ +# -*- coding: utf-8 -*- +import unittest +import socket +import ssl +from unittest.mock import Mock, patch, MagicMock + +from websocket._ssl_compat import ( + SSLError, + SSLEOFError, + SSLWantReadError, + SSLWantWriteError, + HAVE_SSL, +) +from websocket._http import _ssl_socket, _wrap_sni_socket +from websocket._exceptions import WebSocketException +from websocket._socket import recv, send + +""" +test_ssl_edge_cases.py +websocket - WebSocket client library for Python + +Copyright 2025 engn33r + +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. +""" + +class SSLEdgeCasesTest(unittest.TestCase): + + def setUp(self): + if not HAVE_SSL: + self.skipTest("SSL not available") + + def test_ssl_handshake_failure(self): + """Test SSL handshake failure scenarios""" + mock_sock = Mock() + + # Test SSL handshake timeout + with patch("ssl.SSLContext") as mock_ssl_context: + mock_context = Mock() + mock_ssl_context.return_value = mock_context + mock_context.wrap_socket.side_effect = socket.timeout( + "SSL handshake timeout" + ) + + sslopt = {"cert_reqs": ssl.CERT_REQUIRED} + + with self.assertRaises(socket.timeout): + _ssl_socket(mock_sock, sslopt, "example.com") + + def test_ssl_certificate_verification_failures(self): + """Test various SSL certificate verification failure scenarios""" + mock_sock = Mock() + + # Test certificate verification failure + with patch("ssl.SSLContext") as mock_ssl_context: + mock_context = Mock() + mock_ssl_context.return_value = mock_context + mock_context.wrap_socket.side_effect = ssl.SSLCertVerificationError( + "Certificate verification failed" + ) + + sslopt = {"cert_reqs": ssl.CERT_REQUIRED, "check_hostname": True} + + with self.assertRaises(ssl.SSLCertVerificationError): + _ssl_socket(mock_sock, sslopt, "badssl.example") + + def test_ssl_context_configuration_edge_cases(self): + """Test SSL context configuration with various edge cases""" + mock_sock = Mock() + + # Test with pre-created SSL context + with patch("ssl.SSLContext") as mock_ssl_context: + existing_context = Mock() + existing_context.wrap_socket.return_value = Mock() + mock_ssl_context.return_value = existing_context + + sslopt = {"context": existing_context} + + # Call _ssl_socket which should use the existing context + _ssl_socket(mock_sock, sslopt, "example.com") + + # Should use the provided context, not create a new one + existing_context.wrap_socket.assert_called_once() + + def test_ssl_ca_bundle_environment_edge_cases(self): + """Test CA bundle environment variable edge cases""" + mock_sock = Mock() + + # Test with non-existent CA bundle file + with patch.dict( + "os.environ", {"WEBSOCKET_CLIENT_CA_BUNDLE": "/nonexistent/ca-bundle.crt"} + ): + with patch("os.path.isfile", return_value=False): + with patch("os.path.isdir", return_value=False): + with patch("ssl.SSLContext") as mock_ssl_context: + mock_context = Mock() + mock_ssl_context.return_value = mock_context + mock_context.wrap_socket.return_value = Mock() + + sslopt = {} + _ssl_socket(mock_sock, sslopt, "example.com") + + # Should not try to load non-existent CA bundle + mock_context.load_verify_locations.assert_not_called() + + # Test with CA bundle directory + with patch.dict("os.environ", {"WEBSOCKET_CLIENT_CA_BUNDLE": "/etc/ssl/certs"}): + with patch("os.path.isfile", return_value=False): + with patch("os.path.isdir", return_value=True): + with patch("ssl.SSLContext") as mock_ssl_context: + mock_context = Mock() + mock_ssl_context.return_value = mock_context + mock_context.wrap_socket.return_value = Mock() + + sslopt = {} + _ssl_socket(mock_sock, sslopt, "example.com") + + # Should load CA directory + mock_context.load_verify_locations.assert_called_with( + cafile=None, capath="/etc/ssl/certs" + ) + + def test_ssl_cipher_configuration_edge_cases(self): + """Test SSL cipher configuration edge cases""" + mock_sock = Mock() + + # Test with invalid cipher suite + with patch("ssl.SSLContext") as mock_ssl_context: + mock_context = Mock() + mock_ssl_context.return_value = mock_context + mock_context.set_ciphers.side_effect = ssl.SSLError( + "No cipher can be selected" + ) + mock_context.wrap_socket.return_value = Mock() + + sslopt = {"ciphers": "INVALID_CIPHER"} + + with self.assertRaises(WebSocketException): + _ssl_socket(mock_sock, sslopt, "example.com") + + def test_ssl_ecdh_curve_edge_cases(self): + """Test ECDH curve configuration edge cases""" + mock_sock = Mock() + + # Test with invalid ECDH curve + with patch("ssl.SSLContext") as mock_ssl_context: + mock_context = Mock() + mock_ssl_context.return_value = mock_context + mock_context.set_ecdh_curve.side_effect = ValueError("unknown curve name") + mock_context.wrap_socket.return_value = Mock() + + sslopt = {"ecdh_curve": "invalid_curve"} + + with self.assertRaises(WebSocketException): + _ssl_socket(mock_sock, sslopt, "example.com") + + def test_ssl_client_certificate_edge_cases(self): + """Test client certificate configuration edge cases""" + mock_sock = Mock() + + # Test with non-existent client certificate + with patch("ssl.SSLContext") as mock_ssl_context: + mock_context = Mock() + mock_ssl_context.return_value = mock_context + mock_context.load_cert_chain.side_effect = FileNotFoundError("No such file") + mock_context.wrap_socket.return_value = Mock() + + sslopt = {"certfile": "/nonexistent/client.crt"} + + with self.assertRaises(WebSocketException): + _ssl_socket(mock_sock, sslopt, "example.com") + + def test_ssl_want_read_write_retry_edge_cases(self): + """Test SSL want read/write retry edge cases""" + mock_sock = Mock() + + # Test SSLWantReadError with multiple retries before success + read_attempts = [0] # Use list for mutable reference + + def mock_recv(bufsize): + read_attempts[0] += 1 + if read_attempts[0] == 1: + raise SSLWantReadError("The operation did not complete") + elif read_attempts[0] == 2: + return b"data after retries" + else: + return b"" + + mock_sock.recv.side_effect = mock_recv + mock_sock.gettimeout.return_value = 30.0 + + with patch("selectors.DefaultSelector") as mock_selector_class: + mock_selector = Mock() + mock_selector_class.return_value = mock_selector + mock_selector.select.return_value = [True] # Always ready + + result = recv(mock_sock, 100) + + self.assertEqual(result, b"data after retries") + self.assertEqual(read_attempts[0], 2) + # Should have used selector for retry + mock_selector.register.assert_called() + mock_selector.select.assert_called() + + def test_ssl_want_write_retry_edge_cases(self): + """Test SSL want write retry edge cases""" + mock_sock = Mock() + + # Test SSLWantWriteError with multiple retries before success + write_attempts = [0] # Use list for mutable reference + + def mock_send(data): + write_attempts[0] += 1 + if write_attempts[0] == 1: + raise SSLWantWriteError("The operation did not complete") + elif write_attempts[0] == 2: + return len(data) + else: + return 0 + + mock_sock.send.side_effect = mock_send + mock_sock.gettimeout.return_value = 30.0 + + with patch("selectors.DefaultSelector") as mock_selector_class: + mock_selector = Mock() + mock_selector_class.return_value = mock_selector + mock_selector.select.return_value = [True] # Always ready + + result = send(mock_sock, b"test data") + + self.assertEqual(result, 9) # len("test data") + self.assertEqual(write_attempts[0], 2) + + def test_ssl_eof_error_edge_cases(self): + """Test SSL EOF error edge cases""" + mock_sock = Mock() + + # Test SSLEOFError during send + mock_sock.send.side_effect = SSLEOFError("SSL connection has been closed") + mock_sock.gettimeout.return_value = 30.0 + + from websocket._exceptions import WebSocketConnectionClosedException + + with self.assertRaises(WebSocketConnectionClosedException): + send(mock_sock, b"test data") + + def test_ssl_pending_data_edge_cases(self): + """Test SSL pending data scenarios""" + from websocket._dispatcher import SSLDispatcher + from websocket._app import WebSocketApp + + # Mock SSL socket with pending data + mock_ssl_sock = Mock() + mock_ssl_sock.pending.return_value = 1024 # Simulates pending SSL data + + # Mock WebSocketApp + mock_app = Mock(spec=WebSocketApp) + mock_app.sock = Mock() + mock_app.sock.sock = mock_ssl_sock + + dispatcher = SSLDispatcher(mock_app, 5.0) + + # When there's pending data, should return immediately without selector + result = dispatcher.select(mock_ssl_sock, Mock()) + + # Should return the socket list when there's pending data + self.assertEqual(result, [mock_ssl_sock]) + mock_ssl_sock.pending.assert_called_once() + + def test_ssl_renegotiation_edge_cases(self): + """Test SSL renegotiation scenarios""" + mock_sock = Mock() + + # Simulate SSL renegotiation during read + call_count = 0 + + def mock_recv(bufsize): + nonlocal call_count + call_count += 1 + if call_count == 1: + raise SSLWantReadError("SSL renegotiation required") + return b"data after renegotiation" + + mock_sock.recv.side_effect = mock_recv + mock_sock.gettimeout.return_value = 30.0 + + with patch("selectors.DefaultSelector") as mock_selector_class: + mock_selector = Mock() + mock_selector_class.return_value = mock_selector + mock_selector.select.return_value = [True] + + result = recv(mock_sock, 100) + + self.assertEqual(result, b"data after renegotiation") + self.assertEqual(call_count, 2) + + def test_ssl_server_hostname_override(self): + """Test SSL server hostname override scenarios""" + mock_sock = Mock() + + with patch("ssl.SSLContext") as mock_ssl_context: + mock_context = Mock() + mock_ssl_context.return_value = mock_context + mock_context.wrap_socket.return_value = Mock() + + # Test server_hostname override + sslopt = {"server_hostname": "override.example.com"} + _ssl_socket(mock_sock, sslopt, "original.example.com") + + # Should use override hostname in wrap_socket call + mock_context.wrap_socket.assert_called_with( + mock_sock, + do_handshake_on_connect=True, + suppress_ragged_eofs=True, + server_hostname="override.example.com", + ) + + def test_ssl_protocol_version_edge_cases(self): + """Test SSL protocol version edge cases""" + mock_sock = Mock() + + # Test with deprecated SSL version + with patch("ssl.SSLContext") as mock_ssl_context: + mock_context = Mock() + mock_ssl_context.return_value = mock_context + mock_context.wrap_socket.return_value = Mock() + + # Test that deprecated ssl_version is still handled + if hasattr(ssl, "PROTOCOL_TLS"): + sslopt = {"ssl_version": ssl.PROTOCOL_TLS} + _ssl_socket(mock_sock, sslopt, "example.com") + + mock_ssl_context.assert_called_with(ssl.PROTOCOL_TLS) + + def test_ssl_keylog_file_edge_cases(self): + """Test SSL keylog file configuration edge cases""" + mock_sock = Mock() + + # Test with SSLKEYLOGFILE environment variable + with patch.dict("os.environ", {"SSLKEYLOGFILE": "/tmp/ssl_keys.log"}): + with patch("ssl.SSLContext") as mock_ssl_context: + mock_context = Mock() + mock_ssl_context.return_value = mock_context + mock_context.wrap_socket.return_value = Mock() + + sslopt = {} + _ssl_socket(mock_sock, sslopt, "example.com") + + # Should set keylog_filename + self.assertEqual(mock_context.keylog_filename, "/tmp/ssl_keys.log") + + def test_ssl_context_verification_modes(self): + """Test different SSL verification mode combinations""" + mock_sock = Mock() + + test_cases = [ + # (cert_reqs, check_hostname, expected_verify_mode, expected_check_hostname) + (ssl.CERT_NONE, False, ssl.CERT_NONE, False), + (ssl.CERT_REQUIRED, False, ssl.CERT_REQUIRED, False), + (ssl.CERT_REQUIRED, True, ssl.CERT_REQUIRED, True), + ] + + for cert_reqs, check_hostname, expected_verify, expected_check in test_cases: + with self.subTest(cert_reqs=cert_reqs, check_hostname=check_hostname): + with patch("ssl.SSLContext") as mock_ssl_context: + mock_context = Mock() + mock_ssl_context.return_value = mock_context + mock_context.wrap_socket.return_value = Mock() + + sslopt = {"cert_reqs": cert_reqs, "check_hostname": check_hostname} + _ssl_socket(mock_sock, sslopt, "example.com") + + self.assertEqual(mock_context.verify_mode, expected_verify) + self.assertEqual(mock_context.check_hostname, expected_check) + + def test_ssl_socket_shutdown_edge_cases(self): + """Test SSL socket shutdown edge cases""" + from websocket._core import WebSocket + + mock_ssl_sock = Mock() + mock_ssl_sock.shutdown.side_effect = SSLError("SSL shutdown failed") + + ws = WebSocket() + ws.sock = mock_ssl_sock + ws.connected = True + + # Should handle SSL shutdown errors gracefully + try: + ws.close() + except SSLError: + self.fail("SSL shutdown error should be handled gracefully") + + def test_ssl_socket_close_during_operation(self): + """Test SSL socket being closed during ongoing operations""" + mock_sock = Mock() + + # Simulate SSL socket being closed during recv + mock_sock.recv.side_effect = SSLError( + "SSL connection has been closed unexpectedly" + ) + mock_sock.gettimeout.return_value = 30.0 + + from websocket._exceptions import WebSocketConnectionClosedException + + # Should handle unexpected SSL closure + with self.assertRaises((SSLError, WebSocketConnectionClosedException)): + recv(mock_sock, 100) + + def test_ssl_compression_edge_cases(self): + """Test SSL compression configuration edge cases""" + mock_sock = Mock() + + with patch("ssl.SSLContext") as mock_ssl_context: + mock_context = Mock() + mock_ssl_context.return_value = mock_context + mock_context.wrap_socket.return_value = Mock() + + # Test SSL compression options (if available) + sslopt = {"compression": False} # Some SSL contexts support this + + try: + _ssl_socket(mock_sock, sslopt, "example.com") + # Should not fail even if compression option is not supported + except AttributeError: + # Expected if SSL context doesn't support compression option + pass + + def test_ssl_session_reuse_edge_cases(self): + """Test SSL session reuse scenarios""" + mock_sock = Mock() + + with patch("ssl.SSLContext") as mock_ssl_context: + mock_context = Mock() + mock_ssl_context.return_value = mock_context + mock_ssl_sock = Mock() + mock_context.wrap_socket.return_value = mock_ssl_sock + + # Test session reuse + mock_ssl_sock.session = "mock_session" + mock_ssl_sock.session_reused = True + + result = _ssl_socket(mock_sock, {}, "example.com") + + # Should handle session reuse without issues + self.assertIsNotNone(result) + + def test_ssl_alpn_protocol_edge_cases(self): + """Test SSL ALPN (Application Layer Protocol Negotiation) edge cases""" + mock_sock = Mock() + + with patch("ssl.SSLContext") as mock_ssl_context: + mock_context = Mock() + mock_ssl_context.return_value = mock_context + mock_context.wrap_socket.return_value = Mock() + + # Test ALPN configuration + sslopt = {"alpn_protocols": ["http/1.1", "h2"]} + + # ALPN protocols are not currently supported in the SSL wrapper + # but the test should not fail + result = _ssl_socket(mock_sock, sslopt, "example.com") + self.assertIsNotNone(result) + # ALPN would need to be implemented in _wrap_sni_socket function + + def test_ssl_sni_edge_cases(self): + """Test SSL SNI (Server Name Indication) edge cases""" + mock_sock = Mock() + + # Test with IPv6 address (should not use SNI) + with patch("ssl.SSLContext") as mock_ssl_context: + mock_context = Mock() + mock_ssl_context.return_value = mock_context + mock_context.wrap_socket.return_value = Mock() + + # IPv6 addresses should not be used for SNI + ipv6_hostname = "2001:db8::1" + _ssl_socket(mock_sock, {}, ipv6_hostname) + + # Should use IPv6 address as server_hostname + mock_context.wrap_socket.assert_called_with( + mock_sock, + do_handshake_on_connect=True, + suppress_ragged_eofs=True, + server_hostname=ipv6_hostname, + ) + + def test_ssl_buffer_size_edge_cases(self): + """Test SSL buffer size related edge cases""" + mock_sock = Mock() + + def mock_recv(bufsize): + # SSL should never try to read more than 16KB at once + if bufsize > 16384: + raise SSLError("[SSL: BAD_LENGTH] buffer too large") + return b"A" * min(bufsize, 1024) # Return smaller chunks + + mock_sock.recv.side_effect = mock_recv + mock_sock.gettimeout.return_value = 30.0 + + from websocket._abnf import frame_buffer + + # Frame buffer should handle large requests by chunking + fb = frame_buffer(lambda size: recv(mock_sock, size), skip_utf8_validation=True) + + # This should work even with large size due to chunking + result = fb.recv_strict(16384) # Exactly 16KB + + self.assertGreater(len(result), 0) + + def test_ssl_protocol_downgrade_protection(self): + """Test SSL protocol downgrade protection""" + mock_sock = Mock() + + with patch("ssl.SSLContext") as mock_ssl_context: + mock_context = Mock() + mock_ssl_context.return_value = mock_context + mock_context.wrap_socket.side_effect = ssl.SSLError( + "SSLV3_ALERT_HANDSHAKE_FAILURE" + ) + + sslopt = {"ssl_version": ssl.PROTOCOL_TLS_CLIENT} + + # Should propagate SSL protocol errors + with self.assertRaises(ssl.SSLError): + _ssl_socket(mock_sock, sslopt, "example.com") + + def test_ssl_certificate_chain_validation(self): + """Test SSL certificate chain validation edge cases""" + mock_sock = Mock() + + with patch("ssl.SSLContext") as mock_ssl_context: + mock_context = Mock() + mock_ssl_context.return_value = mock_context + + # Test certificate chain validation failure + mock_context.wrap_socket.side_effect = ssl.SSLCertVerificationError( + "certificate verify failed: certificate has expired" + ) + + sslopt = {"cert_reqs": ssl.CERT_REQUIRED, "check_hostname": True} + + with self.assertRaises(ssl.SSLCertVerificationError): + _ssl_socket(mock_sock, sslopt, "expired.badssl.com") + + def test_ssl_weak_cipher_rejection(self): + """Test SSL weak cipher rejection scenarios""" + mock_sock = Mock() + + with patch("ssl.SSLContext") as mock_ssl_context: + mock_context = Mock() + mock_ssl_context.return_value = mock_context + mock_context.wrap_socket.side_effect = ssl.SSLError("no shared cipher") + + sslopt = {"ciphers": "RC4-MD5"} # Intentionally weak cipher + + # Should fail with weak ciphers (SSL error is not wrapped by our code) + with self.assertRaises(ssl.SSLError): + _ssl_socket(mock_sock, sslopt, "example.com") + + def test_ssl_hostname_verification_edge_cases(self): + """Test SSL hostname verification edge cases""" + mock_sock = Mock() + + # Test with wildcard certificate scenarios + test_cases = [ + ("*.example.com", "subdomain.example.com"), # Valid wildcard + ("*.example.com", "sub.subdomain.example.com"), # Invalid wildcard depth + ("example.com", "www.example.com"), # Hostname mismatch + ] + + for cert_hostname, connect_hostname in test_cases: + with self.subTest(cert=cert_hostname, hostname=connect_hostname): + with patch("ssl.SSLContext") as mock_ssl_context: + mock_context = Mock() + mock_ssl_context.return_value = mock_context + + if ( + cert_hostname != connect_hostname + and "sub.subdomain" in connect_hostname + ): + # Simulate hostname verification failure for invalid wildcard + mock_context.wrap_socket.side_effect = ssl.SSLCertVerificationError( + f"hostname '{connect_hostname}' doesn't match '{cert_hostname}'" + ) + + sslopt = { + "cert_reqs": ssl.CERT_REQUIRED, + "check_hostname": True, + } + + with self.assertRaises(ssl.SSLCertVerificationError): + _ssl_socket(mock_sock, sslopt, connect_hostname) + else: + mock_context.wrap_socket.return_value = Mock() + sslopt = { + "cert_reqs": ssl.CERT_REQUIRED, + "check_hostname": True, + } + + # Should succeed for valid cases + result = _ssl_socket(mock_sock, sslopt, connect_hostname) + self.assertIsNotNone(result) + + def test_ssl_memory_bio_edge_cases(self): + """Test SSL memory BIO edge cases""" + mock_sock = Mock() + + # Test SSL memory BIO scenarios (if available) + try: + import ssl + + if hasattr(ssl, "MemoryBIO"): + with patch("ssl.SSLContext") as mock_ssl_context: + mock_context = Mock() + mock_ssl_context.return_value = mock_context + mock_context.wrap_socket.return_value = Mock() + + # Memory BIO should work if available + _ssl_socket(mock_sock, {}, "example.com") + + # Standard socket wrapping should still work + mock_context.wrap_socket.assert_called_once() + except (ImportError, AttributeError): + self.skipTest("SSL MemoryBIO not available") + + +if __name__ == "__main__": + unittest.main() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_url.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_url.py new file mode 100644 index 0000000000000000000000000000000000000000..bbb39b0f3f7667a9c35bb5149f846df043d74836 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_url.py @@ -0,0 +1,471 @@ +# -*- coding: utf-8 -*- +# +import os +import unittest + +from websocket._url import ( + _is_address_in_network, + _is_no_proxy_host, + get_proxy_info, + parse_url, +) +from websocket._exceptions import WebSocketProxyException + +""" +test_url.py +websocket - WebSocket client library for Python + +Copyright 2025 engn33r + +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. +""" + + +class UrlTest(unittest.TestCase): + def test_address_in_network(self): + self.assertTrue(_is_address_in_network("127.0.0.1", "127.0.0.0/8")) + self.assertTrue(_is_address_in_network("127.1.0.1", "127.0.0.0/8")) + self.assertFalse(_is_address_in_network("127.1.0.1", "127.0.0.0/24")) + self.assertTrue(_is_address_in_network("2001:db8::1", "2001:db8::/64")) + self.assertFalse(_is_address_in_network("2001:db8:1::1", "2001:db8::/64")) + + def test_parse_url(self): + p = parse_url("ws://www.example.com/r") + self.assertEqual(p[0], "www.example.com") + self.assertEqual(p[1], 80) + self.assertEqual(p[2], "/r") + self.assertEqual(p[3], False) + + p = parse_url("ws://www.example.com/r/") + self.assertEqual(p[0], "www.example.com") + self.assertEqual(p[1], 80) + self.assertEqual(p[2], "/r/") + self.assertEqual(p[3], False) + + p = parse_url("ws://www.example.com/") + self.assertEqual(p[0], "www.example.com") + self.assertEqual(p[1], 80) + self.assertEqual(p[2], "/") + self.assertEqual(p[3], False) + + p = parse_url("ws://www.example.com") + self.assertEqual(p[0], "www.example.com") + self.assertEqual(p[1], 80) + self.assertEqual(p[2], "/") + self.assertEqual(p[3], False) + + p = parse_url("ws://www.example.com:8080/r") + self.assertEqual(p[0], "www.example.com") + self.assertEqual(p[1], 8080) + self.assertEqual(p[2], "/r") + self.assertEqual(p[3], False) + + p = parse_url("ws://www.example.com:8080/") + self.assertEqual(p[0], "www.example.com") + self.assertEqual(p[1], 8080) + self.assertEqual(p[2], "/") + self.assertEqual(p[3], False) + + p = parse_url("ws://www.example.com:8080") + self.assertEqual(p[0], "www.example.com") + self.assertEqual(p[1], 8080) + self.assertEqual(p[2], "/") + self.assertEqual(p[3], False) + + p = parse_url("wss://www.example.com:8080/r") + self.assertEqual(p[0], "www.example.com") + self.assertEqual(p[1], 8080) + self.assertEqual(p[2], "/r") + self.assertEqual(p[3], True) + + p = parse_url("wss://www.example.com:8080/r?key=value") + self.assertEqual(p[0], "www.example.com") + self.assertEqual(p[1], 8080) + self.assertEqual(p[2], "/r?key=value") + self.assertEqual(p[3], True) + + self.assertRaises(ValueError, parse_url, "http://www.example.com/r") + + p = parse_url("ws://[2a03:4000:123:83::3]/r") + self.assertEqual(p[0], "2a03:4000:123:83::3") + self.assertEqual(p[1], 80) + self.assertEqual(p[2], "/r") + self.assertEqual(p[3], False) + + p = parse_url("ws://[2a03:4000:123:83::3]:8080/r") + self.assertEqual(p[0], "2a03:4000:123:83::3") + self.assertEqual(p[1], 8080) + self.assertEqual(p[2], "/r") + self.assertEqual(p[3], False) + + p = parse_url("wss://[2a03:4000:123:83::3]/r") + self.assertEqual(p[0], "2a03:4000:123:83::3") + self.assertEqual(p[1], 443) + self.assertEqual(p[2], "/r") + self.assertEqual(p[3], True) + + p = parse_url("wss://[2a03:4000:123:83::3]:8080/r") + self.assertEqual(p[0], "2a03:4000:123:83::3") + self.assertEqual(p[1], 8080) + self.assertEqual(p[2], "/r") + self.assertEqual(p[3], True) + + +class IsNoProxyHostTest(unittest.TestCase): + def setUp(self): + self.no_proxy = os.environ.get("no_proxy", None) + if "no_proxy" in os.environ: + del os.environ["no_proxy"] + + def tearDown(self): + if self.no_proxy: + os.environ["no_proxy"] = self.no_proxy + elif "no_proxy" in os.environ: + del os.environ["no_proxy"] + + def test_match_all(self): + self.assertTrue(_is_no_proxy_host("any.websocket.org", ["*"])) + self.assertTrue(_is_no_proxy_host("192.168.0.1", ["*"])) + self.assertFalse(_is_no_proxy_host("192.168.0.1", ["192.168.1.1"])) + self.assertFalse( + _is_no_proxy_host("any.websocket.org", ["other.websocket.org"]) + ) + self.assertTrue( + _is_no_proxy_host("any.websocket.org", ["other.websocket.org", "*"]) + ) + os.environ["no_proxy"] = "*" + self.assertTrue(_is_no_proxy_host("any.websocket.org", None)) + self.assertTrue(_is_no_proxy_host("192.168.0.1", None)) + os.environ["no_proxy"] = "other.websocket.org, *" + self.assertTrue(_is_no_proxy_host("any.websocket.org", None)) + + def test_ip_address(self): + self.assertTrue(_is_no_proxy_host("127.0.0.1", ["127.0.0.1"])) + self.assertFalse(_is_no_proxy_host("127.0.0.2", ["127.0.0.1"])) + self.assertTrue( + _is_no_proxy_host("127.0.0.1", ["other.websocket.org", "127.0.0.1"]) + ) + self.assertFalse( + _is_no_proxy_host("127.0.0.2", ["other.websocket.org", "127.0.0.1"]) + ) + os.environ["no_proxy"] = "127.0.0.1" + self.assertTrue(_is_no_proxy_host("127.0.0.1", None)) + self.assertFalse(_is_no_proxy_host("127.0.0.2", None)) + os.environ["no_proxy"] = "other.websocket.org, 127.0.0.1" + self.assertTrue(_is_no_proxy_host("127.0.0.1", None)) + self.assertFalse(_is_no_proxy_host("127.0.0.2", None)) + + def test_ip_address_in_range(self): + self.assertTrue(_is_no_proxy_host("127.0.0.1", ["127.0.0.0/8"])) + self.assertTrue(_is_no_proxy_host("127.0.0.2", ["127.0.0.0/8"])) + self.assertFalse(_is_no_proxy_host("127.1.0.1", ["127.0.0.0/24"])) + self.assertTrue(_is_no_proxy_host("2001:db8::1", ["2001:db8::/64"])) + self.assertFalse(_is_no_proxy_host("2001:db8:1::1", ["2001:db8::/64"])) + os.environ["no_proxy"] = "127.0.0.0/8,2001:db8::/64" + self.assertTrue(_is_no_proxy_host("127.0.0.1", None)) + self.assertTrue(_is_no_proxy_host("127.0.0.2", None)) + self.assertTrue(_is_no_proxy_host("2001:db8::1", None)) + self.assertFalse(_is_no_proxy_host("2001:db8:1::1", None)) + os.environ["no_proxy"] = "127.0.0.0/24,2001:db8::/64" + self.assertFalse(_is_no_proxy_host("127.1.0.1", None)) + self.assertFalse(_is_no_proxy_host("2001:db8:1::1", None)) + + def test_hostname_match(self): + self.assertTrue(_is_no_proxy_host("my.websocket.org", ["my.websocket.org"])) + self.assertTrue( + _is_no_proxy_host( + "my.websocket.org", ["other.websocket.org", "my.websocket.org"] + ) + ) + self.assertFalse(_is_no_proxy_host("my.websocket.org", ["other.websocket.org"])) + os.environ["no_proxy"] = "my.websocket.org" + self.assertTrue(_is_no_proxy_host("my.websocket.org", None)) + self.assertFalse(_is_no_proxy_host("other.websocket.org", None)) + os.environ["no_proxy"] = "other.websocket.org, my.websocket.org" + self.assertTrue(_is_no_proxy_host("my.websocket.org", None)) + + def test_hostname_match_domain(self): + self.assertTrue(_is_no_proxy_host("any.websocket.org", [".websocket.org"])) + self.assertTrue(_is_no_proxy_host("my.other.websocket.org", [".websocket.org"])) + self.assertTrue( + _is_no_proxy_host( + "any.websocket.org", ["my.websocket.org", ".websocket.org"] + ) + ) + self.assertFalse(_is_no_proxy_host("any.websocket.com", [".websocket.org"])) + os.environ["no_proxy"] = ".websocket.org" + self.assertTrue(_is_no_proxy_host("any.websocket.org", None)) + self.assertTrue(_is_no_proxy_host("my.other.websocket.org", None)) + self.assertFalse(_is_no_proxy_host("any.websocket.com", None)) + os.environ["no_proxy"] = "my.websocket.org, .websocket.org" + self.assertTrue(_is_no_proxy_host("any.websocket.org", None)) + + +class ProxyInfoTest(unittest.TestCase): + def setUp(self): + self.http_proxy = os.environ.get("http_proxy", None) + self.https_proxy = os.environ.get("https_proxy", None) + self.no_proxy = os.environ.get("no_proxy", None) + if "http_proxy" in os.environ: + del os.environ["http_proxy"] + if "https_proxy" in os.environ: + del os.environ["https_proxy"] + if "no_proxy" in os.environ: + del os.environ["no_proxy"] + + def tearDown(self): + if self.http_proxy: + os.environ["http_proxy"] = self.http_proxy + elif "http_proxy" in os.environ: + del os.environ["http_proxy"] + + if self.https_proxy: + os.environ["https_proxy"] = self.https_proxy + elif "https_proxy" in os.environ: + del os.environ["https_proxy"] + + if self.no_proxy: + os.environ["no_proxy"] = self.no_proxy + elif "no_proxy" in os.environ: + del os.environ["no_proxy"] + + def test_proxy_from_args(self): + self.assertRaises( + WebSocketProxyException, + get_proxy_info, + "echo.websocket.events", + False, + proxy_host="localhost", + ) + self.assertEqual( + get_proxy_info( + "echo.websocket.events", False, proxy_host="localhost", proxy_port=3128 + ), + ("localhost", 3128, None), + ) + self.assertEqual( + get_proxy_info( + "echo.websocket.events", True, proxy_host="localhost", proxy_port=3128 + ), + ("localhost", 3128, None), + ) + + self.assertEqual( + get_proxy_info( + "echo.websocket.events", + False, + proxy_host="localhost", + proxy_port=9001, + proxy_auth=("a", "b"), + ), + ("localhost", 9001, ("a", "b")), + ) + self.assertEqual( + get_proxy_info( + "echo.websocket.events", + False, + proxy_host="localhost", + proxy_port=3128, + proxy_auth=("a", "b"), + ), + ("localhost", 3128, ("a", "b")), + ) + self.assertEqual( + get_proxy_info( + "echo.websocket.events", + True, + proxy_host="localhost", + proxy_port=8765, + proxy_auth=("a", "b"), + ), + ("localhost", 8765, ("a", "b")), + ) + self.assertEqual( + get_proxy_info( + "echo.websocket.events", + True, + proxy_host="localhost", + proxy_port=3128, + proxy_auth=("a", "b"), + ), + ("localhost", 3128, ("a", "b")), + ) + + self.assertEqual( + get_proxy_info( + "echo.websocket.events", + True, + proxy_host="localhost", + proxy_port=3128, + no_proxy=["example.com"], + proxy_auth=("a", "b"), + ), + ("localhost", 3128, ("a", "b")), + ) + self.assertEqual( + get_proxy_info( + "echo.websocket.events", + True, + proxy_host="localhost", + proxy_port=3128, + no_proxy=["echo.websocket.events"], + proxy_auth=("a", "b"), + ), + (None, 0, None), + ) + + self.assertEqual( + get_proxy_info( + "echo.websocket.events", + True, + proxy_host="localhost", + proxy_port=3128, + no_proxy=[".websocket.events"], + ), + (None, 0, None), + ) + + def test_proxy_from_env(self): + os.environ["http_proxy"] = "http://localhost/" + self.assertEqual( + get_proxy_info("echo.websocket.events", False), ("localhost", None, None) + ) + os.environ["http_proxy"] = "http://localhost:3128/" + self.assertEqual( + get_proxy_info("echo.websocket.events", False), ("localhost", 3128, None) + ) + + os.environ["http_proxy"] = "http://localhost/" + os.environ["https_proxy"] = "http://localhost2/" + self.assertEqual( + get_proxy_info("echo.websocket.events", False), ("localhost", None, None) + ) + os.environ["http_proxy"] = "http://localhost:3128/" + os.environ["https_proxy"] = "http://localhost2:3128/" + self.assertEqual( + get_proxy_info("echo.websocket.events", False), ("localhost", 3128, None) + ) + + os.environ["http_proxy"] = "http://localhost/" + os.environ["https_proxy"] = "http://localhost2/" + self.assertEqual( + get_proxy_info("echo.websocket.events", True), ("localhost2", None, None) + ) + os.environ["http_proxy"] = "http://localhost:3128/" + os.environ["https_proxy"] = "http://localhost2:3128/" + self.assertEqual( + get_proxy_info("echo.websocket.events", True), ("localhost2", 3128, None) + ) + + os.environ["http_proxy"] = "" + os.environ["https_proxy"] = "http://localhost2/" + self.assertEqual( + get_proxy_info("echo.websocket.events", True), ("localhost2", None, None) + ) + self.assertEqual( + get_proxy_info("echo.websocket.events", False), (None, 0, None) + ) + os.environ["http_proxy"] = "" + os.environ["https_proxy"] = "http://localhost2:3128/" + self.assertEqual( + get_proxy_info("echo.websocket.events", True), ("localhost2", 3128, None) + ) + self.assertEqual( + get_proxy_info("echo.websocket.events", False), (None, 0, None) + ) + + os.environ["http_proxy"] = "http://localhost/" + os.environ["https_proxy"] = "" + self.assertEqual(get_proxy_info("echo.websocket.events", True), (None, 0, None)) + self.assertEqual( + get_proxy_info("echo.websocket.events", False), ("localhost", None, None) + ) + os.environ["http_proxy"] = "http://localhost:3128/" + os.environ["https_proxy"] = "" + self.assertEqual(get_proxy_info("echo.websocket.events", True), (None, 0, None)) + self.assertEqual( + get_proxy_info("echo.websocket.events", False), ("localhost", 3128, None) + ) + + os.environ["http_proxy"] = "http://a:b@localhost/" + self.assertEqual( + get_proxy_info("echo.websocket.events", False), + ("localhost", None, ("a", "b")), + ) + os.environ["http_proxy"] = "http://a:b@localhost:3128/" + self.assertEqual( + get_proxy_info("echo.websocket.events", False), + ("localhost", 3128, ("a", "b")), + ) + + os.environ["http_proxy"] = "http://a:b@localhost/" + os.environ["https_proxy"] = "http://a:b@localhost2/" + self.assertEqual( + get_proxy_info("echo.websocket.events", False), + ("localhost", None, ("a", "b")), + ) + os.environ["http_proxy"] = "http://a:b@localhost:3128/" + os.environ["https_proxy"] = "http://a:b@localhost2:3128/" + self.assertEqual( + get_proxy_info("echo.websocket.events", False), + ("localhost", 3128, ("a", "b")), + ) + + os.environ["http_proxy"] = "http://a:b@localhost/" + os.environ["https_proxy"] = "http://a:b@localhost2/" + self.assertEqual( + get_proxy_info("echo.websocket.events", True), + ("localhost2", None, ("a", "b")), + ) + os.environ["http_proxy"] = "http://a:b@localhost:3128/" + os.environ["https_proxy"] = "http://a:b@localhost2:3128/" + self.assertEqual( + get_proxy_info("echo.websocket.events", True), + ("localhost2", 3128, ("a", "b")), + ) + + os.environ["http_proxy"] = ( + "http://john%40example.com:P%40SSWORD@localhost:3128/" + ) + os.environ["https_proxy"] = ( + "http://john%40example.com:P%40SSWORD@localhost2:3128/" + ) + self.assertEqual( + get_proxy_info("echo.websocket.events", True), + ("localhost2", 3128, ("john@example.com", "P@SSWORD")), + ) + + os.environ["http_proxy"] = "http://a:b@localhost/" + os.environ["https_proxy"] = "http://a:b@localhost2/" + os.environ["no_proxy"] = "example1.com,example2.com" + self.assertEqual( + get_proxy_info("example.1.com", True), ("localhost2", None, ("a", "b")) + ) + os.environ["http_proxy"] = "http://a:b@localhost:3128/" + os.environ["https_proxy"] = "http://a:b@localhost2:3128/" + os.environ["no_proxy"] = "example1.com,example2.com, echo.websocket.events" + self.assertEqual(get_proxy_info("echo.websocket.events", True), (None, 0, None)) + os.environ["http_proxy"] = "http://a:b@localhost:3128/" + os.environ["https_proxy"] = "http://a:b@localhost2:3128/" + os.environ["no_proxy"] = "example1.com,example2.com, .websocket.events" + self.assertEqual(get_proxy_info("echo.websocket.events", True), (None, 0, None)) + + os.environ["http_proxy"] = "http://a:b@localhost:3128/" + os.environ["https_proxy"] = "http://a:b@localhost2:3128/" + os.environ["no_proxy"] = "127.0.0.0/8, 192.168.0.0/16" + self.assertEqual(get_proxy_info("127.0.0.1", False), (None, 0, None)) + self.assertEqual(get_proxy_info("192.168.1.1", False), (None, 0, None)) + + +if __name__ == "__main__": + unittest.main() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..deb9751bd1611b0d74dddebda3f6eb231ed2f6b5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_utils.py @@ -0,0 +1,138 @@ +# -*- coding: utf-8 -*- +import sys +import unittest +from unittest.mock import patch + +""" +test_utils.py +websocket - WebSocket client library for Python + +Copyright 2025 engn33r + +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. +""" + +class UtilsTest(unittest.TestCase): + def test_nolock(self): + """Test NoLock context manager""" + from websocket._utils import NoLock + + lock = NoLock() + + # Test that it can be used as context manager + with lock: + pass # Should not raise any exception + + # Test enter/exit methods directly + self.assertIsNone(lock.__enter__()) + self.assertIsNone(lock.__exit__(None, None, None)) + + def test_utf8_validation_with_wsaccel(self): + """Test UTF-8 validation when wsaccel is available""" + # Import normally (wsaccel should be available in test environment) + from websocket._utils import validate_utf8 + + # Test valid UTF-8 strings (convert to bytes for wsaccel) + self.assertTrue(validate_utf8("Hello, World!".encode("utf-8"))) + self.assertTrue(validate_utf8("🌟 Unicode test".encode("utf-8"))) + self.assertTrue(validate_utf8(b"Hello, bytes")) + self.assertTrue(validate_utf8("Héllo with accénts".encode("utf-8"))) + + # Test invalid UTF-8 sequences + self.assertFalse(validate_utf8(b"\xff\xfe")) # Invalid UTF-8 + self.assertFalse(validate_utf8(b"\x80\x80")) # Invalid continuation + + def test_utf8_validation_fallback(self): + """Test UTF-8 validation fallback when wsaccel is not available""" + # Remove _utils from modules to force reimport + if "websocket._utils" in sys.modules: + del sys.modules["websocket._utils"] + + # Mock wsaccel import to raise ImportError + import builtins + + original_import = builtins.__import__ + + def mock_import(name, *args, **kwargs): + if "wsaccel" in name: + raise ImportError(f"No module named '{name}'") + return original_import(name, *args, **kwargs) + + with patch("builtins.__import__", side_effect=mock_import): + import websocket._utils as utils + + # Test valid UTF-8 strings with fallback implementation (convert strings to bytes) + self.assertTrue(utils.validate_utf8("Hello, World!".encode("utf-8"))) + self.assertTrue(utils.validate_utf8(b"Hello, bytes")) + self.assertTrue(utils.validate_utf8("ASCII text".encode("utf-8"))) + + # Test Unicode strings (convert to bytes) + self.assertTrue(utils.validate_utf8("🌟 Unicode test".encode("utf-8"))) + self.assertTrue(utils.validate_utf8("Héllo with accénts".encode("utf-8"))) + + # Test empty string/bytes + self.assertTrue(utils.validate_utf8("".encode("utf-8"))) + self.assertTrue(utils.validate_utf8(b"")) + + # Test invalid UTF-8 sequences (should return False) + self.assertFalse(utils.validate_utf8(b"\xff\xfe")) + self.assertFalse(utils.validate_utf8(b"\x80\x80")) + + # Note: The fallback implementation may have different validation behavior + # than wsaccel, so we focus on clearly invalid sequences + + def test_extract_err_message(self): + """Test extract_err_message function""" + from websocket._utils import extract_err_message + + # Test with exception that has args + exc_with_args = Exception("Test error message") + self.assertEqual(extract_err_message(exc_with_args), "Test error message") + + # Test with exception that has multiple args + exc_multi_args = Exception("First arg", "Second arg") + self.assertEqual(extract_err_message(exc_multi_args), "First arg") + + # Test with exception that has no args + exc_no_args = Exception() + self.assertIsNone(extract_err_message(exc_no_args)) + + def test_extract_error_code(self): + """Test extract_error_code function""" + from websocket._utils import extract_error_code + + # Test with exception that has integer as first arg + exc_with_code = Exception(404, "Not found") + self.assertEqual(extract_error_code(exc_with_code), 404) + + # Test with exception that has string as first arg + exc_with_string = Exception("Error message", "Second arg") + self.assertIsNone(extract_error_code(exc_with_string)) + + # Test with exception that has only one arg + exc_single_arg = Exception("Single arg") + self.assertIsNone(extract_error_code(exc_single_arg)) + + # Test with exception that has no args + exc_no_args = Exception() + self.assertIsNone(extract_error_code(exc_no_args)) + + def tearDown(self): + """Clean up after tests""" + # Ensure _utils is reimported fresh for next test + if "websocket._utils" in sys.modules: + del sys.modules["websocket._utils"] + + +if __name__ == "__main__": + unittest.main() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_websocket.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_websocket.py new file mode 100644 index 0000000000000000000000000000000000000000..d0bf671985ae5773457d2f737b1360a8ea8c9813 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket/tests/test_websocket.py @@ -0,0 +1,501 @@ +# -*- coding: utf-8 -*- +# +import os +import os.path +import socket +import unittest +from base64 import decodebytes as base64decode + +import websocket as ws +from websocket._exceptions import ( + WebSocketBadStatusException, + WebSocketAddressException, + WebSocketException, +) +from websocket._handshake import _create_sec_websocket_key +from websocket._handshake import _validate as _validate_header +from websocket._http import read_headers +from websocket._utils import validate_utf8 + +""" +test_websocket.py +websocket - WebSocket client library for Python + +Copyright 2025 engn33r + +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. +""" + +try: + import ssl +except ImportError: + # dummy class of SSLError for ssl none-support environment. + class SSLError(Exception): + pass + + +# Skip test to access the internet unless TEST_WITH_INTERNET == 1 +TEST_WITH_INTERNET = os.environ.get("TEST_WITH_INTERNET", "0") == "1" +# Skip tests relying on local websockets server unless LOCAL_WS_SERVER_PORT != -1 +LOCAL_WS_SERVER_PORT = os.environ.get("LOCAL_WS_SERVER_PORT", "-1") +TEST_WITH_LOCAL_SERVER = LOCAL_WS_SERVER_PORT != "-1" +TRACEABLE = True + + +def create_mask_key(_): + return "abcd" + + +class SockMock: + def __init__(self): + self.data = [] + self.sent = [] + + def add_packet(self, data): + self.data.append(data) + + def gettimeout(self): + return None + + def recv(self, bufsize): + if self.data: + e = self.data.pop(0) + if isinstance(e, Exception): + raise e + if len(e) > bufsize: + self.data.insert(0, e[bufsize:]) + return e[:bufsize] + + def send(self, data): + self.sent.append(data) + return len(data) + + def close(self): + pass + + +class HeaderSockMock(SockMock): + def __init__(self, fname): + SockMock.__init__(self) + path = os.path.join(os.path.dirname(__file__), fname) + with open(path, "rb") as f: + self.add_packet(f.read()) + + +class WebSocketTest(unittest.TestCase): + def setUp(self): + ws.enableTrace(TRACEABLE) + + def tearDown(self): + pass + + def test_default_timeout(self): + self.assertEqual(ws.getdefaulttimeout(), None) + ws.setdefaulttimeout(10) + self.assertEqual(ws.getdefaulttimeout(), 10) + ws.setdefaulttimeout(None) + + def test_ws_key(self): + key = _create_sec_websocket_key() + self.assertTrue(key != 24) + self.assertTrue("¥n" not in key) + + def test_nonce(self): + """WebSocket key should be a random 16-byte nonce.""" + key = _create_sec_websocket_key() + nonce = base64decode(key.encode("utf-8")) + self.assertEqual(16, len(nonce)) + + def test_ws_utils(self): + key = "c6b8hTg4EeGb2gQMztV1/g==" + required_header = { + "upgrade": "websocket", + "connection": "upgrade", + "sec-websocket-accept": "Kxep+hNu9n51529fGidYu7a3wO0=", + } + self.assertEqual(_validate_header(required_header, key, None), (True, None)) + + header = required_header.copy() + header["upgrade"] = "http" + self.assertEqual(_validate_header(header, key, None), (False, None)) + del header["upgrade"] + self.assertEqual(_validate_header(header, key, None), (False, None)) + + header = required_header.copy() + header["connection"] = "something" + self.assertEqual(_validate_header(header, key, None), (False, None)) + del header["connection"] + self.assertEqual(_validate_header(header, key, None), (False, None)) + + header = required_header.copy() + header["sec-websocket-accept"] = "something" + self.assertEqual(_validate_header(header, key, None), (False, None)) + del header["sec-websocket-accept"] + self.assertEqual(_validate_header(header, key, None), (False, None)) + + header = required_header.copy() + header["sec-websocket-protocol"] = "sub1" + self.assertEqual( + _validate_header(header, key, ["sub1", "sub2"]), (True, "sub1") + ) + # This case will print out a logging error using the error() function, but that is expected + self.assertEqual(_validate_header(header, key, ["sub2", "sub3"]), (False, None)) + + header = required_header.copy() + header["sec-websocket-protocol"] = "sUb1" + self.assertEqual( + _validate_header(header, key, ["Sub1", "suB2"]), (True, "sub1") + ) + + header = required_header.copy() + # This case will print out a logging error using the error() function, but that is expected + self.assertEqual(_validate_header(header, key, ["Sub1", "suB2"]), (False, None)) + + def test_read_header(self): + status, header, _ = read_headers(HeaderSockMock("data/header01.txt")) + self.assertEqual(status, 101) + self.assertEqual(header["connection"], "Upgrade") + + status, header, _ = read_headers(HeaderSockMock("data/header03.txt")) + self.assertEqual(status, 101) + self.assertEqual(header["connection"], "Upgrade, Keep-Alive") + + HeaderSockMock("data/header02.txt") + self.assertRaises( + ws.WebSocketException, read_headers, HeaderSockMock("data/header02.txt") + ) + + def test_send(self): + # TODO: add longer frame data + sock = ws.WebSocket() + sock.set_mask_key(create_mask_key) + s = sock.sock = HeaderSockMock("data/header01.txt") + sock.send("Hello") + self.assertEqual(s.sent[0], b"\x81\x85abcd)\x07\x0f\x08\x0e") + + sock.send("こんにちは") + self.assertEqual( + s.sent[1], + b"\x81\x8fabcd\x82\xe3\xf0\x87\xe3\xf1\x80\xe5\xca\x81\xe2\xc5\x82\xe3\xcc", + ) + + # sock.send("x" * 5000) + # self.assertEqual(s.sent[1], b'\x81\x8fabcd\x82\xe3\xf0\x87\xe3\xf1\x80\xe5\xca\x81\xe2\xc5\x82\xe3\xcc") + + self.assertEqual(sock.send_binary(b"1111111111101"), 19) + + def test_recv(self): + # TODO: add longer frame data + sock = ws.WebSocket() + s = sock.sock = SockMock() + something = ( + b"\x81\x8fabcd\x82\xe3\xf0\x87\xe3\xf1\x80\xe5\xca\x81\xe2\xc5\x82\xe3\xcc" + ) + s.add_packet(something) + data = sock.recv() + self.assertEqual(data, "こんにちは") + + s.add_packet(b"\x81\x85abcd)\x07\x0f\x08\x0e") + data = sock.recv() + self.assertEqual(data, "Hello") + + @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") + def test_iter(self): + count = 2 + s = ws.create_connection("wss://api.bitfinex.com/ws/2") + s.send('{"event": "subscribe", "channel": "ticker"}') + for _ in s: + count -= 1 + if count == 0: + break + + @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") + def test_next(self): + sock = ws.create_connection("wss://api.bitfinex.com/ws/2") + self.assertEqual(str, type(next(sock))) + + def test_internal_recv_strict(self): + sock = ws.WebSocket() + s = sock.sock = SockMock() + s.add_packet(b"foo") + s.add_packet(socket.timeout()) + s.add_packet(b"bar") + # s.add_packet(SSLError("The read operation timed out")) + s.add_packet(b"baz") + with self.assertRaises(ws.WebSocketTimeoutException): + sock.frame_buffer.recv_strict(9) + # with self.assertRaises(SSLError): + # data = sock._recv_strict(9) + data = sock.frame_buffer.recv_strict(9) + self.assertEqual(data, b"foobarbaz") + with self.assertRaises(ws.WebSocketConnectionClosedException): + sock.frame_buffer.recv_strict(1) + + def test_recv_timeout(self): + sock = ws.WebSocket() + s = sock.sock = SockMock() + s.add_packet(b"\x81") + s.add_packet(socket.timeout()) + s.add_packet(b"\x8dabcd\x29\x07\x0f\x08\x0e") + s.add_packet(socket.timeout()) + s.add_packet(b"\x4e\x43\x33\x0e\x10\x0f\x00\x40") + with self.assertRaises(ws.WebSocketTimeoutException): + sock.recv() + with self.assertRaises(ws.WebSocketTimeoutException): + sock.recv() + data = sock.recv() + self.assertEqual(data, "Hello, World!") + with self.assertRaises(ws.WebSocketConnectionClosedException): + sock.recv() + + def test_recv_with_simple_fragmentation(self): + sock = ws.WebSocket() + s = sock.sock = SockMock() + # OPCODE=TEXT, FIN=0, MSG="Brevity is " + s.add_packet(b"\x01\x8babcd#\x10\x06\x12\x08\x16\x1aD\x08\x11C") + # OPCODE=CONT, FIN=1, MSG="the soul of wit" + s.add_packet(b"\x80\x8fabcd\x15\n\x06D\x12\r\x16\x08A\r\x05D\x16\x0b\x17") + data = sock.recv() + self.assertEqual(data, "Brevity is the soul of wit") + with self.assertRaises(ws.WebSocketConnectionClosedException): + sock.recv() + + def test_recv_with_fire_event_of_fragmentation(self): + sock = ws.WebSocket(fire_cont_frame=True) + s = sock.sock = SockMock() + # OPCODE=TEXT, FIN=0, MSG="Brevity is " + s.add_packet(b"\x01\x8babcd#\x10\x06\x12\x08\x16\x1aD\x08\x11C") + # OPCODE=CONT, FIN=0, MSG="Brevity is " + s.add_packet(b"\x00\x8babcd#\x10\x06\x12\x08\x16\x1aD\x08\x11C") + # OPCODE=CONT, FIN=1, MSG="the soul of wit" + s.add_packet(b"\x80\x8fabcd\x15\n\x06D\x12\r\x16\x08A\r\x05D\x16\x0b\x17") + + _, data = sock.recv_data() + self.assertEqual(data, b"Brevity is ") + _, data = sock.recv_data() + self.assertEqual(data, b"Brevity is ") + _, data = sock.recv_data() + self.assertEqual(data, b"the soul of wit") + + # OPCODE=CONT, FIN=0, MSG="Brevity is " + s.add_packet(b"\x80\x8babcd#\x10\x06\x12\x08\x16\x1aD\x08\x11C") + + with self.assertRaises(ws.WebSocketException): + sock.recv_data() + + with self.assertRaises(ws.WebSocketConnectionClosedException): + sock.recv() + + def test_close(self): + sock = ws.WebSocket() + sock.connected = True + sock.close() + + sock = ws.WebSocket() + s = sock.sock = SockMock() + sock.connected = True + s.add_packet(b"\x88\x80\x17\x98p\x84") + sock.recv() + self.assertEqual(sock.connected, False) + + def test_recv_cont_fragmentation(self): + sock = ws.WebSocket() + s = sock.sock = SockMock() + # OPCODE=CONT, FIN=1, MSG="the soul of wit" + s.add_packet(b"\x80\x8fabcd\x15\n\x06D\x12\r\x16\x08A\r\x05D\x16\x0b\x17") + self.assertRaises(ws.WebSocketException, sock.recv) + + def test_recv_with_prolonged_fragmentation(self): + sock = ws.WebSocket() + s = sock.sock = SockMock() + # OPCODE=TEXT, FIN=0, MSG="Once more unto the breach, " + s.add_packet( + b"\x01\x9babcd.\x0c\x00\x01A\x0f\x0c\x16\x04B\x16\n\x15\rC\x10\t\x07C\x06\x13\x07\x02\x07\tNC" + ) + # OPCODE=CONT, FIN=0, MSG="dear friends, " + s.add_packet(b"\x00\x8eabcd\x05\x07\x02\x16A\x04\x11\r\x04\x0c\x07\x17MB") + # OPCODE=CONT, FIN=1, MSG="once more" + s.add_packet(b"\x80\x89abcd\x0e\x0c\x00\x01A\x0f\x0c\x16\x04") + data = sock.recv() + self.assertEqual(data, "Once more unto the breach, dear friends, once more") + with self.assertRaises(ws.WebSocketConnectionClosedException): + sock.recv() + + def test_recv_with_fragmentation_and_control_frame(self): + sock = ws.WebSocket() + sock.set_mask_key(create_mask_key) + s = sock.sock = SockMock() + # OPCODE=TEXT, FIN=0, MSG="Too much " + s.add_packet(b"\x01\x89abcd5\r\x0cD\x0c\x17\x00\x0cA") + # OPCODE=PING, FIN=1, MSG="Please PONG this" + s.add_packet(b"\x89\x90abcd1\x0e\x06\x05\x12\x07C4.,$D\x15\n\n\x17") + # OPCODE=CONT, FIN=1, MSG="of a good thing" + s.add_packet(b"\x80\x8fabcd\x0e\x04C\x05A\x05\x0c\x0b\x05B\x17\x0c\x08\x0c\x04") + data = sock.recv() + self.assertEqual(data, "Too much of a good thing") + with self.assertRaises(ws.WebSocketConnectionClosedException): + sock.recv() + self.assertEqual( + s.sent[0], b"\x8a\x90abcd1\x0e\x06\x05\x12\x07C4.,$D\x15\n\n\x17" + ) + + @unittest.skipUnless( + TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled" + ) + def test_websocket(self): + s = ws.create_connection(f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}") + self.assertNotEqual(s, None) + s.send("Hello, World") + result = s.next() + s.fileno() + self.assertEqual(result, "Hello, World") + + s.send("こにゃにゃちは、世界") + result = s.recv() + self.assertEqual(result, "こにゃにゃちは、世界") + self.assertRaises(ValueError, s.send_close, -1, "") + s.close() + + @unittest.skipUnless( + TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled" + ) + def test_ping_pong(self): + s = ws.create_connection(f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}") + self.assertNotEqual(s, None) + s.ping("Hello") + s.pong("Hi") + s.close() + + @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") + def test_support_redirect(self): + s = ws.WebSocket() + self.assertRaises(WebSocketBadStatusException, s.connect, "ws://google.com/") + # Need to find a URL that has a redirect code leading to a websocket + + @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") + def test_secure_websocket(self): + s = ws.create_connection("wss://api.bitfinex.com/ws/2") + self.assertNotEqual(s, None) + self.assertTrue(isinstance(s.sock, ssl.SSLSocket)) + self.assertEqual(s.getstatus(), 101) + self.assertNotEqual(s.getheaders(), None) + s.settimeout(10) + self.assertEqual(s.gettimeout(), 10) + self.assertEqual(s.getsubprotocol(), None) + s.abort() + + @unittest.skipUnless( + TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled" + ) + def test_websocket_with_custom_header(self): + s = ws.create_connection( + f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}", + headers={"User-Agent": "PythonWebsocketClient"}, + ) + self.assertNotEqual(s, None) + self.assertEqual(s.getsubprotocol(), None) + s.send("Hello, World") + result = s.recv() + self.assertEqual(result, "Hello, World") + self.assertRaises(ValueError, s.close, -1, "") + s.close() + + @unittest.skipUnless( + TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled" + ) + def test_after_close(self): + s = ws.create_connection(f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}") + self.assertNotEqual(s, None) + s.close() + self.assertRaises(ws.WebSocketConnectionClosedException, s.send, "Hello") + self.assertRaises(ws.WebSocketConnectionClosedException, s.recv) + + +class SockOptTest(unittest.TestCase): + @unittest.skipUnless( + TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled" + ) + def test_sockopt(self): + sockopt = ((socket.IPPROTO_TCP, socket.TCP_NODELAY, 1),) + s = ws.create_connection( + f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}", sockopt=sockopt + ) + self.assertNotEqual( + s.sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY), 0 + ) + s.close() + + +class UtilsTest(unittest.TestCase): + def test_utf8_validator(self): + state = validate_utf8(b"\xf0\x90\x80\x80") + self.assertEqual(state, True) + state = validate_utf8( + b"\xce\xba\xe1\xbd\xb9\xcf\x83\xce\xbc\xce\xb5\xed\xa0\x80edited" + ) + self.assertEqual(state, False) + state = validate_utf8(b"") + self.assertEqual(state, True) + + +class HandshakeTest(unittest.TestCase): + @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") + def test_http_ssl(self): + websock1 = ws.WebSocket( + sslopt={"cert_chain": ssl.get_default_verify_paths().capath}, + enable_multithread=False, + ) + self.assertRaises(ValueError, websock1.connect, "wss://api.bitfinex.com/ws/2") + websock2 = ws.WebSocket(sslopt={"certfile": "myNonexistentCertFile"}) + self.assertRaises( + WebSocketException, websock2.connect, "wss://api.bitfinex.com/ws/2" + ) + + @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") + def test_manual_headers(self): + websock3 = ws.WebSocket( + sslopt={ + "ca_certs": ssl.get_default_verify_paths().cafile, + "ca_cert_path": ssl.get_default_verify_paths().capath, + } + ) + self.assertRaises( + WebSocketBadStatusException, + websock3.connect, + "wss://api.bitfinex.com/ws/2", + cookie="chocolate", + origin="testing_websockets.com", + host="echo.websocket.events/websocket-client-test", + subprotocols=["testproto"], + connection="Upgrade", + header={ + "CustomHeader1": "123", + "Cookie": "TestValue", + "Sec-WebSocket-Key": "k9kFAUWNAMmf5OEMfTlOEA==", + "Sec-WebSocket-Protocol": "newprotocol", + }, + ) + + def test_ipv6(self): + websock2 = ws.WebSocket() + self.assertRaises(ValueError, websock2.connect, "2001:4860:4860::8888") + + def test_bad_urls(self): + websock3 = ws.WebSocket() + self.assertRaises(ValueError, websock3.connect, "ws//example.com") + self.assertRaises(WebSocketAddressException, websock3.connect, "ws://example") + self.assertRaises(ValueError, websock3.connect, "example.com") + + +if __name__ == "__main__": + unittest.main() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket_client-1.9.0.dist-info/INSTALLER b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket_client-1.9.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket_client-1.9.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket_client-1.9.0.dist-info/METADATA b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket_client-1.9.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..dfb92c15dc5bca1e99927f3a2695c5a80b28fb74 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket_client-1.9.0.dist-info/METADATA @@ -0,0 +1,201 @@ +Metadata-Version: 2.4 +Name: websocket-client +Version: 1.9.0 +Summary: WebSocket client for Python with low level API options +Home-page: https://github.com/websocket-client/websocket-client.git +Download-URL: https://github.com/websocket-client/websocket-client/releases +Author: liris +Author-email: liris.pp@gmail.com +Maintainer: engn33r +Maintainer-email: websocket.client@proton.me +License: Apache-2.0 +Project-URL: Documentation, https://websocket-client.readthedocs.io/ +Project-URL: Source, https://github.com/websocket-client/websocket-client/ +Keywords: websockets client +Classifier: Development Status :: 4 - Beta +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: POSIX +Classifier: Operating System :: Microsoft :: Windows +Classifier: Topic :: Internet +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Intended Audience :: Developers +Requires-Python: >=3.9 +Description-Content-Type: text/markdown +License-File: LICENSE +Provides-Extra: test +Requires-Dist: pytest; extra == "test" +Requires-Dist: websockets; extra == "test" +Provides-Extra: optional +Requires-Dist: python-socks; extra == "optional" +Requires-Dist: wsaccel; extra == "optional" +Provides-Extra: docs +Requires-Dist: Sphinx>=6.0; extra == "docs" +Requires-Dist: sphinx_rtd_theme>=1.1.0; extra == "docs" +Requires-Dist: myst-parser>=2.0.0; extra == "docs" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: download-url +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: maintainer +Dynamic: maintainer-email +Dynamic: project-url +Dynamic: provides-extra +Dynamic: requires-python +Dynamic: summary + +[![docs](https://readthedocs.org/projects/websocket-client/badge/?style=flat)](https://websocket-client.readthedocs.io/) +[![Build Status](https://github.com/websocket-client/websocket-client/actions/workflows/build.yml/badge.svg)](https://github.com/websocket-client/websocket-client/actions/workflows/build.yml) +[![codecov](https://codecov.io/gh/websocket-client/websocket-client/branch/master/graph/badge.svg?token=pcXhUQwiL3)](https://codecov.io/gh/websocket-client/websocket-client) +[![PyPI Downloads](https://pepy.tech/badge/websocket-client)](https://pepy.tech/project/websocket-client) +[![PyPI version](https://img.shields.io/pypi/v/websocket_client)](https://pypi.org/project/websocket_client/) +[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) +[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) + +# websocket-client + +websocket-client is a WebSocket client for Python. It provides access +to low level APIs for WebSockets. websocket-client implements version +[hybi-13](https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-13) +of the WebSocket protocol. This client does not currently support the +permessage-deflate extension from +[RFC 7692](https://tools.ietf.org/html/rfc7692). + +## Documentation + +This project's documentation can be found at +[https://websocket-client.readthedocs.io/](https://websocket-client.readthedocs.io/) + +## Contributing + +Please see the [contribution guidelines](https://github.com/websocket-client/websocket-client/blob/master/CONTRIBUTING.md) + +## Installation + +You can use `pip install websocket-client` to install, or `pip install -e .` +to install from a local copy of the code. This module is tested on Python 3.9+. + +There are several optional dependencies that can be installed to enable +specific websocket-client features. +- To install `python-socks` for proxy usage and `wsaccel` for a minor performance boost, use: + `pip install websocket-client[optional]` +- To install `websockets` to run unit tests using the local echo server, use: + `pip install websocket-client[test]` +- To install `Sphinx` and `sphinx_rtd_theme` to build project documentation, use: + `pip install websocket-client[docs]` + +While not a strict dependency, [rel](https://github.com/bubbleboy14/registeredeventlistener) +is useful when using `run_forever` with automatic reconnect. Install rel with `pip install rel`. + +Footnote: Some shells, such as zsh, require you to escape the `[` and `]` characters with a `\`. + +## Usage Tips + +Check out the documentation's FAQ for additional guidelines: +[https://websocket-client.readthedocs.io/en/latest/faq.html](https://websocket-client.readthedocs.io/en/latest/faq.html) + +Known issues with this library include lack of WebSocket Compression +support (RFC 7692) and [minimal threading documentation/support](https://websocket-client.readthedocs.io/en/latest/threading.html). + +## Performance + +The `send` and `validate_utf8` methods can sometimes be bottleneck. +You can disable UTF8 validation in this library (and receive a +performance enhancement) with the `skip_utf8_validation` parameter. +If you want to get better performance, install wsaccel. While +websocket-client does not depend on wsaccel, it will be used if +available. wsaccel doubles the speed of UTF8 validation and +offers a very minor 10% performance boost when masking the +payload data as part of the `send` process. Numpy used to +be a suggested performance enhancement alternative, but +[issue #687](https://github.com/websocket-client/websocket-client/issues/687) +found it didn't help. + +## Examples + +Many more examples are found in the +[examples documentation](https://websocket-client.readthedocs.io/en/latest/examples.html). + +### Long-lived Connection + +Most real-world WebSockets situations involve longer-lived connections. +The WebSocketApp `run_forever` loop will automatically try to reconnect +to an open WebSocket connection when a network +connection is lost if it is provided with: + +- a `dispatcher` argument (async dispatcher like rel or pyevent) +- a non-zero `reconnect` argument (delay between disconnection and attempted reconnection) + +`run_forever` provides a variety of event-based connection controls +using callbacks like `on_message` and `on_error`. +`run_forever` **does not automatically reconnect** if the server +closes the WebSocket gracefully (returning +[a standard websocket close code](https://www.rfc-editor.org/rfc/rfc6455.html#section-7.4.1)). +[This is the logic](https://github.com/websocket-client/websocket-client/pull/838#issuecomment-1228454826) behind the decision. +Customizing behavior when the server closes +the WebSocket should be handled in the `on_close` callback. +This example uses [rel](https://github.com/bubbleboy14/registeredeventlistener) +for the dispatcher to provide automatic reconnection. + +```python +import websocket +import _thread +import time +import rel + +def on_message(ws, message): + print(message) + +def on_error(ws, error): + print(error) + +def on_close(ws, close_status_code, close_msg): + print("### closed ###") + +def on_open(ws): + print("Opened connection") + +if __name__ == "__main__": + websocket.enableTrace(True) + ws = websocket.WebSocketApp("wss://api.gemini.com/v1/marketdata/BTCUSD", + on_open=on_open, + on_message=on_message, + on_error=on_error, + on_close=on_close) + + ws.run_forever(dispatcher=rel, reconnect=5) # Set dispatcher to automatic reconnection, 5 second reconnect delay if connection closed unexpectedly + rel.signal(2, rel.abort) # Keyboard Interrupt + rel.dispatch() +``` + +### Short-lived Connection + +This is if you want to communicate a short message and disconnect +immediately when done. For example, if you want to confirm that a WebSocket +server is running and responds properly to a specific request. + +```python +from websocket import create_connection + +ws = create_connection("ws://echo.websocket.events/") +print(ws.recv()) +print("Sending 'Hello, World'...") +ws.send("Hello, World") +print("Sent") +print("Receiving...") +result = ws.recv() +print("Received '%s'" % result) +ws.close() +``` diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket_client-1.9.0.dist-info/RECORD b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket_client-1.9.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..765513d5516115253a232fc53ceecfecd4206903 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket_client-1.9.0.dist-info/RECORD @@ -0,0 +1,74 @@ +../../Scripts/wsdump.exe,sha256=43WC3aeD0dH9ZsYmUVdPcqhn7u8fXPcs7o_RVcJSa9s,108365 +websocket/__init__.py,sha256=I3CZijeQ5Rkn6HxnwO6QZdNeZbuYEwXBOB62e_y5xp0,958 +websocket/__pycache__/__init__.cpython-311.pyc,, +websocket/__pycache__/_abnf.cpython-311.pyc,, +websocket/__pycache__/_app.cpython-311.pyc,, +websocket/__pycache__/_cookiejar.cpython-311.pyc,, +websocket/__pycache__/_core.cpython-311.pyc,, +websocket/__pycache__/_dispatcher.cpython-311.pyc,, +websocket/__pycache__/_exceptions.cpython-311.pyc,, +websocket/__pycache__/_handshake.cpython-311.pyc,, +websocket/__pycache__/_http.cpython-311.pyc,, +websocket/__pycache__/_logging.cpython-311.pyc,, +websocket/__pycache__/_socket.cpython-311.pyc,, +websocket/__pycache__/_ssl_compat.cpython-311.pyc,, +websocket/__pycache__/_url.cpython-311.pyc,, +websocket/__pycache__/_utils.cpython-311.pyc,, +websocket/__pycache__/_wsdump.cpython-311.pyc,, +websocket/_abnf.py,sha256=RA4YpPUqFhgUjQZi3nFzejQY8qt5fpSRCOTNVVi4xKI,15649 +websocket/_app.py,sha256=o_9M84DHP16PZPYtHpL_z6IQ8-lpMbDjlXmzpyNAaPo,23686 +websocket/_cookiejar.py,sha256=0VbGaki2nZf-qC_iEDxa_hVxid2EPmqYJ3cKxPDOWRo,2346 +websocket/_core.py,sha256=3Xdnig87pa3Lz_rc9GV8zFd-EoRPhOi_q3utNmdUY3c,21856 +websocket/_dispatcher.py,sha256=HHM4QOJ9s6OOrRdQxQD0JugP_C-N352aUwI1NqBcdTs,4592 +websocket/_exceptions.py,sha256=avW2kjXe2sgby-hsUW_QNIuMN6cM3TXf3tBmnSZznis,2178 +websocket/_handshake.py,sha256=WScX-WwtgJBIv-v3YDFJdiUIDbaSa9PcAd2LXpEzNK4,6837 +websocket/_http.py,sha256=aJpOlMYcz6iPb036TcJWWDDInFOdLrEWGkGwvw0q19Q,14676 +websocket/_logging.py,sha256=k7OXNnIh3UdSKNHdZWOR6PeZ3k1AZTpTNjgy8Encwpw,2254 +websocket/_socket.py,sha256=lVZwjro2qGxcoDmkJfcWhamLApsXyqQWX7_7AhHeVKg,6046 +websocket/_ssl_compat.py,sha256=hkC7PiQ6ZkH82a6DneNRHCdKypNvQESrIbgS7j3RqW8,1800 +websocket/_url.py,sha256=4WNYIrWsDVFaZggncSuvBVqZU2ERwMW3tzyByPEp7Eg,5154 +websocket/_utils.py,sha256=Q6En3DqyActKN5A8DZb_S6AUrecnSjH_kqCj3VXedTI,6983 +websocket/_wsdump.py,sha256=nXf2mH7sVHHhNCW0z1g2w--7_WLsd8knD9lWNyMi4-w,7025 +websocket/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +websocket/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +websocket/tests/__pycache__/__init__.cpython-311.pyc,, +websocket/tests/__pycache__/echo-server.cpython-311.pyc,, +websocket/tests/__pycache__/test_abnf.cpython-311.pyc,, +websocket/tests/__pycache__/test_app.cpython-311.pyc,, +websocket/tests/__pycache__/test_cookiejar.cpython-311.pyc,, +websocket/tests/__pycache__/test_dispatcher.cpython-311.pyc,, +websocket/tests/__pycache__/test_handshake_large_response.cpython-311.pyc,, +websocket/tests/__pycache__/test_http.cpython-311.pyc,, +websocket/tests/__pycache__/test_large_payloads.cpython-311.pyc,, +websocket/tests/__pycache__/test_socket.cpython-311.pyc,, +websocket/tests/__pycache__/test_socket_bugs.cpython-311.pyc,, +websocket/tests/__pycache__/test_ssl_compat.cpython-311.pyc,, +websocket/tests/__pycache__/test_ssl_edge_cases.cpython-311.pyc,, +websocket/tests/__pycache__/test_url.cpython-311.pyc,, +websocket/tests/__pycache__/test_utils.cpython-311.pyc,, +websocket/tests/__pycache__/test_websocket.cpython-311.pyc,, +websocket/tests/data/header01.txt,sha256=eR9UDpnf7mREys9MttKytzB5OXA5IwOGWJZKmaF4II8,163 +websocket/tests/data/header02.txt,sha256=1HzQGIMG0OGwfnboRkUqwbTEg2nTevOX2Waj0gQARaw,161 +websocket/tests/data/header03.txt,sha256=l_soTbfEWjZTLC5Ydx2U8uj8NJ30IwAc8yo5IUG5fyQ,216 +websocket/tests/echo-server.py,sha256=yYwKXimgqo6gHFjGgqhkADb6fRncSrF-OewX6UinZVg,482 +websocket/tests/test_abnf.py,sha256=R4QQVCedzcAs7vFTVzur6m3rn4Y-qeIolHaEhAS3vgU,4629 +websocket/tests/test_app.py,sha256=VL9pdeLxlQrGBnv1yU2roIVHCfNocKn29eqdrgQzWbY,14150 +websocket/tests/test_cookiejar.py,sha256=NDOzlQqGGbE2A5NDaZuEK7Lc7SF39tEVhbG4SIN3SJU,4395 +websocket/tests/test_dispatcher.py,sha256=Pd0cqdhbnsrUgqVDjWMn7x2jgEaOB7oxQndp0ypTmBU,13446 +websocket/tests/test_handshake_large_response.py,sha256=Phpwe_xeeZ-tctGKO6bVTg8N-MUgXhCv95TCYiO8n3I,6165 +websocket/tests/test_http.py,sha256=zbtMX7RGEj7wkgpav82jcqCLPhqA2XIqMgr1MM0TaMQ,12461 +websocket/tests/test_large_payloads.py,sha256=NnhryYBbUpmEXHXCai6Tl47ZC87geL1geqwrS_L5Bqk,10064 +websocket/tests/test_socket.py,sha256=Rbok7KEK87Zvlkopwc2QTx2_ShVQR3KK56RBsYkfPKI,12971 +websocket/tests/test_socket_bugs.py,sha256=TV3ycFYTsw0yDi_AsGWgqiutasbcIAO6V0VhbG5NgcQ,6408 +websocket/tests/test_ssl_compat.py,sha256=N-wKgN_bktOO7N8kSi1-bhRXvzBXtNYxaE3svbidRtA,3467 +websocket/tests/test_ssl_edge_cases.py,sha256=qLV9tYrOoxMXPrM5iE2VssBjEQJS59FggFymXHjBKpI,24932 +websocket/tests/test_url.py,sha256=wwX92RoDY0edDKwyD_Ot3rK24lxtjZ448i1YDWMqqts,18268 +websocket/tests/test_utils.py,sha256=v01GZJ-guDR6LfjuTf6ryZ6bj8Gn7F74_aVdPxcUxJc,5441 +websocket/tests/test_websocket.py,sha256=NRNglZnlRZIryRGxYQdpUGTPk0Ai436wHoA1Ow5YC5k,18430 +websocket_client-1.9.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +websocket_client-1.9.0.dist-info/METADATA,sha256=Kc_Exsui3P2HVxKPiT1p6hP-dZgVPEhUIywgQFpJO7E,8337 +websocket_client-1.9.0.dist-info/RECORD,, +websocket_client-1.9.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +websocket_client-1.9.0.dist-info/entry_points.txt,sha256=IoCGCuANLuLxE3m2QXEd2Ip57qScBjf7RfQnkjn6DNE,50 +websocket_client-1.9.0.dist-info/licenses/LICENSE,sha256=162NCWaqNj1Fx7FrCDjK3NUWdqzfIVrZZzB9WBtHhyw,11339 +websocket_client-1.9.0.dist-info/top_level.txt,sha256=8m_tTpcUlzWGl8v-pj5Wi7XhAFaN1_bLKRHQKCyz5_I,10 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket_client-1.9.0.dist-info/WHEEL b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket_client-1.9.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket_client-1.9.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket_client-1.9.0.dist-info/entry_points.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket_client-1.9.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..45c854eb72e1234e16414525850b6f4314d61ec8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket_client-1.9.0.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +wsdump = websocket._wsdump:main diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket_client-1.9.0.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket_client-1.9.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9ef2a65dc558aa705e4641497bd31b287f873835 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket_client-1.9.0.dist-info/licenses/LICENSE @@ -0,0 +1,203 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2025 engn33r + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket_client-1.9.0.dist-info/top_level.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket_client-1.9.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..ca4cb0cf822783478df41eac79b9c0df7694ef2a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websocket_client-1.9.0.dist-info/top_level.txt @@ -0,0 +1 @@ +websocket diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets-16.0.dist-info/INSTALLER b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets-16.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets-16.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets-16.0.dist-info/METADATA b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets-16.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..bc79b137a56c356b8e644a0c67a5d59bc234d989 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets-16.0.dist-info/METADATA @@ -0,0 +1,179 @@ +Metadata-Version: 2.4 +Name: websockets +Version: 16.0 +Summary: An implementation of the WebSocket Protocol (RFC 6455 & 7692) +Author-email: Aymeric Augustin +License-Expression: BSD-3-Clause +Project-URL: Homepage, https://github.com/python-websockets/websockets +Project-URL: Changelog, https://websockets.readthedocs.io/en/stable/project/changelog.html +Project-URL: Documentation, https://websockets.readthedocs.io/ +Project-URL: Funding, https://tidelift.com/subscription/pkg/pypi-websockets?utm_source=pypi-websockets&utm_medium=referral&utm_campaign=readme +Project-URL: Tracker, https://github.com/python-websockets/websockets/issues +Keywords: WebSocket +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Web Environment +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 +Requires-Python: >=3.10 +Description-Content-Type: text/x-rst +License-File: LICENSE +Dynamic: description +Dynamic: description-content-type +Dynamic: license-file + +.. image:: logo/horizontal.svg + :width: 480px + :alt: websockets + +|licence| |version| |pyversions| |tests| |docs| |openssf| + +.. |licence| image:: https://img.shields.io/pypi/l/websockets.svg + :target: https://pypi.python.org/pypi/websockets + +.. |version| image:: https://img.shields.io/pypi/v/websockets.svg + :target: https://pypi.python.org/pypi/websockets + +.. |pyversions| image:: https://img.shields.io/pypi/pyversions/websockets.svg + :target: https://pypi.python.org/pypi/websockets + +.. |tests| image:: https://img.shields.io/github/checks-status/python-websockets/websockets/main?label=tests + :target: https://github.com/python-websockets/websockets/actions/workflows/tests.yml + +.. |docs| image:: https://img.shields.io/readthedocs/websockets.svg + :target: https://websockets.readthedocs.io/ + +.. |openssf| image:: https://bestpractices.coreinfrastructure.org/projects/6475/badge + :target: https://bestpractices.coreinfrastructure.org/projects/6475 + +What is ``websockets``? +----------------------- + +websockets is a library for building WebSocket_ servers and clients in Python +with a focus on correctness, simplicity, robustness, and performance. + +.. _WebSocket: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API + +Built on top of ``asyncio``, Python's standard asynchronous I/O framework, the +default implementation provides an elegant coroutine-based API. + +An implementation on top of ``threading`` and a Sans-I/O implementation are also +available. + +`Documentation is available on Read the Docs. `_ + +.. copy-pasted because GitHub doesn't support the include directive + +Here's an echo server with the ``asyncio`` API: + +.. code:: python + + #!/usr/bin/env python + + import asyncio + from websockets.asyncio.server import serve + + async def echo(websocket): + async for message in websocket: + await websocket.send(message) + + async def main(): + async with serve(echo, "localhost", 8765) as server: + await server.serve_forever() + + asyncio.run(main()) + +Here's how a client sends and receives messages with the ``threading`` API: + +.. code:: python + + #!/usr/bin/env python + + from websockets.sync.client import connect + + def hello(): + with connect("ws://localhost:8765") as websocket: + websocket.send("Hello world!") + message = websocket.recv() + print(f"Received: {message}") + + hello() + + +Does that look good? + +`Get started with the tutorial! `_ + +Why should I use ``websockets``? +-------------------------------- + +The development of ``websockets`` is shaped by four principles: + +1. **Correctness**: ``websockets`` is heavily tested for compliance with + :rfc:`6455`. Continuous integration fails under 100% branch coverage. + +2. **Simplicity**: all you need to understand is ``msg = await ws.recv()`` and + ``await ws.send(msg)``. ``websockets`` takes care of managing connections + so you can focus on your application. + +3. **Robustness**: ``websockets`` is built for production. For example, it was + the only library to `handle backpressure correctly`_ before the issue + became widely known in the Python community. + +4. **Performance**: memory usage is optimized and configurable. A C extension + accelerates expensive operations. It's pre-compiled for Linux, macOS and + Windows and packaged in the wheel format for each system and Python version. + +Documentation is a first class concern in the project. Head over to `Read the +Docs`_ and see for yourself. + +.. _Read the Docs: https://websockets.readthedocs.io/ +.. _handle backpressure correctly: https://vorpus.org/blog/some-thoughts-on-asynchronous-api-design-in-a-post-asyncawait-world/#websocket-servers + +Why shouldn't I use ``websockets``? +----------------------------------- + +* If you prefer callbacks over coroutines: ``websockets`` was created to + provide the best coroutine-based API to manage WebSocket connections in + Python. Pick another library for a callback-based API. + +* If you're looking for a mixed HTTP / WebSocket library: ``websockets`` aims + at being an excellent implementation of :rfc:`6455`: The WebSocket Protocol + and :rfc:`7692`: Compression Extensions for WebSocket. Its support for HTTP + is minimal — just enough for an HTTP health check. + + If you want to do both in the same server, look at HTTP + WebSocket servers + that build on top of ``websockets`` to support WebSocket connections, like + uvicorn_ or Sanic_. + +.. _uvicorn: https://www.uvicorn.org/ +.. _Sanic: https://sanic.dev/en/ + +What else? +---------- + +Bug reports, patches and suggestions are welcome! + +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 + +For anything else, please open an issue_ or send a `pull request`_. + +.. _issue: https://github.com/python-websockets/websockets/issues/new +.. _pull request: https://github.com/python-websockets/websockets/compare/ + +Participants must uphold the `Contributor Covenant code of conduct`_. + +.. _Contributor Covenant code of conduct: https://github.com/python-websockets/websockets/blob/main/CODE_OF_CONDUCT.md + +``websockets`` is released under the `BSD license`_. + +.. _BSD license: https://github.com/python-websockets/websockets/blob/main/LICENSE diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets-16.0.dist-info/RECORD b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets-16.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..3742a8be0252e22d38b4c5190059b9ad17a74617 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets-16.0.dist-info/RECORD @@ -0,0 +1,108 @@ +../../Scripts/websockets.exe,sha256=SuN3YsqSpSB8R_FqkZy-vH35WHcVNh2vR4uPUK_s5WY,108362 +websockets-16.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +websockets-16.0.dist-info/METADATA,sha256=kYsv44IHZloIc5i1QmfnfJ1kPOdwZBABbJ72qItuMDA,6978 +websockets-16.0.dist-info/RECORD,, +websockets-16.0.dist-info/WHEEL,sha256=JLOMsP7F5qtkAkINx5UnzbFguf8CqZeraV8o04b0I8I,101 +websockets-16.0.dist-info/entry_points.txt,sha256=Dnhn4dm5EsI4ZMAsHldGF6CwBXZrGXnR7cnK2-XR7zY,51 +websockets-16.0.dist-info/licenses/LICENSE,sha256=D0RRSZisognTSC0QIEqK3yqkKW_xV6NqXAki8igGMtM,1538 +websockets-16.0.dist-info/top_level.txt,sha256=CMpdKklxKsvZgCgyltxUWOHibZXZ1uYIVpca9xsQ8Hk,11 +websockets/__init__.py,sha256=gnZ1a8qhrWVVClaf7lGqkSVQAPPm-cSZ3k3525fozaY,7294 +websockets/__main__.py,sha256=h1QpgvR08tO6TfQHuySKKgQiQVXVIoQRKLEx5sVht_M,67 +websockets/__pycache__/__init__.cpython-311.pyc,, +websockets/__pycache__/__main__.cpython-311.pyc,, +websockets/__pycache__/auth.cpython-311.pyc,, +websockets/__pycache__/cli.cpython-311.pyc,, +websockets/__pycache__/client.cpython-311.pyc,, +websockets/__pycache__/connection.cpython-311.pyc,, +websockets/__pycache__/datastructures.cpython-311.pyc,, +websockets/__pycache__/exceptions.cpython-311.pyc,, +websockets/__pycache__/frames.cpython-311.pyc,, +websockets/__pycache__/headers.cpython-311.pyc,, +websockets/__pycache__/http.cpython-311.pyc,, +websockets/__pycache__/http11.cpython-311.pyc,, +websockets/__pycache__/imports.cpython-311.pyc,, +websockets/__pycache__/protocol.cpython-311.pyc,, +websockets/__pycache__/proxy.cpython-311.pyc,, +websockets/__pycache__/server.cpython-311.pyc,, +websockets/__pycache__/streams.cpython-311.pyc,, +websockets/__pycache__/typing.cpython-311.pyc,, +websockets/__pycache__/uri.cpython-311.pyc,, +websockets/__pycache__/utils.cpython-311.pyc,, +websockets/__pycache__/version.cpython-311.pyc,, +websockets/asyncio/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +websockets/asyncio/__pycache__/__init__.cpython-311.pyc,, +websockets/asyncio/__pycache__/async_timeout.cpython-311.pyc,, +websockets/asyncio/__pycache__/client.cpython-311.pyc,, +websockets/asyncio/__pycache__/compatibility.cpython-311.pyc,, +websockets/asyncio/__pycache__/connection.cpython-311.pyc,, +websockets/asyncio/__pycache__/messages.cpython-311.pyc,, +websockets/asyncio/__pycache__/router.cpython-311.pyc,, +websockets/asyncio/__pycache__/server.cpython-311.pyc,, +websockets/asyncio/async_timeout.py,sha256=jMKMQcVKWtn09n6lqefqdpSYoMRlP4Ek60RjJ6B6Eco,9253 +websockets/asyncio/client.py,sha256=tM0I44Ra5o0VNTdHi7-RoX8SDBHZVpGeZ8g9XwGtVGg,31654 +websockets/asyncio/compatibility.py,sha256=ld5lpbBgJ8YGAi3tc1hMiIxuLeQWDg6pKDYBVbSQMl4,816 +websockets/asyncio/connection.py,sha256=RvxZpEfj4CFMM0s2WBi9Q5eGpQ9xxrdlZVZOrUULing,50346 +websockets/asyncio/messages.py,sha256=5pvFEis6dP0xGLmotFZGxoPJ1rl9i7k1s85i_Ha4TrY,11445 +websockets/asyncio/router.py,sha256=98y3YRKtWomjfocLPYz4jGwU6bvL9TN4eAlyvKmUJro,7739 +websockets/asyncio/server.py,sha256=G0cSJSp63u37S7cUPmhEJWPdVil7NFDtCXRzIQVxzFU,38938 +websockets/auth.py,sha256=NZ60zoE10wklboBHzj4Wof9piVB09jO1bDn_KHN8ZcE,586 +websockets/cli.py,sha256=dEUrXN6jOq0-HZbdujpvEHTY2WsATSX2F6czGWNC-58,5514 +websockets/client.py,sha256=He7BIvvTGzYbHmp6H31P64wLgGRIAtp87Cht0wdo_qI,14180 +websockets/connection.py,sha256=uIRi5jeS3zVIWq8DcEDJPousrYNTItPe0ioKxBr2hOs,335 +websockets/datastructures.py,sha256=d7WQmEZTLf5i-_SdER6WM-wH1o7u4Ws2SZAv2wcm-w8,5701 +websockets/exceptions.py,sha256=pyrzbaJrSdmwd0PrUKhYNRfFKWOcWR93RphctQzKNj8,13332 +websockets/extensions/__init__.py,sha256=HdQaQhOVkCR5RJVRKXG5Xmb6cMpAhLaKgRikYRzO64E,102 +websockets/extensions/__pycache__/__init__.cpython-311.pyc,, +websockets/extensions/__pycache__/base.cpython-311.pyc,, +websockets/extensions/__pycache__/permessage_deflate.cpython-311.pyc,, +websockets/extensions/base.py,sha256=Je1VMBHq7_gqq5idsCqMPD87CI6m7zpDSRj_lCL37Rc,3026 +websockets/extensions/permessage_deflate.py,sha256=6u4WGX3_k9SzlHAHSuWLw5hSjzrIH711RsF8NcmzgQs,26469 +websockets/frames.py,sha256=mePRkg6ZKdWvPZOuEdEFVhoHsLuS8Apl-1vQbcj90e0,13320 +websockets/headers.py,sha256=2XFbUE0BzEIftBR2KS2ygeSRIYzPB-a-q35jfdcZ1MA,16632 +websockets/http.py,sha256=pQmdzRiYK_SuiwvXIrP_rsJZAj8tGIol76e_TvsPUrg,679 +websockets/http11.py,sha256=bg6tnz33FEp11yQmMm3DUyMHzo5y9l84hPJmNvymDMs,16057 +websockets/imports.py,sha256=oFdWkxypj_diuqneRuA5OWEXLMQ6pAtj-rKqFU6Pmdg,2895 +websockets/legacy/__init__.py,sha256=VS5mRP7oS3kXCcXX7F3vPULmXPFi4VcyKbnv8Lk18MY,287 +websockets/legacy/__pycache__/__init__.cpython-311.pyc,, +websockets/legacy/__pycache__/auth.cpython-311.pyc,, +websockets/legacy/__pycache__/client.cpython-311.pyc,, +websockets/legacy/__pycache__/exceptions.cpython-311.pyc,, +websockets/legacy/__pycache__/framing.cpython-311.pyc,, +websockets/legacy/__pycache__/handshake.cpython-311.pyc,, +websockets/legacy/__pycache__/http.cpython-311.pyc,, +websockets/legacy/__pycache__/protocol.cpython-311.pyc,, +websockets/legacy/__pycache__/server.cpython-311.pyc,, +websockets/legacy/auth.py,sha256=wILIJE28YsQKmQcWdPMzmdM_0Sw674dqUo2XGqyUvH4,6721 +websockets/legacy/client.py,sha256=p4Iw-r8_0HTl0pnKDxXmzpgdA8EHSUWXWkS4htyCetk,27518 +websockets/legacy/exceptions.py,sha256=KrvUEI31DUZs3gl6M-Q-dgsSnsMXzU_bDRuHU6AcKbc,1995 +websockets/legacy/framing.py,sha256=X4UdahsxzmHaQ96Lc1h1JxYGQmldJ3lQATAIIBPMQ1s,6590 +websockets/legacy/handshake.py,sha256=CRRxkJ96TIgWuoMIL0iol4jp4X7llMA8buX4gfo0SwE,5443 +websockets/legacy/http.py,sha256=OPu_UljFJH74nxk5V-jnOOkqzdXcpJ6M0LynIpuZ740,7262 +websockets/legacy/protocol.py,sha256=OFcAFHJ8pFj74uNGIjbyeqSkUSXJhBwMfxdKFwBJQFA,65267 +websockets/legacy/server.py,sha256=Vaib6rEFl_Xkms8uQObh12u0ndomOiFkOLtNalRg-Vk,46442 +websockets/protocol.py,sha256=rmByeSbZrcEbAI2tuTTvGfKD7Sg7jnvwOuOr_sRtY88,28015 +websockets/proxy.py,sha256=Vx6ChvQlavAZ2DkzlmoEw5I5e7alDqBCISi_xZotAS0,5119 +websockets/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +websockets/server.py,sha256=vQdDh3m2Bkq754OYtC91IdkGwScTFsUexkyJtoq9p40,22379 +websockets/speedups.c,sha256=cWPv8E0JKXSneV8b732dwNEbyD5JWJKzyI5bqmGiXaY,6149 +websockets/speedups.cp311-win_amd64.pyd,sha256=nkU85WuuOvSCId1UMjYjDhp7xzL_TtoH_iKzuz_ESoo,11776 +websockets/speedups.pyi,sha256=xJUwsMLc11sH19lvnxlmuwROSIxzQYdvN3Qt5zS0674,105 +websockets/streams.py,sha256=MXiB2d6mNsARFXdwXqVa2GHqb8wCxm0ncqtxPcdDFok,4222 +websockets/sync/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +websockets/sync/__pycache__/__init__.cpython-311.pyc,, +websockets/sync/__pycache__/client.cpython-311.pyc,, +websockets/sync/__pycache__/connection.cpython-311.pyc,, +websockets/sync/__pycache__/messages.cpython-311.pyc,, +websockets/sync/__pycache__/router.cpython-311.pyc,, +websockets/sync/__pycache__/server.cpython-311.pyc,, +websockets/sync/__pycache__/utils.cpython-311.pyc,, +websockets/sync/client.py,sha256=EOrmXS1WhebA6bsDxeJqOj0-SQjF6Z0Vnp5_DlUpPWE,22741 +websockets/sync/connection.py,sha256=KgDAjXoagnNZ5gXuLEbHxEmsCyqYRMkxI4CD6ZsFaiM,42946 +websockets/sync/messages.py,sha256=DIyybPDUiIzC6-uvSqc3U7FjDO1B6plAMPrZgaQf2d0,13206 +websockets/sync/router.py,sha256=TVsMXN0SIyiP5Sl9NxVC4Ovy-88FPbFQTGQVw5SjOYQ,7385 +websockets/sync/server.py,sha256=RkxGcOmPL9NhzBmjs_jACLG5On8o51ghp2wn3XY_Dzg,28420 +websockets/sync/utils.py,sha256=JgQVxO_NcQXZd8m6hDeXpSQ_uN6GYF8u9XLHZ7msv3k,1152 +websockets/typing.py,sha256=FUGyn9CqzlBNvfCTU0Gm75J0IKYxEFcWRyyKDpGTa6Q,2021 +websockets/uri.py,sha256=gohMr47baKGfjhydsaOE1sc8FH_7B8f10SdunNqY2p0,3232 +websockets/utils.py,sha256=5itk0xHhs78fw5nQwvrzv21uMFR4I13aF1nkz687hMg,1250 +websockets/version.py,sha256=LCt43nUYKAFpXjn8qUUIYqsP2XXsol_Hqb7CoITE1HE,3294 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets-16.0.dist-info/WHEEL b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets-16.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..8f98e0aeebdc2c0a3b9b5f83d43db0ef8dbc186b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets-16.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp311-cp311-win_amd64 + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets-16.0.dist-info/entry_points.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets-16.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..60cd61ca0074591bf4dd607f11ee22310a3daab4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets-16.0.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +websockets = websockets.cli:main diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets-16.0.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets-16.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..737391524fbd8fd489087e9ff3ee1b24c1070e83 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets-16.0.dist-info/licenses/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) Aymeric Augustin and contributors + +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. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets-16.0.dist-info/top_level.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets-16.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..14774b465e97f655dbcaa60d97c8a9aa72e7d51b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets-16.0.dist-info/top_level.txt @@ -0,0 +1 @@ +websockets diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..de677b8f9c0da920e26f9e413c409c9ee4e49e27 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__init__.py @@ -0,0 +1,236 @@ +from __future__ import annotations + +# Importing the typing module would conflict with websockets.typing. +from typing import TYPE_CHECKING + +from .imports import lazy_import +from .version import version as __version__ # noqa: F401 + + +__all__ = [ + # .asyncio.client + "connect", + "unix_connect", + "ClientConnection", + # .asyncio.router + "route", + "unix_route", + "Router", + # .asyncio.server + "basic_auth", + "broadcast", + "serve", + "unix_serve", + "ServerConnection", + "Server", + # .client + "ClientProtocol", + # .datastructures + "Headers", + "HeadersLike", + "MultipleValuesError", + # .exceptions + "ConcurrencyError", + "ConnectionClosed", + "ConnectionClosedError", + "ConnectionClosedOK", + "DuplicateParameter", + "InvalidHandshake", + "InvalidHeader", + "InvalidHeaderFormat", + "InvalidHeaderValue", + "InvalidMessage", + "InvalidOrigin", + "InvalidParameterName", + "InvalidParameterValue", + "InvalidProxy", + "InvalidProxyMessage", + "InvalidProxyStatus", + "InvalidState", + "InvalidStatus", + "InvalidUpgrade", + "InvalidURI", + "NegotiationError", + "PayloadTooBig", + "ProtocolError", + "ProxyError", + "SecurityError", + "WebSocketException", + # .frames + "Close", + "CloseCode", + "Frame", + "Opcode", + # .http11 + "Request", + "Response", + # .protocol + "Protocol", + "Side", + "State", + # .server + "ServerProtocol", + # .typing + "Data", + "ExtensionName", + "ExtensionParameter", + "LoggerLike", + "StatusLike", + "Origin", + "Subprotocol", +] + +# When type checking, import non-deprecated aliases eagerly. Else, import on demand. +if TYPE_CHECKING: + from .asyncio.client import ClientConnection, connect, unix_connect + from .asyncio.router import Router, route, unix_route + from .asyncio.server import ( + Server, + ServerConnection, + basic_auth, + broadcast, + serve, + unix_serve, + ) + from .client import ClientProtocol + from .datastructures import Headers, HeadersLike, MultipleValuesError + from .exceptions import ( + ConcurrencyError, + ConnectionClosed, + ConnectionClosedError, + ConnectionClosedOK, + DuplicateParameter, + InvalidHandshake, + InvalidHeader, + InvalidHeaderFormat, + InvalidHeaderValue, + InvalidMessage, + InvalidOrigin, + InvalidParameterName, + InvalidParameterValue, + InvalidProxy, + InvalidProxyMessage, + InvalidProxyStatus, + InvalidState, + InvalidStatus, + InvalidUpgrade, + InvalidURI, + NegotiationError, + PayloadTooBig, + ProtocolError, + ProxyError, + SecurityError, + WebSocketException, + ) + from .frames import Close, CloseCode, Frame, Opcode + from .http11 import Request, Response + from .protocol import Protocol, Side, State + from .server import ServerProtocol + from .typing import ( + Data, + ExtensionName, + ExtensionParameter, + LoggerLike, + Origin, + StatusLike, + Subprotocol, + ) +else: + lazy_import( + globals(), + aliases={ + # .asyncio.client + "connect": ".asyncio.client", + "unix_connect": ".asyncio.client", + "ClientConnection": ".asyncio.client", + # .asyncio.router + "route": ".asyncio.router", + "unix_route": ".asyncio.router", + "Router": ".asyncio.router", + # .asyncio.server + "basic_auth": ".asyncio.server", + "broadcast": ".asyncio.server", + "serve": ".asyncio.server", + "unix_serve": ".asyncio.server", + "ServerConnection": ".asyncio.server", + "Server": ".asyncio.server", + # .client + "ClientProtocol": ".client", + # .datastructures + "Headers": ".datastructures", + "HeadersLike": ".datastructures", + "MultipleValuesError": ".datastructures", + # .exceptions + "ConcurrencyError": ".exceptions", + "ConnectionClosed": ".exceptions", + "ConnectionClosedError": ".exceptions", + "ConnectionClosedOK": ".exceptions", + "DuplicateParameter": ".exceptions", + "InvalidHandshake": ".exceptions", + "InvalidHeader": ".exceptions", + "InvalidHeaderFormat": ".exceptions", + "InvalidHeaderValue": ".exceptions", + "InvalidMessage": ".exceptions", + "InvalidOrigin": ".exceptions", + "InvalidParameterName": ".exceptions", + "InvalidParameterValue": ".exceptions", + "InvalidProxy": ".exceptions", + "InvalidProxyMessage": ".exceptions", + "InvalidProxyStatus": ".exceptions", + "InvalidState": ".exceptions", + "InvalidStatus": ".exceptions", + "InvalidUpgrade": ".exceptions", + "InvalidURI": ".exceptions", + "NegotiationError": ".exceptions", + "PayloadTooBig": ".exceptions", + "ProtocolError": ".exceptions", + "ProxyError": ".exceptions", + "SecurityError": ".exceptions", + "WebSocketException": ".exceptions", + # .frames + "Close": ".frames", + "CloseCode": ".frames", + "Frame": ".frames", + "Opcode": ".frames", + # .http11 + "Request": ".http11", + "Response": ".http11", + # .protocol + "Protocol": ".protocol", + "Side": ".protocol", + "State": ".protocol", + # .server + "ServerProtocol": ".server", + # .typing + "Data": ".typing", + "ExtensionName": ".typing", + "ExtensionParameter": ".typing", + "LoggerLike": ".typing", + "Origin": ".typing", + "StatusLike": ".typing", + "Subprotocol": ".typing", + }, + deprecated_aliases={ + # deprecated in 9.0 - 2021-09-01 + "framing": ".legacy", + "handshake": ".legacy", + "parse_uri": ".uri", + "WebSocketURI": ".uri", + # deprecated in 14.0 - 2024-11-09 + # .legacy.auth + "BasicAuthWebSocketServerProtocol": ".legacy.auth", + "basic_auth_protocol_factory": ".legacy.auth", + # .legacy.client + "WebSocketClientProtocol": ".legacy.client", + # .legacy.exceptions + "AbortHandshake": ".legacy.exceptions", + "InvalidStatusCode": ".legacy.exceptions", + "RedirectHandshake": ".legacy.exceptions", + "WebSocketProtocolError": ".legacy.exceptions", + # .legacy.protocol + "WebSocketCommonProtocol": ".legacy.protocol", + # .legacy.server + "WebSocketServer": ".legacy.server", + "WebSocketServerProtocol": ".legacy.server", + }, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__main__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..e1cbc62e37e5e4cfdce0525a06ff496936cb6afb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__main__.py @@ -0,0 +1,5 @@ +from .cli import main + + +if __name__ == "__main__": + main() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02a33e2e1a4078ee62030277ff1f482b4f69c5a5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/__main__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/__main__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1474a53510146eee25a2427c3de9a11c6af41589 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/__main__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/auth.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/auth.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d143efb72249001d7e22bd7a75667b6de2bd0105 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/auth.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/cli.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/cli.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ef1e04a7ce34f264af015e6070bdfa22f91327e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/cli.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/client.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/client.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea2ef8fcea93a083c0d6981c343eb7afd804423f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/client.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/connection.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/connection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2825326f3408d91508cfacc82cf4deab0bd2aa02 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/connection.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/datastructures.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/datastructures.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..586b9fc5ba370d690930fe1fef9f9419832e2769 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/datastructures.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/exceptions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/exceptions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b87f1e8f184c4d1cf1ba9d6cc9dcc60ef6a68f7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/exceptions.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/frames.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/frames.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e36a3d7a31e2bb78c27d9c02cb1d8b14accf9818 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/frames.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/headers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/headers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c54d5068844efc534a1855c02aeabfc70a14a7a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/headers.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/http.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/http.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5527a47d0048f7cab30a2d31cd385c189cd10d2e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/http.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/http11.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/http11.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da336892a8f812c3a183f0a81cd1489386c5cc44 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/http11.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/imports.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/imports.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87ba28a52563e8bdd18aa8d27e3ab870513e1e19 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/imports.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/protocol.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/protocol.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a29788b00a540ee51de496cc192c6ac3f5f22a6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/protocol.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/proxy.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/proxy.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ecfc17324341320575dabc62024ea10fb41ba91 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/proxy.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/server.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68b1e097cc7bb318e0252979deba9288570b6748 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/server.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/streams.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/streams.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a61739637b6b2280d0e9471e1af881f1c9ebb37 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/streams.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/typing.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/typing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88bfc80f59272d4351fa1b62e7ab29d61a699079 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/typing.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/uri.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/uri.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e76ce77753fed49d0d3c43b5c786e302a713a113 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/uri.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00bd82bc6ec7ea6e919487ac918363feb1d6b0f5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/version.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9bf6e4a07292207fa17edb74599bbc6e185b61ab Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/__pycache__/version.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1c5d60e5fade876c4742d395dd45fbcc266aa30 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__pycache__/async_timeout.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__pycache__/async_timeout.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..065f48c895bf591a72539566b21254a9bb0517f2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__pycache__/async_timeout.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__pycache__/client.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__pycache__/client.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f50c65cf9327ea02c0a55a2561a8ce14e5312aa4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__pycache__/client.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__pycache__/compatibility.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__pycache__/compatibility.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1bffc57980f18d8de2c7e7052ceb8434948c35d2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__pycache__/compatibility.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__pycache__/connection.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__pycache__/connection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27c3dd20317dd24a605023feaaba20a1896cf44b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__pycache__/connection.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__pycache__/messages.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__pycache__/messages.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef2ce66138b9248ed18d09fadf350d148635cba4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__pycache__/messages.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__pycache__/router.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__pycache__/router.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7e36407d1d5f4cc1b4eacb72adfa9c1bd1b70e5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__pycache__/router.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__pycache__/server.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__pycache__/server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07bcfd7bf73236096b9a444b136f24e03a09b814 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/__pycache__/server.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/async_timeout.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/async_timeout.py new file mode 100644 index 0000000000000000000000000000000000000000..3e5b9a0486861da034d15d5e692831d87f45535a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/async_timeout.py @@ -0,0 +1,282 @@ +# From https://github.com/aio-libs/async-timeout/blob/master/async_timeout/__init__.py +# Licensed under the Apache License (Apache-2.0) + +import asyncio +import enum +import sys +import warnings +from types import TracebackType +from typing import Optional, Type + + +if sys.version_info >= (3, 11): + from typing import final +else: + # From https://github.com/python/typing_extensions/blob/main/src/typing_extensions.py + # Licensed under the Python Software Foundation License (PSF-2.0) + + # @final exists in 3.8+, but we backport it for all versions + # before 3.11 to keep support for the __final__ attribute. + # See https://bugs.python.org/issue46342 + def final(f): + """This decorator can be used to indicate to type checkers that + the decorated method cannot be overridden, and decorated class + cannot be subclassed. For example: + + class Base: + @final + def done(self) -> None: + ... + class Sub(Base): + def done(self) -> None: # Error reported by type checker + ... + @final + class Leaf: + ... + class Other(Leaf): # Error reported by type checker + ... + + There is no runtime checking of these properties. The decorator + sets the ``__final__`` attribute to ``True`` on the decorated object + to allow runtime introspection. + """ + try: + f.__final__ = True + except (AttributeError, TypeError): + # Skip the attribute silently if it is not writable. + # AttributeError happens if the object has __slots__ or a + # read-only property, TypeError if it's a builtin class. + pass + return f + + # End https://github.com/python/typing_extensions/blob/main/src/typing_extensions.py + + +if sys.version_info >= (3, 11): + + def _uncancel_task(task: "asyncio.Task[object]") -> None: + task.uncancel() + +else: + + def _uncancel_task(task: "asyncio.Task[object]") -> None: + pass + + +__version__ = "4.0.3" + + +__all__ = ("timeout", "timeout_at", "Timeout") + + +def timeout(delay: Optional[float]) -> "Timeout": + """timeout context manager. + + Useful in cases when you want to apply timeout logic around block + of code or in cases when asyncio.wait_for is not suitable. For example: + + >>> async with timeout(0.001): + ... async with aiohttp.get('https://github.com') as r: + ... await r.text() + + + delay - value in seconds or None to disable timeout logic + """ + loop = asyncio.get_running_loop() + if delay is not None: + deadline = loop.time() + delay # type: Optional[float] + else: + deadline = None + return Timeout(deadline, loop) + + +def timeout_at(deadline: Optional[float]) -> "Timeout": + """Schedule the timeout at absolute time. + + deadline argument points on the time in the same clock system + as loop.time(). + + Please note: it is not POSIX time but a time with + undefined starting base, e.g. the time of the system power on. + + >>> async with timeout_at(loop.time() + 10): + ... async with aiohttp.get('https://github.com') as r: + ... await r.text() + + + """ + loop = asyncio.get_running_loop() + return Timeout(deadline, loop) + + +class _State(enum.Enum): + INIT = "INIT" + ENTER = "ENTER" + TIMEOUT = "TIMEOUT" + EXIT = "EXIT" + + +@final +class Timeout: + # Internal class, please don't instantiate it directly + # Use timeout() and timeout_at() public factories instead. + # + # Implementation note: `async with timeout()` is preferred + # over `with timeout()`. + # While technically the Timeout class implementation + # doesn't need to be async at all, + # the `async with` statement explicitly points that + # the context manager should be used from async function context. + # + # This design allows to avoid many silly misusages. + # + # TimeoutError is raised immediately when scheduled + # if the deadline is passed. + # The purpose is to time out as soon as possible + # without waiting for the next await expression. + + __slots__ = ("_deadline", "_loop", "_state", "_timeout_handler", "_task") + + def __init__( + self, deadline: Optional[float], loop: asyncio.AbstractEventLoop + ) -> None: + self._loop = loop + self._state = _State.INIT + + self._task: Optional["asyncio.Task[object]"] = None + self._timeout_handler = None # type: Optional[asyncio.Handle] + if deadline is None: + self._deadline = None # type: Optional[float] + else: + self.update(deadline) + + def __enter__(self) -> "Timeout": + warnings.warn( + "with timeout() is deprecated, use async with timeout() instead", + DeprecationWarning, + stacklevel=2, + ) + self._do_enter() + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> Optional[bool]: + self._do_exit(exc_type) + return None + + async def __aenter__(self) -> "Timeout": + self._do_enter() + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> Optional[bool]: + self._do_exit(exc_type) + return None + + @property + def expired(self) -> bool: + """Is timeout expired during execution?""" + return self._state == _State.TIMEOUT + + @property + def deadline(self) -> Optional[float]: + return self._deadline + + def reject(self) -> None: + """Reject scheduled timeout if any.""" + # cancel is maybe better name but + # task.cancel() raises CancelledError in asyncio world. + if self._state not in (_State.INIT, _State.ENTER): + raise RuntimeError(f"invalid state {self._state.value}") + self._reject() + + def _reject(self) -> None: + self._task = None + if self._timeout_handler is not None: + self._timeout_handler.cancel() + self._timeout_handler = None + + def shift(self, delay: float) -> None: + """Advance timeout on delay seconds. + + The delay can be negative. + + Raise RuntimeError if shift is called when deadline is not scheduled + """ + deadline = self._deadline + if deadline is None: + raise RuntimeError("cannot shift timeout if deadline is not scheduled") + self.update(deadline + delay) + + def update(self, deadline: float) -> None: + """Set deadline to absolute value. + + deadline argument points on the time in the same clock system + as loop.time(). + + If new deadline is in the past the timeout is raised immediately. + + Please note: it is not POSIX time but a time with + undefined starting base, e.g. the time of the system power on. + """ + if self._state == _State.EXIT: + raise RuntimeError("cannot reschedule after exit from context manager") + if self._state == _State.TIMEOUT: + raise RuntimeError("cannot reschedule expired timeout") + if self._timeout_handler is not None: + self._timeout_handler.cancel() + self._deadline = deadline + if self._state != _State.INIT: + self._reschedule() + + def _reschedule(self) -> None: + assert self._state == _State.ENTER + deadline = self._deadline + if deadline is None: + return + + now = self._loop.time() + if self._timeout_handler is not None: + self._timeout_handler.cancel() + + self._task = asyncio.current_task() + if deadline <= now: + self._timeout_handler = self._loop.call_soon(self._on_timeout) + else: + self._timeout_handler = self._loop.call_at(deadline, self._on_timeout) + + def _do_enter(self) -> None: + if self._state != _State.INIT: + raise RuntimeError(f"invalid state {self._state.value}") + self._state = _State.ENTER + self._reschedule() + + def _do_exit(self, exc_type: Optional[Type[BaseException]]) -> None: + if exc_type is asyncio.CancelledError and self._state == _State.TIMEOUT: + assert self._task is not None + _uncancel_task(self._task) + self._timeout_handler = None + self._task = None + raise asyncio.TimeoutError + # timeout has not expired + self._state = _State.EXIT + self._reject() + return None + + def _on_timeout(self) -> None: + assert self._task is not None + self._task.cancel() + self._state = _State.TIMEOUT + # drop the reference early + self._timeout_handler = None + + +# End https://github.com/aio-libs/async-timeout/blob/master/async_timeout/__init__.py diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/client.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/client.py new file mode 100644 index 0000000000000000000000000000000000000000..c59345d538182d0b9cb4ef310414b90b6416599e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/client.py @@ -0,0 +1,804 @@ +from __future__ import annotations + +import asyncio +import logging +import os +import socket +import ssl as ssl_module +import traceback +import urllib.parse +from collections.abc import AsyncIterator, Generator, Sequence +from types import TracebackType +from typing import Any, Callable, Literal, cast + +from ..client import ClientProtocol, backoff +from ..datastructures import HeadersLike +from ..exceptions import ( + InvalidMessage, + InvalidProxyMessage, + InvalidProxyStatus, + InvalidStatus, + ProxyError, + SecurityError, +) +from ..extensions.base import ClientExtensionFactory +from ..extensions.permessage_deflate import enable_client_permessage_deflate +from ..headers import validate_subprotocols +from ..http11 import USER_AGENT, Response +from ..protocol import CONNECTING, Event +from ..proxy import Proxy, get_proxy, parse_proxy, prepare_connect_request +from ..streams import StreamReader +from ..typing import LoggerLike, Origin, Subprotocol +from ..uri import WebSocketURI, parse_uri +from .compatibility import TimeoutError, asyncio_timeout +from .connection import Connection + + +__all__ = ["connect", "unix_connect", "ClientConnection"] + +MAX_REDIRECTS = int(os.environ.get("WEBSOCKETS_MAX_REDIRECTS", "10")) + + +class ClientConnection(Connection): + """ + :mod:`asyncio` implementation of a WebSocket client connection. + + :class:`ClientConnection` provides :meth:`recv` and :meth:`send` coroutines + for receiving and sending messages. + + It supports asynchronous iteration to receive messages:: + + async for message in websocket: + await process(message) + + The iterator exits normally when the connection is closed with code + 1000 (OK) or 1001 (going away) or without a close code. It raises a + :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is + closed with any other code. + + The ``ping_interval``, ``ping_timeout``, ``close_timeout``, ``max_queue``, + and ``write_limit`` arguments have the same meaning as in :func:`connect`. + + Args: + protocol: Sans-I/O connection. + + """ + + def __init__( + self, + protocol: ClientProtocol, + *, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + max_queue: int | None | tuple[int | None, int | None] = 16, + write_limit: int | tuple[int, int | None] = 2**15, + ) -> None: + self.protocol: ClientProtocol + super().__init__( + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + write_limit=write_limit, + ) + self.response_rcvd: asyncio.Future[None] = self.loop.create_future() + + async def handshake( + self, + additional_headers: HeadersLike | None = None, + user_agent_header: str | None = USER_AGENT, + ) -> None: + """ + Perform the opening handshake. + + """ + async with self.send_context(expected_state=CONNECTING): + self.request = self.protocol.connect() + if additional_headers is not None: + self.request.headers.update(additional_headers) + if user_agent_header is not None: + self.request.headers.setdefault("User-Agent", user_agent_header) + self.protocol.send_request(self.request) + + await asyncio.wait( + [self.response_rcvd, self.connection_lost_waiter], + return_when=asyncio.FIRST_COMPLETED, + ) + + # self.protocol.handshake_exc is set when the connection is lost before + # receiving a response, when the response cannot be parsed, or when the + # response fails the handshake. + + if self.protocol.handshake_exc is not None: + raise self.protocol.handshake_exc + + def process_event(self, event: Event) -> None: + """ + Process one incoming event. + + """ + # First event - handshake response. + if self.response is None: + assert isinstance(event, Response) + self.response = event + self.response_rcvd.set_result(None) + # Later events - frames. + else: + super().process_event(event) + + +def process_exception(exc: Exception) -> Exception | None: + """ + Determine whether a connection error is retryable or fatal. + + When reconnecting automatically with ``async for ... in connect(...)``, if a + connection attempt fails, :func:`process_exception` is called to determine + whether to retry connecting or to raise the exception. + + This function defines the default behavior, which is to retry on: + + * :exc:`EOFError`, :exc:`OSError`, :exc:`asyncio.TimeoutError`: network + errors; + * :exc:`~websockets.exceptions.InvalidStatus` when the status code is 500, + 502, 503, or 504: server or proxy errors. + + All other exceptions are considered fatal. + + You can change this behavior with the ``process_exception`` argument of + :func:`connect`. + + Return :obj:`None` if the exception is retryable i.e. when the error could + be transient and trying to reconnect with the same parameters could succeed. + The exception will be logged at the ``INFO`` level. + + Return an exception, either ``exc`` or a new exception, if the exception is + fatal i.e. when trying to reconnect will most likely produce the same error. + That exception will be raised, breaking out of the retry loop. + + """ + # This catches python-socks' ProxyConnectionError and ProxyTimeoutError. + # Remove asyncio.TimeoutError when dropping Python < 3.11. + if isinstance(exc, (OSError, TimeoutError, asyncio.TimeoutError)): + return None + if isinstance(exc, InvalidMessage) and isinstance(exc.__cause__, EOFError): + return None + if isinstance(exc, InvalidStatus) and exc.response.status_code in [ + 500, # Internal Server Error + 502, # Bad Gateway + 503, # Service Unavailable + 504, # Gateway Timeout + ]: + return None + return exc + + +# This is spelled in lower case because it's exposed as a callable in the API. +class connect: + """ + Connect to the WebSocket server at ``uri``. + + This coroutine returns a :class:`ClientConnection` instance, which you can + use to send and receive messages. + + :func:`connect` may be used as an asynchronous context manager:: + + from websockets.asyncio.client import connect + + async with connect(...) as websocket: + ... + + The connection is closed automatically when exiting the context. + + :func:`connect` can be used as an infinite asynchronous iterator to + reconnect automatically on errors:: + + async for websocket in connect(...): + try: + ... + except websockets.exceptions.ConnectionClosed: + continue + + If the connection fails with a transient error, it is retried with + exponential backoff. If it fails with a fatal error, the exception is + raised, breaking out of the loop. + + The connection is closed automatically after each iteration of the loop. + + Args: + uri: URI of the WebSocket server. + origin: Value of the ``Origin`` header, for servers that require it. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + compression: The "permessage-deflate" extension is enabled by default. + Set ``compression`` to :obj:`None` to disable it. See the + :doc:`compression guide <../../topics/compression>` for details. + additional_headers (HeadersLike | None): Arbitrary HTTP headers to add + to the handshake request. + user_agent_header: Value of the ``User-Agent`` request header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. + Setting it to :obj:`None` removes the header. + proxy: If a proxy is configured, it is used by default. Set ``proxy`` + to :obj:`None` to disable the proxy or to the address of a proxy + to override the system configuration. See the :doc:`proxy docs + <../../topics/proxies>` for details. + process_exception: When reconnecting automatically, tell whether an + error is transient or fatal. The default behavior is defined by + :func:`process_exception`. Refer to its documentation for details. + open_timeout: Timeout for opening the connection in seconds. + :obj:`None` disables the timeout. + ping_interval: Interval between keepalive pings in seconds. + :obj:`None` disables keepalive. + ping_timeout: Timeout for keepalive pings in seconds. + :obj:`None` disables timeouts. + close_timeout: Timeout for closing the connection in seconds. + :obj:`None` disables the timeout. + max_size: Maximum size of incoming messages in bytes. + :obj:`None` disables the limit. You may pass a ``(max_message_size, + max_fragment_size)`` tuple to set different limits for messages and + fragments when you expect long messages sent in short fragments. + max_queue: High-water mark of the buffer where frames are received. + It defaults to 16 frames. The low-water mark defaults to ``max_queue + // 4``. You may pass a ``(high, low)`` tuple to set the high-water + and low-water marks. If you want to disable flow control entirely, + you may set it to ``None``, although that's a bad idea. + write_limit: High-water mark of write buffer in bytes. It is passed to + :meth:`~asyncio.WriteTransport.set_write_buffer_limits`. It defaults + to 32 KiB. You may pass a ``(high, low)`` tuple to set the + high-water and low-water marks. + logger: Logger for this client. + It defaults to ``logging.getLogger("websockets.client")``. + See the :doc:`logging guide <../../topics/logging>` for details. + create_connection: Factory for the :class:`ClientConnection` managing + the connection. Set it to a wrapper or a subclass to customize + connection handling. + + Any other keyword arguments are passed to the event loop's + :meth:`~asyncio.loop.create_connection` method. + + For example: + + * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enforce TLS settings. + When connecting to a ``wss://`` URI, if ``ssl`` isn't provided, a TLS + context is created with :func:`~ssl.create_default_context`. + + * You can set ``server_hostname`` to override the host name from ``uri`` in + the TLS handshake. + + * You can set ``host`` and ``port`` to connect to a different host and port + from those found in ``uri``. This only changes the destination of the TCP + connection. The host name from ``uri`` is still used in the TLS handshake + for secure connections and in the ``Host`` header. + + * You can set ``sock`` to provide a preexisting TCP socket. You may call + :func:`socket.create_connection` (not to be confused with the event loop's + :meth:`~asyncio.loop.create_connection` method) to create a suitable + client socket and customize it. + + When using a proxy: + + * Prefix keyword arguments with ``proxy_`` for configuring TLS between the + client and an HTTPS proxy: ``proxy_ssl``, ``proxy_server_hostname``, + ``proxy_ssl_handshake_timeout``, and ``proxy_ssl_shutdown_timeout``. + * Use the standard keyword arguments for configuring TLS between the proxy + and the WebSocket server: ``ssl``, ``server_hostname``, + ``ssl_handshake_timeout``, and ``ssl_shutdown_timeout``. + * Other keyword arguments are used only for connecting to the proxy. + + Raises: + InvalidURI: If ``uri`` isn't a valid WebSocket URI. + InvalidProxy: If ``proxy`` isn't a valid proxy. + OSError: If the TCP connection fails. + InvalidHandshake: If the opening handshake fails. + TimeoutError: If the opening handshake times out. + + """ + + def __init__( + self, + uri: str, + *, + # WebSocket + origin: Origin | None = None, + extensions: Sequence[ClientExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + compression: str | None = "deflate", + # HTTP + additional_headers: HeadersLike | None = None, + user_agent_header: str | None = USER_AGENT, + proxy: str | Literal[True] | None = True, + process_exception: Callable[[Exception], Exception | None] = process_exception, + # Timeouts + open_timeout: float | None = 10, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + # Limits + max_size: int | None | tuple[int | None, int | None] = 2**20, + max_queue: int | None | tuple[int | None, int | None] = 16, + write_limit: int | tuple[int, int | None] = 2**15, + # Logging + logger: LoggerLike | None = None, + # Escape hatch for advanced customization + create_connection: type[ClientConnection] | None = None, + # Other keyword arguments are passed to loop.create_connection + **kwargs: Any, + ) -> None: + self.uri = uri + + if subprotocols is not None: + validate_subprotocols(subprotocols) + + if compression == "deflate": + extensions = enable_client_permessage_deflate(extensions) + elif compression is not None: + raise ValueError(f"unsupported compression: {compression}") + + if logger is None: + logger = logging.getLogger("websockets.client") + + if create_connection is None: + create_connection = ClientConnection + + def protocol_factory(uri: WebSocketURI) -> ClientConnection: + # This is a protocol in the Sans-I/O implementation of websockets. + protocol = ClientProtocol( + uri, + origin=origin, + extensions=extensions, + subprotocols=subprotocols, + max_size=max_size, + logger=logger, + ) + # This is a connection in websockets and a protocol in asyncio. + connection = create_connection( + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + write_limit=write_limit, + ) + return connection + + self.proxy = proxy + self.protocol_factory = protocol_factory + self.additional_headers = additional_headers + self.user_agent_header = user_agent_header + self.process_exception = process_exception + self.open_timeout = open_timeout + self.logger = logger + self.connection_kwargs = kwargs + + async def create_connection(self) -> ClientConnection: + """Create TCP or Unix connection.""" + loop = asyncio.get_running_loop() + kwargs = self.connection_kwargs.copy() + + ws_uri = parse_uri(self.uri) + + proxy = self.proxy + if kwargs.get("unix", False): + proxy = None + if kwargs.get("sock") is not None: + proxy = None + if proxy is True: + proxy = get_proxy(ws_uri) + + def factory() -> ClientConnection: + return self.protocol_factory(ws_uri) + + if ws_uri.secure: + kwargs.setdefault("ssl", True) + kwargs.setdefault("server_hostname", ws_uri.host) + if kwargs.get("ssl") is None: + raise ValueError("ssl=None is incompatible with a wss:// URI") + else: + if kwargs.get("ssl") is not None: + raise ValueError("ssl argument is incompatible with a ws:// URI") + + if kwargs.pop("unix", False): + _, connection = await loop.create_unix_connection(factory, **kwargs) + elif proxy is not None: + proxy_parsed = parse_proxy(proxy) + if proxy_parsed.scheme[:5] == "socks": + # Connect to the server through the proxy. + sock = await connect_socks_proxy( + proxy_parsed, + ws_uri, + local_addr=kwargs.pop("local_addr", None), + ) + # Initialize WebSocket connection via the proxy. + _, connection = await loop.create_connection( + factory, + sock=sock, + **kwargs, + ) + elif proxy_parsed.scheme[:4] == "http": + # Split keyword arguments between the proxy and the server. + all_kwargs, proxy_kwargs, kwargs = kwargs, {}, {} + for key, value in all_kwargs.items(): + if key.startswith("ssl") or key == "server_hostname": + kwargs[key] = value + elif key.startswith("proxy_"): + proxy_kwargs[key[6:]] = value + else: + proxy_kwargs[key] = value + # Validate the proxy_ssl argument. + if proxy_parsed.scheme == "https": + proxy_kwargs.setdefault("ssl", True) + if proxy_kwargs.get("ssl") is None: + raise ValueError( + "proxy_ssl=None is incompatible with an https:// proxy" + ) + else: + if proxy_kwargs.get("ssl") is not None: + raise ValueError( + "proxy_ssl argument is incompatible with an http:// proxy" + ) + # Connect to the server through the proxy. + transport = await connect_http_proxy( + proxy_parsed, + ws_uri, + user_agent_header=self.user_agent_header, + **proxy_kwargs, + ) + # Initialize WebSocket connection via the proxy. + connection = factory() + transport.set_protocol(connection) + ssl = kwargs.pop("ssl", None) + if ssl is True: + ssl = ssl_module.create_default_context() + if ssl is not None: + new_transport = await loop.start_tls( + transport, connection, ssl, **kwargs + ) + assert new_transport is not None # help mypy + transport = new_transport + connection.connection_made(transport) + else: + raise AssertionError("unsupported proxy") + else: + # Connect to the server directly. + if kwargs.get("sock") is None: + kwargs.setdefault("host", ws_uri.host) + kwargs.setdefault("port", ws_uri.port) + # Initialize WebSocket connection. + _, connection = await loop.create_connection(factory, **kwargs) + return connection + + def process_redirect(self, exc: Exception) -> Exception | str: + """ + Determine whether a connection error is a redirect that can be followed. + + Return the new URI if it's a valid redirect. Else, return an exception. + + """ + if not ( + isinstance(exc, InvalidStatus) + and exc.response.status_code + in [ + 300, # Multiple Choices + 301, # Moved Permanently + 302, # Found + 303, # See Other + 307, # Temporary Redirect + 308, # Permanent Redirect + ] + and "Location" in exc.response.headers + ): + return exc + + old_ws_uri = parse_uri(self.uri) + new_uri = urllib.parse.urljoin(self.uri, exc.response.headers["Location"]) + new_ws_uri = parse_uri(new_uri) + + # If connect() received a socket, it is closed and cannot be reused. + if self.connection_kwargs.get("sock") is not None: + return ValueError( + f"cannot follow redirect to {new_uri} with a preexisting socket" + ) + + # TLS downgrade is forbidden. + if old_ws_uri.secure and not new_ws_uri.secure: + return SecurityError(f"cannot follow redirect to non-secure URI {new_uri}") + + # Apply restrictions to cross-origin redirects. + if ( + old_ws_uri.secure != new_ws_uri.secure + or old_ws_uri.host != new_ws_uri.host + or old_ws_uri.port != new_ws_uri.port + ): + # Cross-origin redirects on Unix sockets don't quite make sense. + if self.connection_kwargs.get("unix", False): + return ValueError( + f"cannot follow cross-origin redirect to {new_uri} " + f"with a Unix socket" + ) + + # Cross-origin redirects when host and port are overridden are ill-defined. + if ( + self.connection_kwargs.get("host") is not None + or self.connection_kwargs.get("port") is not None + ): + return ValueError( + f"cannot follow cross-origin redirect to {new_uri} " + f"with an explicit host or port" + ) + + return new_uri + + # ... = await connect(...) + + def __await__(self) -> Generator[Any, None, ClientConnection]: + # Create a suitable iterator by calling __await__ on a coroutine. + return self.__await_impl__().__await__() + + async def __await_impl__(self) -> ClientConnection: + try: + async with asyncio_timeout(self.open_timeout): + for _ in range(MAX_REDIRECTS): + self.connection = await self.create_connection() + try: + await self.connection.handshake( + self.additional_headers, + self.user_agent_header, + ) + except asyncio.CancelledError: + self.connection.transport.abort() + raise + except Exception as exc: + # Always close the connection even though keep-alive is + # the default in HTTP/1.1 because create_connection ties + # opening the network connection with initializing the + # protocol. In the current design of connect(), there is + # no easy way to reuse the network connection that works + # in every case nor to reinitialize the protocol. + self.connection.transport.abort() + + uri_or_exc = self.process_redirect(exc) + # Response is a valid redirect; follow it. + if isinstance(uri_or_exc, str): + self.uri = uri_or_exc + continue + # Response isn't a valid redirect; raise the exception. + if uri_or_exc is exc: + raise + else: + raise uri_or_exc from exc + + else: + self.connection.start_keepalive() + return self.connection + else: + raise SecurityError(f"more than {MAX_REDIRECTS} redirects") + + except TimeoutError as exc: + # Re-raise exception with an informative error message. + raise TimeoutError("timed out during opening handshake") from exc + + # ... = yield from connect(...) - remove when dropping Python < 3.11 + + __iter__ = __await__ + + # async with connect(...) as ...: ... + + async def __aenter__(self) -> ClientConnection: + return await self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + await self.connection.close() + + # async for ... in connect(...): + + async def __aiter__(self) -> AsyncIterator[ClientConnection]: + delays: Generator[float] | None = None + while True: + try: + async with self as protocol: + yield protocol + except Exception as exc: + # Determine whether the exception is retryable or fatal. + # The API of process_exception is "return an exception or None"; + # "raise an exception" is also supported because it's a frequent + # mistake. It isn't documented in order to keep the API simple. + try: + new_exc = self.process_exception(exc) + except Exception as raised_exc: + new_exc = raised_exc + + # The connection failed with a fatal error. + # Raise the exception and exit the loop. + if new_exc is exc: + raise + if new_exc is not None: + raise new_exc from exc + + # The connection failed with a retryable error. + # Start or continue backoff and reconnect. + if delays is None: + delays = backoff() + delay = next(delays) + self.logger.info( + "connect failed; reconnecting in %.1f seconds: %s", + delay, + traceback.format_exception_only(exc)[0].strip(), + ) + await asyncio.sleep(delay) + continue + + else: + # The connection succeeded. Reset backoff. + delays = None + + +def unix_connect( + path: str | None = None, + uri: str | None = None, + **kwargs: Any, +) -> connect: + """ + Connect to a WebSocket server listening on a Unix socket. + + This function accepts the same keyword arguments as :func:`connect`. + + It's only available on Unix. + + It's mainly useful for debugging servers listening on Unix sockets. + + Args: + path: File system path to the Unix socket. + uri: URI of the WebSocket server. ``uri`` defaults to + ``ws://localhost/`` or, when a ``ssl`` argument is provided, to + ``wss://localhost/``. + + """ + if uri is None: + if kwargs.get("ssl") is None: + uri = "ws://localhost/" + else: + uri = "wss://localhost/" + return connect(uri=uri, unix=True, path=path, **kwargs) + + +try: + from python_socks import ProxyType + from python_socks.async_.asyncio import Proxy as SocksProxy + +except ImportError: + + async def connect_socks_proxy( + proxy: Proxy, + ws_uri: WebSocketURI, + **kwargs: Any, + ) -> socket.socket: + raise ImportError("connecting through a SOCKS proxy requires python-socks") + +else: + SOCKS_PROXY_TYPES = { + "socks5h": ProxyType.SOCKS5, + "socks5": ProxyType.SOCKS5, + "socks4a": ProxyType.SOCKS4, + "socks4": ProxyType.SOCKS4, + } + + SOCKS_PROXY_RDNS = { + "socks5h": True, + "socks5": False, + "socks4a": True, + "socks4": False, + } + + async def connect_socks_proxy( + proxy: Proxy, + ws_uri: WebSocketURI, + **kwargs: Any, + ) -> socket.socket: + """Connect via a SOCKS proxy and return the socket.""" + socks_proxy = SocksProxy( + SOCKS_PROXY_TYPES[proxy.scheme], + proxy.host, + proxy.port, + proxy.username, + proxy.password, + SOCKS_PROXY_RDNS[proxy.scheme], + ) + # connect() is documented to raise OSError. + # socks_proxy.connect() doesn't raise TimeoutError; it gets canceled. + # Wrap other exceptions in ProxyError, a subclass of InvalidHandshake. + try: + return await socks_proxy.connect(ws_uri.host, ws_uri.port, **kwargs) + except OSError: + raise + except Exception as exc: + raise ProxyError("failed to connect to SOCKS proxy") from exc + + +class HTTPProxyConnection(asyncio.Protocol): + def __init__( + self, + ws_uri: WebSocketURI, + proxy: Proxy, + user_agent_header: str | None = None, + ): + self.ws_uri = ws_uri + self.proxy = proxy + self.user_agent_header = user_agent_header + + self.reader = StreamReader() + self.parser = Response.parse( + self.reader.read_line, + self.reader.read_exact, + self.reader.read_to_eof, + proxy=True, + ) + + loop = asyncio.get_running_loop() + self.response: asyncio.Future[Response] = loop.create_future() + + def run_parser(self) -> None: + try: + next(self.parser) + except StopIteration as exc: + response = exc.value + if 200 <= response.status_code < 300: + self.response.set_result(response) + else: + self.response.set_exception(InvalidProxyStatus(response)) + except Exception as exc: + proxy_exc = InvalidProxyMessage( + "did not receive a valid HTTP response from proxy" + ) + proxy_exc.__cause__ = exc + self.response.set_exception(proxy_exc) + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + transport = cast(asyncio.Transport, transport) + self.transport = transport + self.transport.write( + prepare_connect_request(self.proxy, self.ws_uri, self.user_agent_header) + ) + + def data_received(self, data: bytes) -> None: + self.reader.feed_data(data) + self.run_parser() + + def eof_received(self) -> None: + self.reader.feed_eof() + self.run_parser() + + def connection_lost(self, exc: Exception | None) -> None: + self.reader.feed_eof() + if exc is not None: + self.response.set_exception(exc) + + +async def connect_http_proxy( + proxy: Proxy, + ws_uri: WebSocketURI, + user_agent_header: str | None = None, + **kwargs: Any, +) -> asyncio.Transport: + transport, protocol = await asyncio.get_running_loop().create_connection( + lambda: HTTPProxyConnection(ws_uri, proxy, user_agent_header), + proxy.host, + proxy.port, + **kwargs, + ) + + try: + # This raises exceptions if the connection to the proxy fails. + await protocol.response + except Exception: + transport.close() + raise + + return transport diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/compatibility.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/compatibility.py new file mode 100644 index 0000000000000000000000000000000000000000..cd3f93891a5893d6a96979e54b3b80cf83d35b12 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/compatibility.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +import sys + + +__all__ = ["TimeoutError", "aiter", "anext", "asyncio_timeout", "asyncio_timeout_at"] + + +if sys.version_info[:2] >= (3, 11): + TimeoutError = TimeoutError + aiter = aiter + anext = anext + from asyncio import ( + timeout as asyncio_timeout, # noqa: F401 + timeout_at as asyncio_timeout_at, # noqa: F401 + ) + +else: # Python < 3.11 + from asyncio import TimeoutError + + def aiter(async_iterable): + return type(async_iterable).__aiter__(async_iterable) + + async def anext(async_iterator): + return await type(async_iterator).__anext__(async_iterator) + + from .async_timeout import ( + timeout as asyncio_timeout, # noqa: F401 + timeout_at as asyncio_timeout_at, # noqa: F401 + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/connection.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..bae9f62ab5b7f36f194f8d34d7ccd61287b52874 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/connection.py @@ -0,0 +1,1247 @@ +from __future__ import annotations + +import asyncio +import collections +import contextlib +import logging +import random +import struct +import sys +import traceback +import uuid +from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Iterable, Mapping +from types import TracebackType +from typing import Any, Literal, cast, overload + +from ..exceptions import ( + ConcurrencyError, + ConnectionClosed, + ConnectionClosedOK, + ProtocolError, +) +from ..frames import DATA_OPCODES, CloseCode, Frame, Opcode +from ..http11 import Request, Response +from ..protocol import CLOSED, OPEN, Event, Protocol, State +from ..typing import BytesLike, Data, DataLike, LoggerLike, Subprotocol +from .compatibility import ( + TimeoutError, + aiter, + anext, + asyncio_timeout, + asyncio_timeout_at, +) +from .messages import Assembler + + +__all__ = ["Connection"] + + +class Connection(asyncio.Protocol): + """ + :mod:`asyncio` implementation of a WebSocket connection. + + :class:`Connection` provides APIs shared between WebSocket servers and + clients. + + You shouldn't use it directly. Instead, use + :class:`~websockets.asyncio.client.ClientConnection` or + :class:`~websockets.asyncio.server.ServerConnection`. + + """ + + def __init__( + self, + protocol: Protocol, + *, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + max_queue: int | None | tuple[int | None, int | None] = 16, + write_limit: int | tuple[int, int | None] = 2**15, + ) -> None: + self.protocol = protocol + self.ping_interval = ping_interval + self.ping_timeout = ping_timeout + self.close_timeout = close_timeout + if isinstance(max_queue, int) or max_queue is None: + self.max_queue_high, self.max_queue_low = max_queue, None + else: + self.max_queue_high, self.max_queue_low = max_queue + if isinstance(write_limit, int): + self.write_limit_high, self.write_limit_low = write_limit, None + else: + self.write_limit_high, self.write_limit_low = write_limit + + # Inject reference to this instance in the protocol's logger. + self.protocol.logger = logging.LoggerAdapter( + self.protocol.logger, + {"websocket": self}, + ) + + # Copy attributes from the protocol for convenience. + self.id: uuid.UUID = self.protocol.id + """Unique identifier of the connection. Useful in logs.""" + self.logger: LoggerLike = self.protocol.logger + """Logger for this connection.""" + self.debug = self.protocol.debug + + # HTTP handshake request and response. + self.request: Request | None = None + """Opening handshake request.""" + self.response: Response | None = None + """Opening handshake response.""" + + # Event loop running this connection. + self.loop = asyncio.get_running_loop() + + # Assembler turning frames into messages and serializing reads. + self.recv_messages: Assembler # initialized in connection_made + + # Deadline for the closing handshake. + self.close_deadline: float | None = None + + # Whether we are busy sending a fragmented message. + self.send_in_progress: asyncio.Future[None] | None = None + + # Mapping of ping IDs to pong waiters, in chronological order. + self.pending_pings: dict[bytes, tuple[asyncio.Future[float], float]] = {} + + self.latency: float = 0.0 + """ + Latency of the connection, in seconds. + + Latency is defined as the round-trip time of the connection. It is + measured by sending a Ping frame and waiting for a matching Pong frame. + Before the first measurement, :attr:`latency` is ``0.0``. + + By default, websockets enables a :ref:`keepalive ` mechanism + that sends Ping frames automatically at regular intervals. You can also + send Ping frames and measure latency with :meth:`ping`. + """ + + # Task that sends keepalive pings. None when ping_interval is None. + self.keepalive_task: asyncio.Task[None] | None = None + + # Exception raised while reading from the connection, to be chained to + # ConnectionClosed in order to show why the TCP connection dropped. + self.recv_exc: BaseException | None = None + + # Completed when the TCP connection is closed and the WebSocket + # connection state becomes CLOSED. + self.connection_lost_waiter: asyncio.Future[None] = self.loop.create_future() + + # Adapted from asyncio.FlowControlMixin. + self.paused: bool = False + self.drain_waiters: collections.deque[asyncio.Future[None]] = ( + collections.deque() + ) + + # Public attributes + + @property + def local_address(self) -> Any: + """ + Local address of the connection. + + For IPv4 connections, this is a ``(host, port)`` tuple. + + The format of the address depends on the address family. + See :meth:`~socket.socket.getsockname`. + + """ + return self.transport.get_extra_info("sockname") + + @property + def remote_address(self) -> Any: + """ + Remote address of the connection. + + For IPv4 connections, this is a ``(host, port)`` tuple. + + The format of the address depends on the address family. + See :meth:`~socket.socket.getpeername`. + + """ + return self.transport.get_extra_info("peername") + + @property + def state(self) -> State: + """ + State of the WebSocket connection, defined in :rfc:`6455`. + + This attribute is provided for completeness. Typical applications + shouldn't check its value. Instead, they should call :meth:`~recv` or + :meth:`send` and handle :exc:`~websockets.exceptions.ConnectionClosed` + exceptions. + + """ + return self.protocol.state + + @property + def subprotocol(self) -> Subprotocol | None: + """ + Subprotocol negotiated during the opening handshake. + + :obj:`None` if no subprotocol was negotiated. + + """ + return self.protocol.subprotocol + + @property + def close_code(self) -> int | None: + """ + State of the WebSocket connection, defined in :rfc:`6455`. + + This attribute is provided for completeness. Typical applications + shouldn't check its value. Instead, they should inspect attributes + of :exc:`~websockets.exceptions.ConnectionClosed` exceptions. + + """ + return self.protocol.close_code + + @property + def close_reason(self) -> str | None: + """ + State of the WebSocket connection, defined in :rfc:`6455`. + + This attribute is provided for completeness. Typical applications + shouldn't check its value. Instead, they should inspect attributes + of :exc:`~websockets.exceptions.ConnectionClosed` exceptions. + + """ + return self.protocol.close_reason + + # Public methods + + async def __aenter__(self) -> Connection: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + if exc_type is None: + await self.close() + else: + await self.close(CloseCode.INTERNAL_ERROR) + + async def __aiter__(self) -> AsyncIterator[Data]: + """ + Iterate on incoming messages. + + The iterator calls :meth:`recv` and yields messages asynchronously in an + infinite loop. + + It exits when the connection is closed normally. It raises a + :exc:`~websockets.exceptions.ConnectionClosedError` exception after a + protocol error or a network failure. + + """ + try: + while True: + yield await self.recv() + except ConnectionClosedOK: + return + + @overload + async def recv(self, decode: Literal[True]) -> str: ... + + @overload + async def recv(self, decode: Literal[False]) -> bytes: ... + + @overload + async def recv(self, decode: bool | None = None) -> Data: ... + + async def recv(self, decode: bool | None = None) -> Data: + """ + Receive the next message. + + When the connection is closed, :meth:`recv` raises + :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises + :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal closure + and :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol + error or a network failure. This is how you detect the end of the + message stream. + + Canceling :meth:`recv` is safe. There's no risk of losing data. The next + invocation of :meth:`recv` will return the next message. + + This makes it possible to enforce a timeout by wrapping :meth:`recv` in + :func:`~asyncio.timeout` or :func:`~asyncio.wait_for`. + + When the message is fragmented, :meth:`recv` waits until all fragments + are received, reassembles them, and returns the whole message. + + Args: + decode: Set this flag to override the default behavior of returning + :class:`str` or :class:`bytes`. See below for details. + + Returns: + A string (:class:`str`) for a Text_ frame or a bytestring + (:class:`bytes`) for a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + You may override this behavior with the ``decode`` argument: + + * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames and + return a bytestring (:class:`bytes`). This improves performance + when decoding isn't needed, for example if the message contains + JSON and you're using a JSON library that expects a bytestring. + * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames and + return strings (:class:`str`). This may be useful for servers that + send binary frames instead of text frames. + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If two coroutines call :meth:`recv` or + :meth:`recv_streaming` concurrently. + + """ + try: + return await self.recv_messages.get(decode) + except EOFError: + pass + # fallthrough + except ConcurrencyError: + raise ConcurrencyError( + "cannot call recv while another coroutine " + "is already running recv or recv_streaming" + ) from None + except UnicodeDecodeError as exc: + async with self.send_context(): + self.protocol.fail( + CloseCode.INVALID_DATA, + f"{exc.reason} at position {exc.start}", + ) + # fallthrough + + # Wait for the protocol state to be CLOSED before accessing close_exc. + await asyncio.shield(self.connection_lost_waiter) + raise self.protocol.close_exc from self.recv_exc + + @overload + def recv_streaming(self, decode: Literal[True]) -> AsyncIterator[str]: ... + + @overload + def recv_streaming(self, decode: Literal[False]) -> AsyncIterator[bytes]: ... + + @overload + def recv_streaming(self, decode: bool | None = None) -> AsyncIterator[Data]: ... + + async def recv_streaming(self, decode: bool | None = None) -> AsyncIterator[Data]: + """ + Receive the next message frame by frame. + + This method is designed for receiving fragmented messages. It returns an + asynchronous iterator that yields each fragment as it is received. This + iterator must be fully consumed. Else, future calls to :meth:`recv` or + :meth:`recv_streaming` will raise + :exc:`~websockets.exceptions.ConcurrencyError`, making the connection + unusable. + + :meth:`recv_streaming` raises the same exceptions as :meth:`recv`. + + Canceling :meth:`recv_streaming` before receiving the first frame is + safe. Canceling it after receiving one or more frames leaves the + iterator in a partially consumed state, making the connection unusable. + Instead, you should close the connection with :meth:`close`. + + Args: + decode: Set this flag to override the default behavior of returning + :class:`str` or :class:`bytes`. See below for details. + + Returns: + An iterator of strings (:class:`str`) for a Text_ frame or + bytestrings (:class:`bytes`) for a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + You may override this behavior with the ``decode`` argument: + + * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames and + yield bytestrings (:class:`bytes`). This improves performance + when decoding isn't needed. + * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames and + yield strings (:class:`str`). This may be useful for servers that + send binary frames instead of text frames. + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If two coroutines call :meth:`recv` or + :meth:`recv_streaming` concurrently. + + """ + try: + async for frame in self.recv_messages.get_iter(decode): + yield frame + return + except EOFError: + pass + # fallthrough + except ConcurrencyError: + raise ConcurrencyError( + "cannot call recv_streaming while another coroutine " + "is already running recv or recv_streaming" + ) from None + except UnicodeDecodeError as exc: + async with self.send_context(): + self.protocol.fail( + CloseCode.INVALID_DATA, + f"{exc.reason} at position {exc.start}", + ) + # fallthrough + + # Wait for the protocol state to be CLOSED before accessing close_exc. + await asyncio.shield(self.connection_lost_waiter) + raise self.protocol.close_exc from self.recv_exc + + async def send( + self, + message: DataLike | Iterable[DataLike] | AsyncIterable[DataLike], + text: bool | None = None, + ) -> None: + """ + Send a message. + + A string (:class:`str`) is sent as a Text_ frame. A bytestring or + bytes-like object (:class:`bytes`, :class:`bytearray`, or + :class:`memoryview`) is sent as a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + You may override this behavior with the ``text`` argument: + + * Set ``text=True`` to send an UTF-8 bytestring or bytes-like object + (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) in a + Text_ frame. This improves performance when the message is already + UTF-8 encoded, for example if the message contains JSON and you're + using a JSON library that produces a bytestring. + * Set ``text=False`` to send a string (:class:`str`) in a Binary_ + frame. This may be useful for servers that expect binary frames + instead of text frames. + + :meth:`send` also accepts an iterable or asynchronous iterable of + strings, bytestrings, or bytes-like objects to enable fragmentation_. + Each item is treated as a message fragment and sent in its own frame. + All items must be of the same type, or else :meth:`send` will raise a + :exc:`TypeError` and the connection will be closed. + + .. _fragmentation: https://datatracker.ietf.org/doc/html/rfc6455#section-5.4 + + :meth:`send` rejects dict-like objects because this is often an error. + (If you really want to send the keys of a dict-like object as fragments, + call its :meth:`~dict.keys` method and pass the result to :meth:`send`.) + + Canceling :meth:`send` is discouraged. Instead, you should close the + connection with :meth:`close`. Indeed, there are only two situations + where :meth:`send` may yield control to the event loop and then get + canceled; in both cases, :meth:`close` has the same effect and the + effect is more obvious: + + 1. The write buffer is full. If you don't want to wait until enough + data is sent, your only alternative is to close the connection. + :meth:`close` will likely time out then abort the TCP connection. + 2. ``message`` is an asynchronous iterator that yields control. + Stopping in the middle of a fragmented message will cause a + protocol error and the connection will be closed. + + When the connection is closed, :meth:`send` raises + :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it + raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal + connection closure and + :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol + error or a network failure. + + Args: + message: Message to send. + + Raises: + ConnectionClosed: When the connection is closed. + TypeError: If ``message`` doesn't have a supported type. + + """ + # While sending a fragmented message, prevent sending other messages + # until all fragments are sent. + while self.send_in_progress is not None: + await asyncio.shield(self.send_in_progress) + + # Unfragmented message -- this case must be handled first because + # strings and bytes-like objects are iterable. + + if isinstance(message, str): + async with self.send_context(): + if text is False: + self.protocol.send_binary(message.encode()) + else: + self.protocol.send_text(message.encode()) + + elif isinstance(message, BytesLike): + async with self.send_context(): + if text is True: + self.protocol.send_text(message) + else: + self.protocol.send_binary(message) + + # Catch a common mistake -- passing a dict to send(). + + elif isinstance(message, Mapping): + raise TypeError("data is a dict-like object") + + # Fragmented message -- regular iterator. + + elif isinstance(message, Iterable): + chunks = iter(message) + try: + chunk = next(chunks) + except StopIteration: + return + + assert self.send_in_progress is None + self.send_in_progress = self.loop.create_future() + try: + # First fragment. + if isinstance(chunk, str): + async with self.send_context(): + if text is False: + self.protocol.send_binary(chunk.encode(), fin=False) + else: + self.protocol.send_text(chunk.encode(), fin=False) + encode = True + elif isinstance(chunk, BytesLike): + async with self.send_context(): + if text is True: + self.protocol.send_text(chunk, fin=False) + else: + self.protocol.send_binary(chunk, fin=False) + encode = False + else: + raise TypeError("iterable must contain bytes or str") + + # Other fragments + for chunk in chunks: + if isinstance(chunk, str) and encode: + async with self.send_context(): + self.protocol.send_continuation(chunk.encode(), fin=False) + elif isinstance(chunk, BytesLike) and not encode: + async with self.send_context(): + self.protocol.send_continuation(chunk, fin=False) + else: + raise TypeError("iterable must contain uniform types") + + # Final fragment. + async with self.send_context(): + self.protocol.send_continuation(b"", fin=True) + + except Exception: + # We're half-way through a fragmented message and we can't + # complete it. This makes the connection unusable. + async with self.send_context(): + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "error in fragmented message", + ) + raise + + finally: + self.send_in_progress.set_result(None) + self.send_in_progress = None + + # Fragmented message -- async iterator. + + elif isinstance(message, AsyncIterable): + achunks = aiter(message) + try: + chunk = await anext(achunks) + except StopAsyncIteration: + return + + assert self.send_in_progress is None + self.send_in_progress = self.loop.create_future() + try: + # First fragment. + if isinstance(chunk, str): + if text is False: + async with self.send_context(): + self.protocol.send_binary(chunk.encode(), fin=False) + else: + async with self.send_context(): + self.protocol.send_text(chunk.encode(), fin=False) + encode = True + elif isinstance(chunk, BytesLike): + if text is True: + async with self.send_context(): + self.protocol.send_text(chunk, fin=False) + else: + async with self.send_context(): + self.protocol.send_binary(chunk, fin=False) + encode = False + else: + raise TypeError("async iterable must contain bytes or str") + + # Other fragments + async for chunk in achunks: + if isinstance(chunk, str) and encode: + async with self.send_context(): + self.protocol.send_continuation(chunk.encode(), fin=False) + elif isinstance(chunk, BytesLike) and not encode: + async with self.send_context(): + self.protocol.send_continuation(chunk, fin=False) + else: + raise TypeError("async iterable must contain uniform types") + + # Final fragment. + async with self.send_context(): + self.protocol.send_continuation(b"", fin=True) + + except Exception: + # We're half-way through a fragmented message and we can't + # complete it. This makes the connection unusable. + async with self.send_context(): + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "error in fragmented message", + ) + raise + + finally: + self.send_in_progress.set_result(None) + self.send_in_progress = None + + else: + raise TypeError("data must be str, bytes, iterable, or async iterable") + + async def close( + self, + code: CloseCode | int = CloseCode.NORMAL_CLOSURE, + reason: str = "", + ) -> None: + """ + Perform the closing handshake. + + :meth:`close` waits for the other end to complete the handshake and + for the TCP connection to terminate. + + :meth:`close` is idempotent: it doesn't do anything once the + connection is closed. + + Args: + code: WebSocket close code. + reason: WebSocket close reason. + + """ + try: + # The context manager takes care of waiting for the TCP connection + # to terminate after calling a method that sends a close frame. + async with self.send_context(): + if self.send_in_progress is not None: + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "close during fragmented message", + ) + else: + self.protocol.send_close(code, reason) + except ConnectionClosed: + # Ignore ConnectionClosed exceptions raised from send_context(). + # They mean that the connection is closed, which was the goal. + pass + + async def wait_closed(self) -> None: + """ + Wait until the connection is closed. + + :meth:`wait_closed` waits for the closing handshake to complete and for + the TCP connection to terminate. + + """ + await asyncio.shield(self.connection_lost_waiter) + + async def ping(self, data: DataLike | None = None) -> Awaitable[float]: + """ + Send a Ping_. + + .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2 + + A ping may serve as a keepalive or as a check that the remote endpoint + received all messages up to this point + + Args: + data: Payload of the ping. A :class:`str` will be encoded to UTF-8. + If ``data`` is :obj:`None`, the payload is four random bytes. + + Returns: + A future that will be completed when the corresponding pong is + received. You can ignore it if you don't intend to wait. The result + of the future is the latency of the connection in seconds. + + :: + + pong_received = await ws.ping() + # only if you want to wait for the corresponding pong + latency = await pong_received + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If another ping was sent with the same data and + the corresponding pong wasn't received yet. + + """ + if isinstance(data, BytesLike): + data = bytes(data) + elif isinstance(data, str): + data = data.encode() + elif data is not None: + raise TypeError("data must be str or bytes-like") + + async with self.send_context(): + # Protect against duplicates if a payload is explicitly set. + if data in self.pending_pings: + raise ConcurrencyError("already waiting for a pong with the same data") + + # Generate a unique random payload otherwise. + while data is None or data in self.pending_pings: + data = struct.pack("!I", random.getrandbits(32)) + + pong_received = self.loop.create_future() + ping_timestamp = self.loop.time() + # The event loop's default clock is time.monotonic(). Its resolution + # is a bit low on Windows (~16ms). This is improved in Python 3.13. + self.pending_pings[data] = (pong_received, ping_timestamp) + self.protocol.send_ping(data) + return pong_received + + async def pong(self, data: DataLike = b"") -> None: + """ + Send a Pong_. + + .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3 + + An unsolicited pong may serve as a unidirectional heartbeat. + + Args: + data: Payload of the pong. A :class:`str` will be encoded to UTF-8. + + Raises: + ConnectionClosed: When the connection is closed. + + """ + if isinstance(data, BytesLike): + data = bytes(data) + elif isinstance(data, str): + data = data.encode() + else: + raise TypeError("data must be str or bytes-like") + + async with self.send_context(): + self.protocol.send_pong(data) + + # Private methods + + def process_event(self, event: Event) -> None: + """ + Process one incoming event. + + This method is overridden in subclasses to handle the handshake. + + """ + assert isinstance(event, Frame) + if event.opcode in DATA_OPCODES: + self.recv_messages.put(event) + + if event.opcode is Opcode.PONG: + self.acknowledge_pings(bytes(event.data)) + + def acknowledge_pings(self, data: bytes) -> None: + """ + Acknowledge pings when receiving a pong. + + """ + # Ignore unsolicited pong. + if data not in self.pending_pings: + return + + pong_timestamp = self.loop.time() + + # Sending a pong for only the most recent ping is legal. + # Acknowledge all previous pings too in that case. + ping_id = None + ping_ids = [] + for ping_id, (pong_received, ping_timestamp) in self.pending_pings.items(): + ping_ids.append(ping_id) + latency = pong_timestamp - ping_timestamp + if not pong_received.done(): + pong_received.set_result(latency) + if ping_id == data: + self.latency = latency + break + else: + raise AssertionError("solicited pong not found in pings") + + # Remove acknowledged pings from self.pending_pings. + for ping_id in ping_ids: + del self.pending_pings[ping_id] + + def terminate_pending_pings(self) -> None: + """ + Raise ConnectionClosed in pending pings when the connection is closed. + + """ + assert self.protocol.state is CLOSED + exc = self.protocol.close_exc + + for pong_received, _ping_timestamp in self.pending_pings.values(): + if not pong_received.done(): + pong_received.set_exception(exc) + # If the exception is never retrieved, it will be logged when ping + # is garbage-collected. This is confusing for users. + # Given that ping is done (with an exception), canceling it does + # nothing, but it prevents logging the exception. + pong_received.cancel() + + self.pending_pings.clear() + + async def keepalive(self) -> None: + """ + Send a Ping frame and wait for a Pong frame at regular intervals. + + """ + assert self.ping_interval is not None + latency = 0.0 + try: + while True: + # If self.ping_timeout > latency > self.ping_interval, + # pings will be sent immediately after receiving pongs. + # The period will be longer than self.ping_interval. + await asyncio.sleep(self.ping_interval - latency) + + # This cannot raise ConnectionClosed when the connection is + # closing because ping(), via send_context(), waits for the + # connection to be closed before raising ConnectionClosed. + # However, connection_lost() cancels keepalive_task before + # it gets a chance to resume excuting. + pong_received = await self.ping() + if self.debug: + self.logger.debug("% sent keepalive ping") + + if self.ping_timeout is not None: + try: + async with asyncio_timeout(self.ping_timeout): + # connection_lost cancels keepalive immediately + # after setting a ConnectionClosed exception on + # pong_received. A CancelledError is raised here, + # not a ConnectionClosed exception. + latency = await pong_received + if self.debug: + self.logger.debug("% received keepalive pong") + except asyncio.TimeoutError: + if self.debug: + self.logger.debug("- timed out waiting for keepalive pong") + async with self.send_context(): + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "keepalive ping timeout", + ) + raise AssertionError( + "send_context() should wait for connection_lost(), " + "which cancels keepalive()" + ) + except Exception: + self.logger.error("keepalive ping failed", exc_info=True) + + def start_keepalive(self) -> None: + """ + Run :meth:`keepalive` in a task, unless keepalive is disabled. + + """ + if self.ping_interval is not None: + self.keepalive_task = self.loop.create_task(self.keepalive()) + + @contextlib.asynccontextmanager + async def send_context( + self, + *, + expected_state: State = OPEN, # CONNECTING during the opening handshake + ) -> AsyncIterator[None]: + """ + Create a context for writing to the connection from user code. + + On entry, :meth:`send_context` checks that the connection is open; on + exit, it writes outgoing data to the socket:: + + async with self.send_context(): + self.protocol.send_text(message.encode()) + + When the connection isn't open on entry, when the connection is expected + to close on exit, or when an unexpected error happens, terminating the + connection, :meth:`send_context` waits until the connection is closed + then raises :exc:`~websockets.exceptions.ConnectionClosed`. + + """ + # Should we wait until the connection is closed? + wait_for_close = False + # Should we close the transport and raise ConnectionClosed? + raise_close_exc = False + # What exception should we chain ConnectionClosed to? + original_exc: BaseException | None = None + + if self.protocol.state is expected_state: + # Let the caller interact with the protocol. + try: + yield + except (ProtocolError, ConcurrencyError): + # The protocol state wasn't changed. Exit immediately. + raise + except Exception as exc: + self.logger.error("unexpected internal error", exc_info=True) + # This branch should never run. It's a safety net in case of + # bugs. Since we don't know what happened, we will close the + # connection and raise the exception to the caller. + wait_for_close = False + raise_close_exc = True + original_exc = exc + else: + # Check if the connection is expected to close soon. + if self.protocol.close_expected(): + wait_for_close = True + # Set the close deadline based on the close timeout. + # Since we tested earlier that protocol.state is OPEN + # (or CONNECTING), self.close_deadline is still None. + assert self.close_deadline is None + if self.close_timeout is not None: + self.close_deadline = self.loop.time() + self.close_timeout + # Write outgoing data to the socket with flow control. + try: + self.send_data() + await self.drain() + except Exception as exc: + if self.debug: + self.logger.debug( + "! error while sending data", + exc_info=True, + ) + # While the only expected exception here is OSError, + # other exceptions would be treated identically. + wait_for_close = False + raise_close_exc = True + original_exc = exc + + else: # self.protocol.state is not expected_state + # Minor layering violation: we assume that the connection + # will be closing soon if it isn't in the expected state. + wait_for_close = True + # Calculate close_deadline if it wasn't set yet. + if self.close_deadline is None: + if self.close_timeout is not None: + self.close_deadline = self.loop.time() + self.close_timeout + raise_close_exc = True + + # If the connection is expected to close soon and the close timeout + # elapses, close the socket to terminate the connection. + if wait_for_close: + try: + async with asyncio_timeout_at(self.close_deadline): + await asyncio.shield(self.connection_lost_waiter) + except TimeoutError: + # There's no risk of overwriting another error because + # original_exc is never set when wait_for_close is True. + assert original_exc is None + original_exc = TimeoutError("timed out while closing connection") + # Set recv_exc before closing the transport in order to get + # proper exception reporting. + raise_close_exc = True + self.set_recv_exc(original_exc) + + # If an error occurred, close the transport to terminate the connection and + # raise an exception. + if raise_close_exc: + self.transport.abort() + # Wait for the protocol state to be CLOSED before accessing close_exc. + await asyncio.shield(self.connection_lost_waiter) + raise self.protocol.close_exc from original_exc + + def send_data(self) -> None: + """ + Send outgoing data. + + """ + for data in self.protocol.data_to_send(): + if data: + self.transport.write(data) + else: + # Half-close the TCP connection when possible i.e. no TLS. + if self.transport.can_write_eof(): + if self.debug: + self.logger.debug("x half-closing TCP connection") + # write_eof() doesn't document which exceptions it raises. + # OSError is plausible. uvloop can raise RuntimeError here. + try: + self.transport.write_eof() + except Exception: # pragma: no cover + pass + # Else, close the TCP connection. + else: # pragma: no cover + if self.debug: + self.logger.debug("x closing TCP connection") + self.transport.close() + + def set_recv_exc(self, exc: BaseException | None) -> None: + """ + Set recv_exc, if not set yet. + + This method must be called only from connection callbacks. + + """ + if self.recv_exc is None: + self.recv_exc = exc + + # asyncio.Protocol methods + + # Connection callbacks + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + transport = cast(asyncio.Transport, transport) + self.recv_messages = Assembler( + self.max_queue_high, + self.max_queue_low, + pause=transport.pause_reading, + resume=transport.resume_reading, + ) + transport.set_write_buffer_limits( + self.write_limit_high, + self.write_limit_low, + ) + self.transport = transport + + def connection_lost(self, exc: Exception | None) -> None: + # Calling protocol.receive_eof() is safe because it's idempotent. + # This guarantees that the protocol state becomes CLOSED. + self.protocol.receive_eof() + assert self.protocol.state is CLOSED + + self.set_recv_exc(exc) + + # Abort recv() and pending pings with a ConnectionClosed exception. + self.recv_messages.close() + self.terminate_pending_pings() + + if self.keepalive_task is not None: + self.keepalive_task.cancel() + + # If self.connection_lost_waiter isn't pending, that's a bug, because: + # - it's set only here in connection_lost() which is called only once; + # - it must never be canceled. + self.connection_lost_waiter.set_result(None) + + # Adapted from asyncio.streams.FlowControlMixin + if self.paused: # pragma: no cover + self.paused = False + for waiter in self.drain_waiters: + if not waiter.done(): + if exc is None: + waiter.set_result(None) + else: + waiter.set_exception(exc) + + # Flow control callbacks + + def pause_writing(self) -> None: # pragma: no cover + # Adapted from asyncio.streams.FlowControlMixin + assert not self.paused + self.paused = True + + def resume_writing(self) -> None: # pragma: no cover + # Adapted from asyncio.streams.FlowControlMixin + assert self.paused + self.paused = False + for waiter in self.drain_waiters: + if not waiter.done(): + waiter.set_result(None) + + async def drain(self) -> None: # pragma: no cover + # We don't check if the connection is closed because we call drain() + # immediately after write() and write() would fail in that case. + + # Adapted from asyncio.streams.StreamWriter + # Yield to the event loop so that connection_lost() may be called. + if self.transport.is_closing(): + await asyncio.sleep(0) + + # Adapted from asyncio.streams.FlowControlMixin + if self.paused: + waiter = self.loop.create_future() + self.drain_waiters.append(waiter) + try: + await waiter + finally: + self.drain_waiters.remove(waiter) + + # Streaming protocol callbacks + + def data_received(self, data: bytes) -> None: + # Feed incoming data to the protocol. + self.protocol.receive_data(data) + + # This isn't expected to raise an exception. + events = self.protocol.events_received() + + # Write outgoing data to the transport. + try: + self.send_data() + except Exception as exc: + if self.debug: + self.logger.debug("! error while sending data", exc_info=True) + self.set_recv_exc(exc) + + # If needed, set the close deadline based on the close timeout. + if self.protocol.close_expected(): + if self.close_deadline is None: + if self.close_timeout is not None: + self.close_deadline = self.loop.time() + self.close_timeout + + # If self.send_data raised an exception, then events are lost. + # Given that automatic responses write small amounts of data, + # this should be uncommon, so we don't handle the edge case. + + for event in events: + # This isn't expected to raise an exception. + self.process_event(event) + + def eof_received(self) -> None: + # Feed the end of the data stream to the protocol. + self.protocol.receive_eof() + + # This isn't expected to raise an exception. + events = self.protocol.events_received() + + # There is no error handling because send_data() can only write + # the end of the data stream and it handles errors by itself. + self.send_data() + + # This code path is triggered when receiving an HTTP response + # without a Content-Length header. This is the only case where + # reading until EOF generates an event; all other events have + # a known length. Ignore for coverage measurement because tests + # are in test_client.py rather than test_connection.py. + for event in events: # pragma: no cover + # This isn't expected to raise an exception. + self.process_event(event) + + # The WebSocket protocol has its own closing handshake: endpoints close + # the TCP or TLS connection after sending and receiving a close frame. + # As a consequence, they never need to write after receiving EOF, so + # there's no reason to keep the transport open by returning True. + # Besides, that doesn't work on TLS connections. + + +# broadcast() is defined in the connection module even though it's primarily +# used by servers and documented in the server module because it works with +# client connections too and because it's easier to test together with the +# Connection class. + + +def broadcast( + connections: Iterable[Connection], + message: DataLike, + raise_exceptions: bool = False, +) -> None: + """ + Broadcast a message to several WebSocket connections. + + A string (:class:`str`) is sent as a Text_ frame. A bytestring or bytes-like + object (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) is sent + as a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + :func:`broadcast` pushes the message synchronously to all connections even + if their write buffers are overflowing. There's no backpressure. + + If you broadcast messages faster than a connection can handle them, messages + will pile up in its write buffer until the connection times out. Keep + ``ping_interval`` and ``ping_timeout`` low to prevent excessive memory usage + from slow connections. + + Unlike :meth:`~websockets.asyncio.connection.Connection.send`, + :func:`broadcast` doesn't support sending fragmented messages. Indeed, + fragmentation is useful for sending large messages without buffering them in + memory, while :func:`broadcast` buffers one copy per connection as fast as + possible. + + :func:`broadcast` skips connections that aren't open in order to avoid + errors on connections where the closing handshake is in progress. + + :func:`broadcast` ignores failures to write the message on some connections. + It continues writing to other connections. On Python 3.11 and above, you may + set ``raise_exceptions`` to :obj:`True` to record failures and raise all + exceptions in a :pep:`654` :exc:`ExceptionGroup`. + + While :func:`broadcast` makes more sense for servers, it works identically + with clients, if you have a use case for opening connections to many servers + and broadcasting a message to them. + + Args: + websockets: WebSocket connections to which the message will be sent. + message: Message to send. + raise_exceptions: Whether to raise an exception in case of failures. + + Raises: + TypeError: If ``message`` doesn't have a supported type. + + """ + if isinstance(message, str): + send_method = "send_text" + message = message.encode() + elif isinstance(message, BytesLike): + send_method = "send_binary" + else: + raise TypeError("data must be str or bytes") + + if raise_exceptions: + if sys.version_info[:2] < (3, 11): # pragma: no cover + raise ValueError("raise_exceptions requires at least Python 3.11") + exceptions: list[Exception] = [] + + for connection in connections: + exception: Exception + + if connection.protocol.state is not OPEN: + continue + + if connection.send_in_progress is not None: + if raise_exceptions: + exception = ConcurrencyError("sending a fragmented message") + exceptions.append(exception) + else: + connection.logger.warning( + "skipped broadcast: sending a fragmented message", + ) + continue + + try: + # Call connection.protocol.send_text or send_binary. + # Either way, message is already converted to bytes. + getattr(connection.protocol, send_method)(message) + connection.send_data() + except Exception as write_exception: + if raise_exceptions: + exception = RuntimeError("failed to write message") + exception.__cause__ = write_exception + exceptions.append(exception) + else: + connection.logger.warning( + "skipped broadcast: failed to write message: %s", + traceback.format_exception_only(write_exception)[0].strip(), + ) + + if raise_exceptions and exceptions: + raise ExceptionGroup("skipped broadcast", exceptions) + + +# Pretend that broadcast is actually defined in the server module. +broadcast.__module__ = "websockets.asyncio.server" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/messages.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/messages.py new file mode 100644 index 0000000000000000000000000000000000000000..37126bf5e53b46cbc665c38e62fc17b5bfea9a15 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/messages.py @@ -0,0 +1,316 @@ +from __future__ import annotations + +import asyncio +import codecs +import collections +from collections.abc import AsyncIterator, Iterable +from typing import Any, Callable, Generic, Literal, TypeVar, overload + +from ..exceptions import ConcurrencyError +from ..frames import OP_BINARY, OP_CONT, OP_TEXT, Frame +from ..typing import Data + + +__all__ = ["Assembler"] + +UTF8Decoder = codecs.getincrementaldecoder("utf-8") + +T = TypeVar("T") + + +class SimpleQueue(Generic[T]): + """ + Simplified version of :class:`asyncio.Queue`. + + Provides only the subset of functionality needed by :class:`Assembler`. + + """ + + def __init__(self) -> None: + self.loop = asyncio.get_running_loop() + self.get_waiter: asyncio.Future[None] | None = None + self.queue: collections.deque[T] = collections.deque() + + def __len__(self) -> int: + return len(self.queue) + + def put(self, item: T) -> None: + """Put an item into the queue.""" + self.queue.append(item) + if self.get_waiter is not None and not self.get_waiter.done(): + self.get_waiter.set_result(None) + + async def get(self, block: bool = True) -> T: + """Remove and return an item from the queue, waiting if necessary.""" + if not self.queue: + if not block: + raise EOFError("stream of frames ended") + assert self.get_waiter is None, "cannot call get() concurrently" + self.get_waiter = self.loop.create_future() + try: + await self.get_waiter + finally: + self.get_waiter.cancel() + self.get_waiter = None + return self.queue.popleft() + + def reset(self, items: Iterable[T]) -> None: + """Put back items into an empty, idle queue.""" + assert self.get_waiter is None, "cannot reset() while get() is running" + assert not self.queue, "cannot reset() while queue isn't empty" + self.queue.extend(items) + + def abort(self) -> None: + """Close the queue, raising EOFError in get() if necessary.""" + if self.get_waiter is not None and not self.get_waiter.done(): + self.get_waiter.set_exception(EOFError("stream of frames ended")) + + +class Assembler: + """ + Assemble messages from frames. + + :class:`Assembler` expects only data frames. The stream of frames must + respect the protocol; if it doesn't, the behavior is undefined. + + Args: + pause: Called when the buffer of frames goes above the high water mark; + should pause reading from the network. + resume: Called when the buffer of frames goes below the low water mark; + should resume reading from the network. + + """ + + def __init__( + self, + high: int | None = None, + low: int | None = None, + pause: Callable[[], Any] = lambda: None, + resume: Callable[[], Any] = lambda: None, + ) -> None: + # Queue of incoming frames. + self.frames: SimpleQueue[Frame] = SimpleQueue() + + # We cannot put a hard limit on the size of the queue because a single + # call to Protocol.data_received() could produce thousands of frames, + # which must be buffered. Instead, we pause reading when the buffer goes + # above the high limit and we resume when it goes under the low limit. + if high is not None and low is None: + low = high // 4 + if high is None and low is not None: + high = low * 4 + if high is not None and low is not None: + if low < 0: + raise ValueError("low must be positive or equal to zero") + if high < low: + raise ValueError("high must be greater than or equal to low") + self.high, self.low = high, low + self.pause = pause + self.resume = resume + self.paused = False + + # This flag prevents concurrent calls to get() by user code. + self.get_in_progress = False + + # This flag marks the end of the connection. + self.closed = False + + @overload + async def get(self, decode: Literal[True]) -> str: ... + + @overload + async def get(self, decode: Literal[False]) -> bytes: ... + + @overload + async def get(self, decode: bool | None = None) -> Data: ... + + async def get(self, decode: bool | None = None) -> Data: + """ + Read the next message. + + :meth:`get` returns a single :class:`str` or :class:`bytes`. + + If the message is fragmented, :meth:`get` waits until the last frame is + received, then it reassembles the message and returns it. To receive + messages frame by frame, use :meth:`get_iter` instead. + + Args: + decode: :obj:`False` disables UTF-8 decoding of text frames and + returns :class:`bytes`. :obj:`True` forces UTF-8 decoding of + binary frames and returns :class:`str`. + + Raises: + EOFError: If the stream of frames has ended. + UnicodeDecodeError: If a text frame contains invalid UTF-8. + ConcurrencyError: If two coroutines run :meth:`get` or + :meth:`get_iter` concurrently. + + """ + if self.get_in_progress: + raise ConcurrencyError("get() or get_iter() is already running") + self.get_in_progress = True + + # Locking with get_in_progress prevents concurrent execution + # until get() fetches a complete message or is canceled. + + try: + # Fetch the first frame. + frame = await self.frames.get(not self.closed) + self.maybe_resume() + assert frame.opcode is OP_TEXT or frame.opcode is OP_BINARY + if decode is None: + decode = frame.opcode is OP_TEXT + frames = [frame] + + # Fetch subsequent frames for fragmented messages. + while not frame.fin: + try: + frame = await self.frames.get(not self.closed) + except asyncio.CancelledError: + # Put frames already received back into the queue + # so that future calls to get() can return them. + self.frames.reset(frames) + raise + self.maybe_resume() + assert frame.opcode is OP_CONT + frames.append(frame) + + finally: + self.get_in_progress = False + + # This converts frame.data to bytes when it's a bytearray. + data = b"".join(frame.data for frame in frames) + if decode: + return data.decode() + else: + return data + + @overload + def get_iter(self, decode: Literal[True]) -> AsyncIterator[str]: ... + + @overload + def get_iter(self, decode: Literal[False]) -> AsyncIterator[bytes]: ... + + @overload + def get_iter(self, decode: bool | None = None) -> AsyncIterator[Data]: ... + + async def get_iter(self, decode: bool | None = None) -> AsyncIterator[Data]: + """ + Stream the next message. + + Iterating the return value of :meth:`get_iter` asynchronously yields a + :class:`str` or :class:`bytes` for each frame in the message. + + The iterator must be fully consumed before calling :meth:`get_iter` or + :meth:`get` again. Else, :exc:`ConcurrencyError` is raised. + + This method only makes sense for fragmented messages. If messages aren't + fragmented, use :meth:`get` instead. + + Args: + decode: :obj:`False` disables UTF-8 decoding of text frames and + returns :class:`bytes`. :obj:`True` forces UTF-8 decoding of + binary frames and returns :class:`str`. + + Raises: + EOFError: If the stream of frames has ended. + UnicodeDecodeError: If a text frame contains invalid UTF-8. + ConcurrencyError: If two coroutines run :meth:`get` or + :meth:`get_iter` concurrently. + + """ + if self.get_in_progress: + raise ConcurrencyError("get() or get_iter() is already running") + self.get_in_progress = True + + # Locking with get_in_progress prevents concurrent execution + # until get_iter() fetches a complete message or is canceled. + + # If get_iter() raises an exception e.g. in decoder.decode(), + # get_in_progress remains set and the connection becomes unusable. + + # Yield the first frame. + try: + frame = await self.frames.get(not self.closed) + except asyncio.CancelledError: + self.get_in_progress = False + raise + self.maybe_resume() + assert frame.opcode is OP_TEXT or frame.opcode is OP_BINARY + if decode is None: + decode = frame.opcode is OP_TEXT + if decode: + decoder = UTF8Decoder() + yield decoder.decode(frame.data, frame.fin) + else: + # Convert to bytes when frame.data is a bytearray. + yield bytes(frame.data) + + # Yield subsequent frames for fragmented messages. + while not frame.fin: + # We cannot handle asyncio.CancelledError because we don't buffer + # previous fragments — we're streaming them. Canceling get_iter() + # here will leave the assembler in a stuck state. Future calls to + # get() or get_iter() will raise ConcurrencyError. + frame = await self.frames.get(not self.closed) + self.maybe_resume() + assert frame.opcode is OP_CONT + if decode: + yield decoder.decode(frame.data, frame.fin) + else: + # Convert to bytes when frame.data is a bytearray. + yield bytes(frame.data) + + self.get_in_progress = False + + def put(self, frame: Frame) -> None: + """ + Add ``frame`` to the next message. + + Raises: + EOFError: If the stream of frames has ended. + + """ + if self.closed: + raise EOFError("stream of frames ended") + + self.frames.put(frame) + self.maybe_pause() + + def maybe_pause(self) -> None: + """Pause the writer if queue is above the high water mark.""" + # Skip if flow control is disabled. + if self.high is None: + return + + # Check for "> high" to support high = 0. + if len(self.frames) > self.high and not self.paused: + self.paused = True + self.pause() + + def maybe_resume(self) -> None: + """Resume the writer if queue is below the low water mark.""" + # Skip if flow control is disabled. + if self.low is None: + return + + # Check for "<= low" to support low = 0. + if len(self.frames) <= self.low and self.paused: + self.paused = False + self.resume() + + def close(self) -> None: + """ + End the stream of frames. + + Calling :meth:`close` concurrently with :meth:`get`, :meth:`get_iter`, + or :meth:`put` is safe. They will raise :exc:`EOFError`. + + """ + if self.closed: + return + + self.closed = True + + # Unblock get() or get_iter(). + self.frames.abort() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/router.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/router.py new file mode 100644 index 0000000000000000000000000000000000000000..97da471f0b1f775ddf474a3c16b7db326f629086 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/router.py @@ -0,0 +1,219 @@ +from __future__ import annotations + +import http +import ssl as ssl_module +import urllib.parse +from typing import Any, Awaitable, Callable, Literal + +from ..http11 import Request, Response +from .server import Server, ServerConnection, serve + + +__all__ = ["route", "unix_route", "Router"] + + +try: + from werkzeug.exceptions import NotFound + from werkzeug.routing import Map, RequestRedirect + +except ImportError: + + def route( + url_map: Map, + *args: Any, + server_name: str | None = None, + ssl: ssl_module.SSLContext | Literal[True] | None = None, + create_router: type[Router] | None = None, + **kwargs: Any, + ) -> Awaitable[Server]: + raise ImportError("route() requires werkzeug") + + def unix_route( + url_map: Map, + path: str | None = None, + **kwargs: Any, + ) -> Awaitable[Server]: + raise ImportError("unix_route() requires werkzeug") + +else: + + def route( + url_map: Map, + *args: Any, + server_name: str | None = None, + ssl: ssl_module.SSLContext | Literal[True] | None = None, + create_router: type[Router] | None = None, + **kwargs: Any, + ) -> Awaitable[Server]: + """ + Create a WebSocket server dispatching connections to different handlers. + + This feature requires the third-party library `werkzeug`_: + + .. code-block:: console + + $ pip install werkzeug + + .. _werkzeug: https://werkzeug.palletsprojects.com/ + + :func:`route` accepts the same arguments as + :func:`~websockets.sync.server.serve`, except as described below. + + The first argument is a :class:`werkzeug.routing.Map` that maps URL patterns + to connection handlers. In addition to the connection, handlers receive + parameters captured in the URL as keyword arguments. + + Here's an example:: + + + from websockets.asyncio.router import route + from werkzeug.routing import Map, Rule + + async def channel_handler(websocket, channel_id): + ... + + url_map = Map([ + Rule("/channel/", endpoint=channel_handler), + ... + ]) + + # set this future to exit the server + stop = asyncio.get_running_loop().create_future() + + async with route(url_map, ...) as server: + await stop + + + Refer to the documentation of :mod:`werkzeug.routing` for details. + + If you define redirects with ``Rule(..., redirect_to=...)`` in the URL map, + when the server runs behind a reverse proxy that modifies the ``Host`` + header or terminates TLS, you need additional configuration: + + * Set ``server_name`` to the name of the server as seen by clients. When + not provided, websockets uses the value of the ``Host`` header. + + * Set ``ssl=True`` to generate ``wss://`` URIs without enabling TLS. + Under the hood, this bind the URL map with a ``url_scheme`` of + ``wss://`` instead of ``ws://``. + + There is no need to specify ``websocket=True`` in each rule. It is added + automatically. + + Args: + url_map: Mapping of URL patterns to connection handlers. + server_name: Name of the server as seen by clients. If :obj:`None`, + websockets uses the value of the ``Host`` header. + ssl: Configuration for enabling TLS on the connection. Set it to + :obj:`True` if a reverse proxy terminates TLS connections. + create_router: Factory for the :class:`Router` dispatching requests to + handlers. Set it to a wrapper or a subclass to customize routing. + + """ + url_scheme = "ws" if ssl is None else "wss" + if ssl is not True and ssl is not None: + kwargs["ssl"] = ssl + + if create_router is None: + create_router = Router + + router = create_router(url_map, server_name, url_scheme) + + _process_request: ( + Callable[ + [ServerConnection, Request], + Awaitable[Response | None] | Response | None, + ] + | None + ) = kwargs.pop("process_request", None) + if _process_request is None: + process_request: Callable[ + [ServerConnection, Request], + Awaitable[Response | None] | Response | None, + ] = router.route_request + else: + + async def process_request( + connection: ServerConnection, request: Request + ) -> Response | None: + response = _process_request(connection, request) + if isinstance(response, Awaitable): + response = await response + if response is not None: + return response + return router.route_request(connection, request) + + return serve(router.handler, *args, process_request=process_request, **kwargs) + + def unix_route( + url_map: Map, + path: str | None = None, + **kwargs: Any, + ) -> Awaitable[Server]: + """ + Create a WebSocket Unix server dispatching connections to different handlers. + + :func:`unix_route` combines the behaviors of :func:`route` and + :func:`~websockets.asyncio.server.unix_serve`. + + Args: + url_map: Mapping of URL patterns to connection handlers. + path: File system path to the Unix socket. + + """ + return route(url_map, unix=True, path=path, **kwargs) + + +class Router: + """WebSocket router supporting :func:`route`.""" + + def __init__( + self, + url_map: Map, + server_name: str | None = None, + url_scheme: str = "ws", + ) -> None: + self.url_map = url_map + self.server_name = server_name + self.url_scheme = url_scheme + for rule in self.url_map.iter_rules(): + rule.websocket = True + + def get_server_name(self, connection: ServerConnection, request: Request) -> str: + if self.server_name is None: + return request.headers["Host"] + else: + return self.server_name + + def redirect(self, connection: ServerConnection, url: str) -> Response: + response = connection.respond(http.HTTPStatus.FOUND, f"Found at {url}") + response.headers["Location"] = url + return response + + def not_found(self, connection: ServerConnection) -> Response: + return connection.respond(http.HTTPStatus.NOT_FOUND, "Not Found") + + def route_request( + self, connection: ServerConnection, request: Request + ) -> Response | None: + """Route incoming request.""" + url_map_adapter = self.url_map.bind( + server_name=self.get_server_name(connection, request), + url_scheme=self.url_scheme, + ) + try: + parsed = urllib.parse.urlparse(request.path) + handler, kwargs = url_map_adapter.match( + path_info=parsed.path, + query_args=parsed.query, + ) + except RequestRedirect as redirect: + return self.redirect(connection, redirect.new_url) + except NotFound: + return self.not_found(connection) + connection.handler, connection.handler_kwargs = handler, kwargs + return None + + async def handler(self, connection: ServerConnection) -> None: + """Handle a connection.""" + return await connection.handler(connection, **connection.handler_kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/server.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/server.py new file mode 100644 index 0000000000000000000000000000000000000000..b78d7dc20b73f2a2fac377502c6de61f5f92c04d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/asyncio/server.py @@ -0,0 +1,997 @@ +from __future__ import annotations + +import asyncio +import hmac +import http +import logging +import re +import socket +import sys +from collections.abc import Awaitable, Generator, Iterable, Sequence +from types import TracebackType +from typing import Any, Callable, Mapping, cast + +from ..exceptions import InvalidHeader +from ..extensions.base import ServerExtensionFactory +from ..extensions.permessage_deflate import enable_server_permessage_deflate +from ..frames import CloseCode +from ..headers import ( + build_www_authenticate_basic, + parse_authorization_basic, + validate_subprotocols, +) +from ..http11 import SERVER, Request, Response +from ..protocol import CONNECTING, OPEN, Event +from ..server import ServerProtocol +from ..typing import LoggerLike, Origin, StatusLike, Subprotocol +from .compatibility import asyncio_timeout +from .connection import Connection, broadcast + + +__all__ = [ + "broadcast", + "serve", + "unix_serve", + "ServerConnection", + "Server", + "basic_auth", +] + + +class ServerConnection(Connection): + """ + :mod:`asyncio` implementation of a WebSocket server connection. + + :class:`ServerConnection` provides :meth:`recv` and :meth:`send` methods for + receiving and sending messages. + + It supports asynchronous iteration to receive messages:: + + async for message in websocket: + await process(message) + + The iterator exits normally when the connection is closed with code + 1000 (OK) or 1001 (going away) or without a close code. It raises a + :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is + closed with any other code. + + The ``ping_interval``, ``ping_timeout``, ``close_timeout``, ``max_queue``, + and ``write_limit`` arguments have the same meaning as in :func:`serve`. + + Args: + protocol: Sans-I/O connection. + server: Server that manages this connection. + + """ + + def __init__( + self, + protocol: ServerProtocol, + server: Server, + *, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + max_queue: int | None | tuple[int | None, int | None] = 16, + write_limit: int | tuple[int, int | None] = 2**15, + ) -> None: + self.protocol: ServerProtocol + super().__init__( + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + write_limit=write_limit, + ) + self.server = server + self.request_rcvd: asyncio.Future[None] = self.loop.create_future() + self.username: str # see basic_auth() + self.handler: Callable[[ServerConnection], Awaitable[None]] # see route() + self.handler_kwargs: Mapping[str, Any] # see route() + + def respond(self, status: StatusLike, text: str) -> Response: + """ + Create a plain text HTTP response. + + ``process_request`` and ``process_response`` may call this method to + return an HTTP response instead of performing the WebSocket opening + handshake. + + You can modify the response before returning it, for example by changing + HTTP headers. + + Args: + status: HTTP status code. + text: HTTP response body; it will be encoded to UTF-8. + + Returns: + HTTP response to send to the client. + + """ + return self.protocol.reject(status, text) + + async def handshake( + self, + process_request: ( + Callable[ + [ServerConnection, Request], + Awaitable[Response | None] | Response | None, + ] + | None + ) = None, + process_response: ( + Callable[ + [ServerConnection, Request, Response], + Awaitable[Response | None] | Response | None, + ] + | None + ) = None, + server_header: str | None = SERVER, + ) -> None: + """ + Perform the opening handshake. + + """ + await asyncio.wait( + [self.request_rcvd, self.connection_lost_waiter], + return_when=asyncio.FIRST_COMPLETED, + ) + + if self.request is not None: + async with self.send_context(expected_state=CONNECTING): + response = None + + if process_request is not None: + try: + response = process_request(self, self.request) + if isinstance(response, Awaitable): + response = await response + except Exception as exc: + self.protocol.handshake_exc = exc + response = self.protocol.reject( + http.HTTPStatus.INTERNAL_SERVER_ERROR, + ( + "Failed to open a WebSocket connection.\n" + "See server log for more information.\n" + ), + ) + + if response is None: + if self.server.is_serving(): + self.response = self.protocol.accept(self.request) + else: + self.response = self.protocol.reject( + http.HTTPStatus.SERVICE_UNAVAILABLE, + "Server is shutting down.\n", + ) + else: + assert isinstance(response, Response) # help mypy + self.response = response + + if server_header: + self.response.headers["Server"] = server_header + + response = None + + if process_response is not None: + try: + response = process_response(self, self.request, self.response) + if isinstance(response, Awaitable): + response = await response + except Exception as exc: + self.protocol.handshake_exc = exc + response = self.protocol.reject( + http.HTTPStatus.INTERNAL_SERVER_ERROR, + ( + "Failed to open a WebSocket connection.\n" + "See server log for more information.\n" + ), + ) + + if response is not None: + assert isinstance(response, Response) # help mypy + self.response = response + + self.protocol.send_response(self.response) + + # self.protocol.handshake_exc is set when the connection is lost before + # receiving a request, when the request cannot be parsed, or when the + # handshake fails, including when process_request or process_response + # raises an exception. + + # It isn't set when process_request or process_response sends an HTTP + # response that rejects the handshake. + + if self.protocol.handshake_exc is not None: + raise self.protocol.handshake_exc + + def process_event(self, event: Event) -> None: + """ + Process one incoming event. + + """ + # First event - handshake request. + if self.request is None: + assert isinstance(event, Request) + self.request = event + self.request_rcvd.set_result(None) + # Later events - frames. + else: + super().process_event(event) + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + super().connection_made(transport) + self.server.start_connection_handler(self) + + +class Server: + """ + WebSocket server returned by :func:`serve`. + + This class mirrors the API of :class:`asyncio.Server`. + + It keeps track of WebSocket connections in order to close them properly + when shutting down. + + Args: + handler: Connection handler. It receives the WebSocket connection, + which is a :class:`ServerConnection`, in argument. + process_request: Intercept the request during the opening handshake. + Return an HTTP response to force the response. Return :obj:`None` to + continue normally. When you force an HTTP 101 Continue response, the + handshake is successful. Else, the connection is aborted. + ``process_request`` may be a function or a coroutine. + process_response: Intercept the response during the opening handshake. + Modify the response or return a new HTTP response to force the + response. Return :obj:`None` to continue normally. When you force an + HTTP 101 Continue response, the handshake is successful. Else, the + connection is aborted. ``process_response`` may be a function or a + coroutine. + server_header: Value of the ``Server`` response header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to + :obj:`None` removes the header. + open_timeout: Timeout for opening connections in seconds. + :obj:`None` disables the timeout. + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.server")``. + See the :doc:`logging guide <../../topics/logging>` for details. + + """ + + def __init__( + self, + handler: Callable[[ServerConnection], Awaitable[None]], + *, + process_request: ( + Callable[ + [ServerConnection, Request], + Awaitable[Response | None] | Response | None, + ] + | None + ) = None, + process_response: ( + Callable[ + [ServerConnection, Request, Response], + Awaitable[Response | None] | Response | None, + ] + | None + ) = None, + server_header: str | None = SERVER, + open_timeout: float | None = 10, + logger: LoggerLike | None = None, + ) -> None: + self.loop = asyncio.get_running_loop() + self.handler = handler + self.process_request = process_request + self.process_response = process_response + self.server_header = server_header + self.open_timeout = open_timeout + if logger is None: + logger = logging.getLogger("websockets.server") + self.logger = logger + + # Keep track of active connections. + self.handlers: dict[ServerConnection, asyncio.Task[None]] = {} + + # Task responsible for closing the server and terminating connections. + self.close_task: asyncio.Task[None] | None = None + + # Completed when the server is closed and connections are terminated. + self.closed_waiter: asyncio.Future[None] = self.loop.create_future() + + @property + def connections(self) -> set[ServerConnection]: + """ + Set of active connections. + + This property contains all connections that completed the opening + handshake successfully and didn't start the closing handshake yet. + It can be useful in combination with :func:`~broadcast`. + + """ + return {connection for connection in self.handlers if connection.state is OPEN} + + def wrap(self, server: asyncio.Server) -> None: + """ + Attach to a given :class:`asyncio.Server`. + + Since :meth:`~asyncio.loop.create_server` doesn't support injecting a + custom ``Server`` class, the easiest solution that doesn't rely on + private :mod:`asyncio` APIs is to: + + - instantiate a :class:`Server` + - give the protocol factory a reference to that instance + - call :meth:`~asyncio.loop.create_server` with the factory + - attach the resulting :class:`asyncio.Server` with this method + + """ + self.server = server + for sock in server.sockets: + if sock.family == socket.AF_INET: + name = "%s:%d" % sock.getsockname() + elif sock.family == socket.AF_INET6: + name = "[%s]:%d" % sock.getsockname()[:2] + elif sock.family == socket.AF_UNIX: + name = sock.getsockname() + # In the unlikely event that someone runs websockets over a + # protocol other than IP or Unix sockets, avoid crashing. + else: # pragma: no cover + name = str(sock.getsockname()) + self.logger.info("server listening on %s", name) + + async def conn_handler(self, connection: ServerConnection) -> None: + """ + Handle the lifecycle of a WebSocket connection. + + Since this method doesn't have a caller that can handle exceptions, + it attempts to log relevant ones. + + It guarantees that the TCP connection is closed before exiting. + + """ + try: + async with asyncio_timeout(self.open_timeout): + try: + await connection.handshake( + self.process_request, + self.process_response, + self.server_header, + ) + except asyncio.CancelledError: + connection.transport.abort() + raise + except Exception: + connection.logger.error("opening handshake failed", exc_info=True) + connection.transport.abort() + return + + if connection.protocol.state is not OPEN: + # process_request or process_response rejected the handshake. + connection.transport.abort() + return + + try: + connection.start_keepalive() + await self.handler(connection) + except Exception: + connection.logger.error("connection handler failed", exc_info=True) + await connection.close(CloseCode.INTERNAL_ERROR) + else: + await connection.close() + + except TimeoutError: + # When the opening handshake times out, there's nothing to log. + pass + + except Exception: # pragma: no cover + # Don't leak connections on unexpected errors. + connection.transport.abort() + + finally: + # Registration is tied to the lifecycle of conn_handler() because + # the server waits for connection handlers to terminate, even if + # all connections are already closed. + del self.handlers[connection] + + def start_connection_handler(self, connection: ServerConnection) -> None: + """ + Register a connection with this server. + + """ + # The connection must be registered in self.handlers immediately. + # If it was registered in conn_handler(), a race condition could + # happen when closing the server after scheduling conn_handler() + # but before it starts executing. + self.handlers[connection] = self.loop.create_task(self.conn_handler(connection)) + + def close( + self, + close_connections: bool = True, + code: CloseCode | int = CloseCode.GOING_AWAY, + reason: str = "", + ) -> None: + """ + Close the server. + + * Close the underlying :class:`asyncio.Server`. + * When ``close_connections`` is :obj:`True`, which is the default, close + existing connections. Specifically: + + * Reject opening WebSocket connections with an HTTP 503 (service + unavailable) error. This happens when the server accepted the TCP + connection but didn't complete the opening handshake before closing. + * Close open WebSocket connections with code 1001 (going away). + ``code`` and ``reason`` can be customized, for example to use code + 1012 (service restart). + + * Wait until all connection handlers terminate. + + :meth:`close` is idempotent. + + """ + if self.close_task is None: + self.close_task = self.get_loop().create_task( + self._close(close_connections, code, reason) + ) + + async def _close( + self, + close_connections: bool = True, + code: CloseCode | int = CloseCode.GOING_AWAY, + reason: str = "", + ) -> None: + """ + Implementation of :meth:`close`. + + This calls :meth:`~asyncio.Server.close` on the underlying + :class:`asyncio.Server` object to stop accepting new connections and + then closes open connections. + + """ + self.logger.info("server closing") + + # Stop accepting new connections. + self.server.close() + + # Wait until all accepted connections reach connection_made() and call + # register(). See https://github.com/python/cpython/issues/79033 for + # details. This workaround can be removed when dropping Python < 3.11. + await asyncio.sleep(0) + + # After server.close(), handshake() closes OPENING connections with an + # HTTP 503 error. + + if close_connections: + # Close OPEN connections with code 1001 by default. + close_tasks = [ + asyncio.create_task(connection.close(code, reason)) + for connection in self.handlers + if connection.protocol.state is not CONNECTING + ] + # asyncio.wait doesn't accept an empty first argument. + if close_tasks: + await asyncio.wait(close_tasks) + + # Wait until all TCP connections are closed. + await self.server.wait_closed() + + # Wait until all connection handlers terminate. + # asyncio.wait doesn't accept an empty first argument. + if self.handlers: + await asyncio.wait(self.handlers.values()) + + # Tell wait_closed() to return. + self.closed_waiter.set_result(None) + + self.logger.info("server closed") + + async def wait_closed(self) -> None: + """ + Wait until the server is closed. + + When :meth:`wait_closed` returns, all TCP connections are closed and + all connection handlers have returned. + + To ensure a fast shutdown, a connection handler should always be + awaiting at least one of: + + * :meth:`~ServerConnection.recv`: when the connection is closed, + it raises :exc:`~websockets.exceptions.ConnectionClosedOK`; + * :meth:`~ServerConnection.wait_closed`: when the connection is + closed, it returns. + + Then the connection handler is immediately notified of the shutdown; + it can clean up and exit. + + """ + await asyncio.shield(self.closed_waiter) + + def get_loop(self) -> asyncio.AbstractEventLoop: + """ + See :meth:`asyncio.Server.get_loop`. + + """ + return self.server.get_loop() + + def is_serving(self) -> bool: # pragma: no cover + """ + See :meth:`asyncio.Server.is_serving`. + + """ + return self.server.is_serving() + + async def start_serving(self) -> None: # pragma: no cover + """ + See :meth:`asyncio.Server.start_serving`. + + Typical use:: + + server = await serve(..., start_serving=False) + # perform additional setup here... + # ... then start the server + await server.start_serving() + + """ + await self.server.start_serving() + + async def serve_forever(self) -> None: # pragma: no cover + """ + See :meth:`asyncio.Server.serve_forever`. + + Typical use:: + + server = await serve(...) + # this coroutine doesn't return + # canceling it stops the server + await server.serve_forever() + + This is an alternative to using :func:`serve` as an asynchronous context + manager. Shutdown is triggered by canceling :meth:`serve_forever` + instead of exiting a :func:`serve` context. + + """ + await self.server.serve_forever() + + @property + def sockets(self) -> tuple[socket.socket, ...]: + """ + See :attr:`asyncio.Server.sockets`. + + """ + return self.server.sockets + + async def __aenter__(self) -> Server: # pragma: no cover + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: # pragma: no cover + self.close() + await self.wait_closed() + + +# This is spelled in lower case because it's exposed as a callable in the API. +class serve: + """ + Create a WebSocket server listening on ``host`` and ``port``. + + Whenever a client connects, the server creates a :class:`ServerConnection`, + performs the opening handshake, and delegates to the ``handler`` coroutine. + + The handler receives the :class:`ServerConnection` instance, which you can + use to send and receive messages. + + Once the handler completes, either normally or with an exception, the server + performs the closing handshake and closes the connection. + + This coroutine returns a :class:`Server` whose API mirrors + :class:`asyncio.Server`. Treat it as an asynchronous context manager to + ensure that the server will be closed:: + + from websockets.asyncio.server import serve + + def handler(websocket): + ... + + # set this future to exit the server + stop = asyncio.get_running_loop().create_future() + + async with serve(handler, host, port): + await stop + + Alternatively, call :meth:`~Server.serve_forever` to serve requests and + cancel it to stop the server:: + + server = await serve(handler, host, port) + await server.serve_forever() + + Args: + handler: Connection handler. It receives the WebSocket connection, + which is a :class:`ServerConnection`, in argument. + host: Network interfaces the server binds to. + See :meth:`~asyncio.loop.create_server` for details. + port: TCP port the server listens on. + See :meth:`~asyncio.loop.create_server` for details. + origins: Acceptable values of the ``Origin`` header, for defending + against Cross-Site WebSocket Hijacking attacks. Values can be + :class:`str` to test for an exact match or regular expressions + compiled by :func:`re.compile` to test against a pattern. Include + :obj:`None` in the list if the lack of an origin is acceptable. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + select_subprotocol: Callback for selecting a subprotocol among + those supported by the client and the server. It receives a + :class:`ServerConnection` (not a + :class:`~websockets.server.ServerProtocol`!) instance and a list of + subprotocols offered by the client. Other than the first argument, + it has the same behavior as the + :meth:`ServerProtocol.select_subprotocol + ` method. + compression: The "permessage-deflate" extension is enabled by default. + Set ``compression`` to :obj:`None` to disable it. See the + :doc:`compression guide <../../topics/compression>` for details. + process_request: Intercept the request during the opening handshake. + Return an HTTP response to force the response or :obj:`None` to + continue normally. When you force an HTTP 101 Continue response, the + handshake is successful. Else, the connection is aborted. + ``process_request`` may be a function or a coroutine. + process_response: Intercept the response during the opening handshake. + Return an HTTP response to force the response or :obj:`None` to + continue normally. When you force an HTTP 101 Continue response, the + handshake is successful. Else, the connection is aborted. + ``process_response`` may be a function or a coroutine. + server_header: Value of the ``Server`` response header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to + :obj:`None` removes the header. + open_timeout: Timeout for opening connections in seconds. + :obj:`None` disables the timeout. + ping_interval: Interval between keepalive pings in seconds. + :obj:`None` disables keepalive. + ping_timeout: Timeout for keepalive pings in seconds. + :obj:`None` disables timeouts. + close_timeout: Timeout for closing connections in seconds. + :obj:`None` disables the timeout. + max_size: Maximum size of incoming messages in bytes. + :obj:`None` disables the limit. You may pass a ``(max_message_size, + max_fragment_size)`` tuple to set different limits for messages and + fragments when you expect long messages sent in short fragments. + max_queue: High-water mark of the buffer where frames are received. + It defaults to 16 frames. The low-water mark defaults to ``max_queue + // 4``. You may pass a ``(high, low)`` tuple to set the high-water + and low-water marks. If you want to disable flow control entirely, + you may set it to ``None``, although that's a bad idea. + write_limit: High-water mark of write buffer in bytes. It is passed to + :meth:`~asyncio.WriteTransport.set_write_buffer_limits`. It defaults + to 32 KiB. You may pass a ``(high, low)`` tuple to set the + high-water and low-water marks. + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.server")``. See the + :doc:`logging guide <../../topics/logging>` for details. + create_connection: Factory for the :class:`ServerConnection` managing + the connection. Set it to a wrapper or a subclass to customize + connection handling. + + Any other keyword arguments are passed to the event loop's + :meth:`~asyncio.loop.create_server` method. + + For example: + + * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enable TLS. + + * You can set ``sock`` to provide a preexisting TCP socket. You may call + :func:`socket.create_server` (not to be confused with the event loop's + :meth:`~asyncio.loop.create_server` method) to create a suitable server + socket and customize it. + + * You can set ``start_serving`` to ``False`` to start accepting connections + only after you call :meth:`~Server.start_serving()` or + :meth:`~Server.serve_forever()`. + + """ + + def __init__( + self, + handler: Callable[[ServerConnection], Awaitable[None]], + host: str | None = None, + port: int | None = None, + *, + # WebSocket + origins: Sequence[Origin | re.Pattern[str] | None] | None = None, + extensions: Sequence[ServerExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + select_subprotocol: ( + Callable[ + [ServerConnection, Sequence[Subprotocol]], + Subprotocol | None, + ] + | None + ) = None, + compression: str | None = "deflate", + # HTTP + process_request: ( + Callable[ + [ServerConnection, Request], + Awaitable[Response | None] | Response | None, + ] + | None + ) = None, + process_response: ( + Callable[ + [ServerConnection, Request, Response], + Awaitable[Response | None] | Response | None, + ] + | None + ) = None, + server_header: str | None = SERVER, + # Timeouts + open_timeout: float | None = 10, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + # Limits + max_size: int | None | tuple[int | None, int | None] = 2**20, + max_queue: int | None | tuple[int | None, int | None] = 16, + write_limit: int | tuple[int, int | None] = 2**15, + # Logging + logger: LoggerLike | None = None, + # Escape hatch for advanced customization + create_connection: type[ServerConnection] | None = None, + # Other keyword arguments are passed to loop.create_server + **kwargs: Any, + ) -> None: + if subprotocols is not None: + validate_subprotocols(subprotocols) + + if compression == "deflate": + extensions = enable_server_permessage_deflate(extensions) + elif compression is not None: + raise ValueError(f"unsupported compression: {compression}") + + if create_connection is None: + create_connection = ServerConnection + + self.server = Server( + handler, + process_request=process_request, + process_response=process_response, + server_header=server_header, + open_timeout=open_timeout, + logger=logger, + ) + + if kwargs.get("ssl") is not None: + kwargs.setdefault("ssl_handshake_timeout", open_timeout) + if sys.version_info[:2] >= (3, 11): # pragma: no branch + kwargs.setdefault("ssl_shutdown_timeout", close_timeout) + + def factory() -> ServerConnection: + """ + Create an asyncio protocol for managing a WebSocket connection. + + """ + # Create a closure to give select_subprotocol access to connection. + protocol_select_subprotocol: ( + Callable[ + [ServerProtocol, Sequence[Subprotocol]], + Subprotocol | None, + ] + | None + ) = None + if select_subprotocol is not None: + + def protocol_select_subprotocol( + protocol: ServerProtocol, + subprotocols: Sequence[Subprotocol], + ) -> Subprotocol | None: + # mypy doesn't know that select_subprotocol is immutable. + assert select_subprotocol is not None + # Ensure this function is only used in the intended context. + assert protocol is connection.protocol + return select_subprotocol(connection, subprotocols) + + # This is a protocol in the Sans-I/O implementation of websockets. + protocol = ServerProtocol( + origins=origins, + extensions=extensions, + subprotocols=subprotocols, + select_subprotocol=protocol_select_subprotocol, + max_size=max_size, + logger=logger, + ) + # This is a connection in websockets and a protocol in asyncio. + connection = create_connection( + protocol, + self.server, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + write_limit=write_limit, + ) + return connection + + loop = asyncio.get_running_loop() + if kwargs.pop("unix", False): + self.create_server = loop.create_unix_server(factory, **kwargs) + else: + # mypy cannot tell that kwargs must provide sock when port is None. + self.create_server = loop.create_server(factory, host, port, **kwargs) # type: ignore[arg-type] + + # async with serve(...) as ...: ... + + async def __aenter__(self) -> Server: + return await self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + self.server.close() + await self.server.wait_closed() + + # ... = await serve(...) + + def __await__(self) -> Generator[Any, None, Server]: + # Create a suitable iterator by calling __await__ on a coroutine. + return self.__await_impl__().__await__() + + async def __await_impl__(self) -> Server: + server = await self.create_server + self.server.wrap(server) + return self.server + + # ... = yield from serve(...) - remove when dropping Python < 3.11 + + __iter__ = __await__ + + +def unix_serve( + handler: Callable[[ServerConnection], Awaitable[None]], + path: str | None = None, + **kwargs: Any, +) -> Awaitable[Server]: + """ + Create a WebSocket server listening on a Unix socket. + + This function is identical to :func:`serve`, except the ``host`` and + ``port`` arguments are replaced by ``path``. It's only available on Unix. + + It's useful for deploying a server behind a reverse proxy such as nginx. + + Args: + handler: Connection handler. It receives the WebSocket connection, + which is a :class:`ServerConnection`, in argument. + path: File system path to the Unix socket. + + """ + return serve(handler, unix=True, path=path, **kwargs) + + +def is_credentials(credentials: Any) -> bool: + try: + username, password = credentials + except (TypeError, ValueError): + return False + else: + return isinstance(username, str) and isinstance(password, str) + + +def basic_auth( + realm: str = "", + credentials: tuple[str, str] | Iterable[tuple[str, str]] | None = None, + check_credentials: Callable[[str, str], Awaitable[bool] | bool] | None = None, +) -> Callable[[ServerConnection, Request], Awaitable[Response | None]]: + """ + Factory for ``process_request`` to enforce HTTP Basic Authentication. + + :func:`basic_auth` is designed to integrate with :func:`serve` as follows:: + + from websockets.asyncio.server import basic_auth, serve + + async with serve( + ..., + process_request=basic_auth( + realm="my dev server", + credentials=("hello", "iloveyou"), + ), + ): + + If authentication succeeds, the connection's ``username`` attribute is set. + If it fails, the server responds with an HTTP 401 Unauthorized status. + + One of ``credentials`` or ``check_credentials`` must be provided; not both. + + Args: + realm: Scope of protection. It should contain only ASCII characters + because the encoding of non-ASCII characters is undefined. Refer to + section 2.2 of :rfc:`7235` for details. + credentials: Hard coded authorized credentials. It can be a + ``(username, password)`` pair or a list of such pairs. + check_credentials: Function or coroutine that verifies credentials. + It receives ``username`` and ``password`` arguments and returns + whether they're valid. + Raises: + TypeError: If ``credentials`` or ``check_credentials`` is wrong. + ValueError: If ``credentials`` and ``check_credentials`` are both + provided or both not provided. + + """ + if (credentials is None) == (check_credentials is None): + raise ValueError("provide either credentials or check_credentials") + + if credentials is not None: + if is_credentials(credentials): + credentials_list = [cast(tuple[str, str], credentials)] + elif isinstance(credentials, Iterable): + credentials_list = list(cast(Iterable[tuple[str, str]], credentials)) + if not all(is_credentials(item) for item in credentials_list): + raise TypeError(f"invalid credentials argument: {credentials}") + else: + raise TypeError(f"invalid credentials argument: {credentials}") + + credentials_dict = dict(credentials_list) + + def check_credentials(username: str, password: str) -> bool: + try: + expected_password = credentials_dict[username] + except KeyError: + return False + return hmac.compare_digest(expected_password, password) + + assert check_credentials is not None # help mypy + + async def process_request( + connection: ServerConnection, + request: Request, + ) -> Response | None: + """ + Perform HTTP Basic Authentication. + + If it succeeds, set the connection's ``username`` attribute and return + :obj:`None`. If it fails, return an HTTP 401 Unauthorized responss. + + """ + try: + authorization = request.headers["Authorization"] + except KeyError: + response = connection.respond( + http.HTTPStatus.UNAUTHORIZED, + "Missing credentials\n", + ) + response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm) + return response + + try: + username, password = parse_authorization_basic(authorization) + except InvalidHeader: + response = connection.respond( + http.HTTPStatus.UNAUTHORIZED, + "Unsupported credentials\n", + ) + response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm) + return response + + valid_credentials = check_credentials(username, password) + if isinstance(valid_credentials, Awaitable): + valid_credentials = await valid_credentials + + if not valid_credentials: + response = connection.respond( + http.HTTPStatus.UNAUTHORIZED, + "Invalid credentials\n", + ) + response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm) + return response + + connection.username = username + return None + + return process_request diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/auth.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..cbc1635e62d5e00339d9d197ac2c096004e86062 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/auth.py @@ -0,0 +1,18 @@ +from __future__ import annotations + +import warnings + + +with warnings.catch_warnings(): + # Suppress redundant DeprecationWarning raised by websockets.legacy. + warnings.filterwarnings("ignore", category=DeprecationWarning) + from .legacy.auth import * + from .legacy.auth import __all__ # noqa: F401 + + +warnings.warn( # deprecated in 14.0 - 2024-11-09 + "websockets.auth, an alias for websockets.legacy.auth, is deprecated; " + "see https://websockets.readthedocs.io/en/stable/howto/upgrade.html " + "for upgrade instructions", + DeprecationWarning, +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/cli.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..85b22291554308f4d94fec4e5759aba3667a7ae1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/cli.py @@ -0,0 +1,178 @@ +from __future__ import annotations + +import argparse +import asyncio +import os +import sys +from typing import Generator + +from .asyncio.client import ClientConnection, connect +from .asyncio.messages import SimpleQueue +from .exceptions import ConnectionClosed +from .frames import Close +from .streams import StreamReader +from .version import version as websockets_version + + +__all__ = ["main"] + + +def print_during_input(string: str) -> None: + sys.stdout.write( + # Save cursor position + "\N{ESC}7" + # Add a new line + "\N{LINE FEED}" + # Move cursor up + "\N{ESC}[A" + # Insert blank line, scroll last line down + "\N{ESC}[L" + # Print string in the inserted blank line + f"{string}\N{LINE FEED}" + # Restore cursor position + "\N{ESC}8" + # Move cursor down + "\N{ESC}[B" + ) + sys.stdout.flush() + + +def print_over_input(string: str) -> None: + sys.stdout.write( + # Move cursor to beginning of line + "\N{CARRIAGE RETURN}" + # Delete current line + "\N{ESC}[K" + # Print string + f"{string}\N{LINE FEED}" + ) + sys.stdout.flush() + + +class ReadLines(asyncio.Protocol): + def __init__(self) -> None: + self.reader = StreamReader() + self.messages: SimpleQueue[str] = SimpleQueue() + + def parse(self) -> Generator[None, None, None]: + while True: + sys.stdout.write("> ") + sys.stdout.flush() + line = yield from self.reader.read_line(sys.maxsize) + self.messages.put(line.decode().rstrip("\r\n")) + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + self.parser = self.parse() + next(self.parser) + + def data_received(self, data: bytes) -> None: + self.reader.feed_data(data) + next(self.parser) + + def eof_received(self) -> None: + self.reader.feed_eof() + # next(self.parser) isn't useful and would raise EOFError. + + def connection_lost(self, exc: Exception | None) -> None: + self.reader.discard() + self.messages.abort() + + +async def print_incoming_messages(websocket: ClientConnection) -> None: + async for message in websocket: + if isinstance(message, str): + print_during_input("< " + message) + else: + print_during_input("< (binary) " + message.hex()) + + +async def send_outgoing_messages( + websocket: ClientConnection, + messages: SimpleQueue[str], +) -> None: + while True: + try: + message = await messages.get() + except EOFError: + break + try: + await websocket.send(message) + except ConnectionClosed: # pragma: no cover + break + + +async def interactive_client(uri: str) -> None: + try: + websocket = await connect(uri) + except Exception as exc: + print(f"Failed to connect to {uri}: {exc}.") + sys.exit(1) + else: + print(f"Connected to {uri}.") + + loop = asyncio.get_running_loop() + transport, protocol = await loop.connect_read_pipe(ReadLines, sys.stdin) + incoming = asyncio.create_task( + print_incoming_messages(websocket), + ) + outgoing = asyncio.create_task( + send_outgoing_messages(websocket, protocol.messages), + ) + try: + await asyncio.wait( + [incoming, outgoing], + # Clean up and exit when the server closes the connection + # or the user enters EOT (^D), whichever happens first. + return_when=asyncio.FIRST_COMPLETED, + ) + # asyncio.run() cancels the main task when the user triggers SIGINT (^C). + # https://docs.python.org/3/library/asyncio-runner.html#handling-keyboard-interruption + # Clean up and exit without re-raising CancelledError to prevent Python + # from raising KeyboardInterrupt and displaying a stack track. + except asyncio.CancelledError: # pragma: no cover + pass + finally: + incoming.cancel() + outgoing.cancel() + transport.close() + + await websocket.close() + assert websocket.close_code is not None and websocket.close_reason is not None + close_status = Close(websocket.close_code, websocket.close_reason) + print_over_input(f"Connection closed: {close_status}.") + + +def main(argv: list[str] | None = None) -> None: + parser = argparse.ArgumentParser( + prog="websockets", + description="Interactive WebSocket client.", + add_help=False, + ) + group = parser.add_mutually_exclusive_group() + group.add_argument("--version", action="store_true") + group.add_argument("uri", metavar="", nargs="?") + args = parser.parse_args(argv) + + if args.version: + print(f"websockets {websockets_version}") + return + + if args.uri is None: + parser.print_usage() + sys.exit(2) + + # Enable VT100 to support ANSI escape codes in Command Prompt on Windows. + # See https://github.com/python/cpython/issues/74261 for why this works. + if sys.platform == "win32": + os.system("") + + try: + import readline # noqa: F401 + except ImportError: # readline isn't available on all platforms + pass + + # Remove the try/except block when dropping Python < 3.11. + try: + asyncio.run(interactive_client(args.uri)) + except KeyboardInterrupt: # pragma: no cover + pass diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/client.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/client.py new file mode 100644 index 0000000000000000000000000000000000000000..462eec0ece3908d54c66a6780ccce87505be0b2e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/client.py @@ -0,0 +1,391 @@ +from __future__ import annotations + +import os +import random +import warnings +from collections.abc import Generator, Sequence +from typing import Any + +from .datastructures import Headers, MultipleValuesError +from .exceptions import ( + InvalidHandshake, + InvalidHeader, + InvalidHeaderValue, + InvalidMessage, + InvalidStatus, + InvalidUpgrade, + NegotiationError, +) +from .extensions import ClientExtensionFactory, Extension +from .headers import ( + build_authorization_basic, + build_extension, + build_host, + build_subprotocol, + parse_connection, + parse_extension, + parse_subprotocol, + parse_upgrade, +) +from .http11 import Request, Response +from .imports import lazy_import +from .protocol import CLIENT, CONNECTING, OPEN, Protocol, State +from .typing import ( + ConnectionOption, + ExtensionHeader, + LoggerLike, + Origin, + Subprotocol, + UpgradeProtocol, +) +from .uri import WebSocketURI +from .utils import accept_key, generate_key + + +__all__ = ["ClientProtocol"] + + +class ClientProtocol(Protocol): + """ + Sans-I/O implementation of a WebSocket client connection. + + Args: + uri: URI of the WebSocket server, parsed + with :func:`~websockets.uri.parse_uri`. + origin: Value of the ``Origin`` header. This is useful when connecting + to a server that validates the ``Origin`` header to defend against + Cross-Site WebSocket Hijacking attacks. + extensions: List of supported extensions, in order in which they + should be tried. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + state: Initial state of the WebSocket connection. + max_size: Maximum size of incoming messages in bytes. + :obj:`None` disables the limit. You may pass a ``(max_message_size, + max_fragment_size)`` tuple to set different limits for messages and + fragments when you expect long messages sent in short fragments. + logger: Logger for this connection; + defaults to ``logging.getLogger("websockets.client")``; + see the :doc:`logging guide <../../topics/logging>` for details. + + """ + + def __init__( + self, + uri: WebSocketURI, + *, + origin: Origin | None = None, + extensions: Sequence[ClientExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + state: State = CONNECTING, + max_size: int | None | tuple[int | None, int | None] = 2**20, + logger: LoggerLike | None = None, + ) -> None: + super().__init__( + side=CLIENT, + state=state, + max_size=max_size, + logger=logger, + ) + self.uri = uri + self.origin = origin + self.available_extensions = extensions + self.available_subprotocols = subprotocols + self.key = generate_key() + + def connect(self) -> Request: + """ + Create a handshake request to open a connection. + + You must send the handshake request with :meth:`send_request`. + + You can modify it before sending it, for example to add HTTP headers. + + Returns: + WebSocket handshake request event to send to the server. + + """ + headers = Headers() + headers["Host"] = build_host(self.uri.host, self.uri.port, self.uri.secure) + if self.uri.user_info: + headers["Authorization"] = build_authorization_basic(*self.uri.user_info) + if self.origin is not None: + headers["Origin"] = self.origin + headers["Upgrade"] = "websocket" + headers["Connection"] = "Upgrade" + headers["Sec-WebSocket-Key"] = self.key + headers["Sec-WebSocket-Version"] = "13" + if self.available_extensions is not None: + headers["Sec-WebSocket-Extensions"] = build_extension( + [ + (extension_factory.name, extension_factory.get_request_params()) + for extension_factory in self.available_extensions + ] + ) + if self.available_subprotocols is not None: + headers["Sec-WebSocket-Protocol"] = build_subprotocol( + self.available_subprotocols + ) + return Request(self.uri.resource_name, headers) + + def process_response(self, response: Response) -> None: + """ + Check a handshake response. + + Args: + request: WebSocket handshake response received from the server. + + Raises: + InvalidHandshake: If the handshake response is invalid. + + """ + + if response.status_code != 101: + raise InvalidStatus(response) + + headers = response.headers + + connection: list[ConnectionOption] = sum( + [parse_connection(value) for value in headers.get_all("Connection")], [] + ) + if not any(value.lower() == "upgrade" for value in connection): + raise InvalidUpgrade( + "Connection", ", ".join(connection) if connection else None + ) + + upgrade: list[UpgradeProtocol] = sum( + [parse_upgrade(value) for value in headers.get_all("Upgrade")], [] + ) + # For compatibility with non-strict implementations, ignore case when + # checking the Upgrade header. It's supposed to be 'WebSocket'. + if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"): + raise InvalidUpgrade("Upgrade", ", ".join(upgrade) if upgrade else None) + + try: + s_w_accept = headers["Sec-WebSocket-Accept"] + except KeyError: + raise InvalidHeader("Sec-WebSocket-Accept") from None + except MultipleValuesError: + raise InvalidHeader("Sec-WebSocket-Accept", "multiple values") from None + if s_w_accept != accept_key(self.key): + raise InvalidHeaderValue("Sec-WebSocket-Accept", s_w_accept) + + self.extensions = self.process_extensions(headers) + self.subprotocol = self.process_subprotocol(headers) + + def process_extensions(self, headers: Headers) -> list[Extension]: + """ + Handle the Sec-WebSocket-Extensions HTTP response header. + + Check that each extension is supported, as well as its parameters. + + :rfc:`6455` leaves the rules up to the specification of each + extension. + + To provide this level of flexibility, for each extension accepted by + the server, we check for a match with each extension available in the + client configuration. If no match is found, an exception is raised. + + If several variants of the same extension are accepted by the server, + it may be configured several times, which won't make sense in general. + Extensions must implement their own requirements. For this purpose, + the list of previously accepted extensions is provided. + + Other requirements, for example related to mandatory extensions or the + order of extensions, may be implemented by overriding this method. + + Args: + headers: WebSocket handshake response headers. + + Returns: + List of accepted extensions. + + Raises: + InvalidHandshake: To abort the handshake. + + """ + accepted_extensions: list[Extension] = [] + + extensions = headers.get_all("Sec-WebSocket-Extensions") + + if extensions: + if self.available_extensions is None: + raise NegotiationError("no extensions supported") + + parsed_extensions: list[ExtensionHeader] = sum( + [parse_extension(header_value) for header_value in extensions], [] + ) + + for name, response_params in parsed_extensions: + for extension_factory in self.available_extensions: + # Skip non-matching extensions based on their name. + if extension_factory.name != name: + continue + + # Skip non-matching extensions based on their params. + try: + extension = extension_factory.process_response_params( + response_params, accepted_extensions + ) + except NegotiationError: + continue + + # Add matching extension to the final list. + accepted_extensions.append(extension) + + # Break out of the loop once we have a match. + break + + # If we didn't break from the loop, no extension in our list + # matched what the server sent. Fail the connection. + else: + raise NegotiationError( + f"Unsupported extension: " + f"name = {name}, params = {response_params}" + ) + + return accepted_extensions + + def process_subprotocol(self, headers: Headers) -> Subprotocol | None: + """ + Handle the Sec-WebSocket-Protocol HTTP response header. + + If provided, check that it contains exactly one supported subprotocol. + + Args: + headers: WebSocket handshake response headers. + + Returns: + Subprotocol, if one was selected. + + """ + subprotocol: Subprotocol | None = None + + subprotocols = headers.get_all("Sec-WebSocket-Protocol") + + if subprotocols: + if self.available_subprotocols is None: + raise NegotiationError("no subprotocols supported") + + parsed_subprotocols: Sequence[Subprotocol] = sum( + [parse_subprotocol(header_value) for header_value in subprotocols], [] + ) + if len(parsed_subprotocols) > 1: + raise InvalidHeader( + "Sec-WebSocket-Protocol", + f"multiple values: {', '.join(parsed_subprotocols)}", + ) + + subprotocol = parsed_subprotocols[0] + if subprotocol not in self.available_subprotocols: + raise NegotiationError(f"unsupported subprotocol: {subprotocol}") + + return subprotocol + + def send_request(self, request: Request) -> None: + """ + Send a handshake request to the server. + + Args: + request: WebSocket handshake request event. + + """ + if self.debug: + self.logger.debug("> GET %s HTTP/1.1", request.path) + for key, value in request.headers.raw_items(): + self.logger.debug("> %s: %s", key, value) + + self.writes.append(request.serialize()) + + def parse(self) -> Generator[None]: + if self.state is CONNECTING: + try: + response = yield from Response.parse( + self.reader.read_line, + self.reader.read_exact, + self.reader.read_to_eof, + ) + except Exception as exc: + self.handshake_exc = InvalidMessage( + "did not receive a valid HTTP response" + ) + self.handshake_exc.__cause__ = exc + self.send_eof() + self.parser = self.discard() + next(self.parser) # start coroutine + yield + + if self.debug: + code, phrase = response.status_code, response.reason_phrase + self.logger.debug("< HTTP/1.1 %d %s", code, phrase) + for key, value in response.headers.raw_items(): + self.logger.debug("< %s: %s", key, value) + if response.body: + self.logger.debug("< [body] (%d bytes)", len(response.body)) + + try: + self.process_response(response) + except InvalidHandshake as exc: + response._exception = exc + self.events.append(response) + self.handshake_exc = exc + self.send_eof() + self.parser = self.discard() + next(self.parser) # start coroutine + yield + + assert self.state is CONNECTING + self.state = OPEN + self.events.append(response) + + yield from super().parse() + + +class ClientConnection(ClientProtocol): + def __init__(self, *args: Any, **kwargs: Any) -> None: + warnings.warn( # deprecated in 11.0 - 2023-04-02 + "ClientConnection was renamed to ClientProtocol", + DeprecationWarning, + ) + super().__init__(*args, **kwargs) + + +BACKOFF_INITIAL_DELAY = float(os.environ.get("WEBSOCKETS_BACKOFF_INITIAL_DELAY", "5")) +BACKOFF_MIN_DELAY = float(os.environ.get("WEBSOCKETS_BACKOFF_MIN_DELAY", "3.1")) +BACKOFF_MAX_DELAY = float(os.environ.get("WEBSOCKETS_BACKOFF_MAX_DELAY", "90.0")) +BACKOFF_FACTOR = float(os.environ.get("WEBSOCKETS_BACKOFF_FACTOR", "1.618")) + + +def backoff( + initial_delay: float = BACKOFF_INITIAL_DELAY, + min_delay: float = BACKOFF_MIN_DELAY, + max_delay: float = BACKOFF_MAX_DELAY, + factor: float = BACKOFF_FACTOR, +) -> Generator[float]: + """ + Generate a series of backoff delays between reconnection attempts. + + Yields: + How many seconds to wait before retrying to connect. + + """ + # Add a random initial delay between 0 and 5 seconds. + # See 7.2.3. Recovering from Abnormal Closure in RFC 6455. + yield random.random() * initial_delay + delay = min_delay + while delay < max_delay: + yield delay + delay *= factor + while True: + yield max_delay + + +lazy_import( + globals(), + deprecated_aliases={ + # deprecated in 14.0 - 2024-11-09 + "WebSocketClientProtocol": ".legacy.client", + "connect": ".legacy.client", + "unix_connect": ".legacy.client", + }, +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/connection.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..9ed99a45af81ee02911003e33ccd96c58416ab7a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/connection.py @@ -0,0 +1,12 @@ +from __future__ import annotations + +import warnings + +from .protocol import SEND_EOF, Protocol as Connection, Side, State # noqa: F401 + + +warnings.warn( # deprecated in 11.0 - 2023-04-02 + "websockets.connection was renamed to websockets.protocol " + "and Connection was renamed to Protocol", + DeprecationWarning, +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/datastructures.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/datastructures.py new file mode 100644 index 0000000000000000000000000000000000000000..bf09959af85f6137699c7f74b48d5ef021d8055e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/datastructures.py @@ -0,0 +1,183 @@ +from __future__ import annotations + +from collections.abc import Iterable, Iterator, Mapping, MutableMapping +from typing import Any, Protocol + + +__all__ = [ + "Headers", + "HeadersLike", + "MultipleValuesError", +] + + +class MultipleValuesError(LookupError): + """ + Exception raised when :class:`Headers` has multiple values for a key. + + """ + + def __str__(self) -> str: + # Implement the same logic as KeyError_str in Objects/exceptions.c. + if len(self.args) == 1: + return repr(self.args[0]) + return super().__str__() + + +class Headers(MutableMapping[str, str]): + """ + Efficient data structure for manipulating HTTP headers. + + A :class:`list` of ``(name, values)`` is inefficient for lookups. + + A :class:`dict` doesn't suffice because header names are case-insensitive + and multiple occurrences of headers with the same name are possible. + + :class:`Headers` stores HTTP headers in a hybrid data structure to provide + efficient insertions and lookups while preserving the original data. + + In order to account for multiple values with minimal hassle, + :class:`Headers` follows this logic: + + - When getting a header with ``headers[name]``: + - if there's no value, :exc:`KeyError` is raised; + - if there's exactly one value, it's returned; + - if there's more than one value, :exc:`MultipleValuesError` is raised. + + - When setting a header with ``headers[name] = value``, the value is + appended to the list of values for that header. + + - When deleting a header with ``del headers[name]``, all values for that + header are removed (this is slow). + + Other methods for manipulating headers are consistent with this logic. + + As long as no header occurs multiple times, :class:`Headers` behaves like + :class:`dict`, except keys are lower-cased to provide case-insensitivity. + + Two methods support manipulating multiple values explicitly: + + - :meth:`get_all` returns a list of all values for a header; + - :meth:`raw_items` returns an iterator of ``(name, values)`` pairs. + + """ + + __slots__ = ["_dict", "_list"] + + # Like dict, Headers accepts an optional "mapping or iterable" argument. + def __init__(self, *args: HeadersLike, **kwargs: str) -> None: + self._dict: dict[str, list[str]] = {} + self._list: list[tuple[str, str]] = [] + self.update(*args, **kwargs) + + def __str__(self) -> str: + return "".join(f"{key}: {value}\r\n" for key, value in self._list) + "\r\n" + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self._list!r})" + + def copy(self) -> Headers: + copy = self.__class__() + copy._dict = self._dict.copy() + copy._list = self._list.copy() + return copy + + def serialize(self) -> bytes: + # Since headers only contain ASCII characters, we can keep this simple. + return str(self).encode() + + # Collection methods + + def __contains__(self, key: object) -> bool: + return isinstance(key, str) and key.lower() in self._dict + + def __iter__(self) -> Iterator[str]: + return iter(self._dict) + + def __len__(self) -> int: + return len(self._dict) + + # MutableMapping methods + + def __getitem__(self, key: str) -> str: + value = self._dict[key.lower()] + if len(value) == 1: + return value[0] + else: + raise MultipleValuesError(key) + + def __setitem__(self, key: str, value: str) -> None: + self._dict.setdefault(key.lower(), []).append(value) + self._list.append((key, value)) + + def __delitem__(self, key: str) -> None: + key_lower = key.lower() + self._dict.__delitem__(key_lower) + # This is inefficient. Fortunately deleting HTTP headers is uncommon. + self._list = [(k, v) for k, v in self._list if k.lower() != key_lower] + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, Headers): + return NotImplemented + return self._dict == other._dict + + def clear(self) -> None: + """ + Remove all headers. + + """ + self._dict = {} + self._list = [] + + def update(self, *args: HeadersLike, **kwargs: str) -> None: + """ + Update from a :class:`Headers` instance and/or keyword arguments. + + """ + args = tuple( + arg.raw_items() if isinstance(arg, Headers) else arg for arg in args + ) + super().update(*args, **kwargs) + + # Methods for handling multiple values + + def get_all(self, key: str) -> list[str]: + """ + Return the (possibly empty) list of all values for a header. + + Args: + key: Header name. + + """ + return self._dict.get(key.lower(), []) + + def raw_items(self) -> Iterator[tuple[str, str]]: + """ + Return an iterator of all values as ``(name, value)`` pairs. + + """ + return iter(self._list) + + +# copy of _typeshed.SupportsKeysAndGetItem. +class SupportsKeysAndGetItem(Protocol): # pragma: no cover + """ + Dict-like types with ``keys() -> str`` and ``__getitem__(key: str) -> str`` methods. + + """ + + def keys(self) -> Iterable[str]: ... + + def __getitem__(self, key: str) -> str: ... + + +HeadersLike = ( + Headers | Mapping[str, str] | Iterable[tuple[str, str]] | SupportsKeysAndGetItem +) +""" +Types accepted where :class:`Headers` is expected. + +In addition to :class:`Headers` itself, this includes dict-like types where both +keys and values are :class:`str`. + +""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/exceptions.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..00777386102b9dde8310ca15e7afa7c7ffa6f374 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/exceptions.py @@ -0,0 +1,473 @@ +""" +:mod:`websockets.exceptions` defines the following hierarchy of exceptions. + +* :exc:`WebSocketException` + * :exc:`ConnectionClosed` + * :exc:`ConnectionClosedOK` + * :exc:`ConnectionClosedError` + * :exc:`InvalidURI` + * :exc:`InvalidProxy` + * :exc:`InvalidHandshake` + * :exc:`SecurityError` + * :exc:`ProxyError` + * :exc:`InvalidProxyMessage` + * :exc:`InvalidProxyStatus` + * :exc:`InvalidMessage` + * :exc:`InvalidStatus` + * :exc:`InvalidStatusCode` (legacy) + * :exc:`InvalidHeader` + * :exc:`InvalidHeaderFormat` + * :exc:`InvalidHeaderValue` + * :exc:`InvalidOrigin` + * :exc:`InvalidUpgrade` + * :exc:`NegotiationError` + * :exc:`DuplicateParameter` + * :exc:`InvalidParameterName` + * :exc:`InvalidParameterValue` + * :exc:`AbortHandshake` (legacy) + * :exc:`RedirectHandshake` (legacy) + * :exc:`ProtocolError` (Sans-I/O) + * :exc:`PayloadTooBig` (Sans-I/O) + * :exc:`InvalidState` (Sans-I/O) + * :exc:`ConcurrencyError` + +""" + +from __future__ import annotations + +import warnings + +from .imports import lazy_import + + +__all__ = [ + "WebSocketException", + "ConnectionClosed", + "ConnectionClosedOK", + "ConnectionClosedError", + "InvalidURI", + "InvalidProxy", + "InvalidHandshake", + "SecurityError", + "ProxyError", + "InvalidProxyMessage", + "InvalidProxyStatus", + "InvalidMessage", + "InvalidStatus", + "InvalidHeader", + "InvalidHeaderFormat", + "InvalidHeaderValue", + "InvalidOrigin", + "InvalidUpgrade", + "NegotiationError", + "DuplicateParameter", + "InvalidParameterName", + "InvalidParameterValue", + "ProtocolError", + "PayloadTooBig", + "InvalidState", + "ConcurrencyError", +] + + +class WebSocketException(Exception): + """ + Base class for all exceptions defined by websockets. + + """ + + +class ConnectionClosed(WebSocketException): + """ + Raised when trying to interact with a closed connection. + + Attributes: + rcvd: If a close frame was received, its code and reason are available + in ``rcvd.code`` and ``rcvd.reason``. + sent: If a close frame was sent, its code and reason are available + in ``sent.code`` and ``sent.reason``. + rcvd_then_sent: If close frames were received and sent, this attribute + tells in which order this happened, from the perspective of this + side of the connection. + + """ + + def __init__( + self, + rcvd: frames.Close | None, + sent: frames.Close | None, + rcvd_then_sent: bool | None = None, + ) -> None: + self.rcvd = rcvd + self.sent = sent + self.rcvd_then_sent = rcvd_then_sent + assert (self.rcvd_then_sent is None) == (self.rcvd is None or self.sent is None) + + def __str__(self) -> str: + if self.rcvd is None: + if self.sent is None: + return "no close frame received or sent" + else: + return f"sent {self.sent}; no close frame received" + else: + if self.sent is None: + return f"received {self.rcvd}; no close frame sent" + else: + if self.rcvd_then_sent: + return f"received {self.rcvd}; then sent {self.sent}" + else: + return f"sent {self.sent}; then received {self.rcvd}" + + # code and reason attributes are provided for backwards-compatibility + + @property + def code(self) -> int: + warnings.warn( # deprecated in 13.1 - 2024-09-21 + "ConnectionClosed.code is deprecated; " + "use Protocol.close_code or ConnectionClosed.rcvd.code", + DeprecationWarning, + ) + if self.rcvd is None: + return frames.CloseCode.ABNORMAL_CLOSURE + return self.rcvd.code + + @property + def reason(self) -> str: + warnings.warn( # deprecated in 13.1 - 2024-09-21 + "ConnectionClosed.reason is deprecated; " + "use Protocol.close_reason or ConnectionClosed.rcvd.reason", + DeprecationWarning, + ) + if self.rcvd is None: + return "" + return self.rcvd.reason + + +class ConnectionClosedOK(ConnectionClosed): + """ + Like :exc:`ConnectionClosed`, when the connection terminated properly. + + A close code with code 1000 (OK) or 1001 (going away) or without a code was + received and sent. + + """ + + +class ConnectionClosedError(ConnectionClosed): + """ + Like :exc:`ConnectionClosed`, when the connection terminated with an error. + + A close frame with a code other than 1000 (OK) or 1001 (going away) was + received or sent, or the closing handshake didn't complete properly. + + """ + + +class InvalidURI(WebSocketException): + """ + Raised when connecting to a URI that isn't a valid WebSocket URI. + + """ + + def __init__(self, uri: str, msg: str) -> None: + self.uri = uri + self.msg = msg + + def __str__(self) -> str: + return f"{self.uri} isn't a valid URI: {self.msg}" + + +class InvalidProxy(WebSocketException): + """ + Raised when connecting via a proxy that isn't valid. + + """ + + def __init__(self, proxy: str, msg: str) -> None: + self.proxy = proxy + self.msg = msg + + def __str__(self) -> str: + return f"{self.proxy} isn't a valid proxy: {self.msg}" + + +class InvalidHandshake(WebSocketException): + """ + Base class for exceptions raised when the opening handshake fails. + + """ + + +class SecurityError(InvalidHandshake): + """ + Raised when a handshake request or response breaks a security rule. + + Security limits can be configured with :doc:`environment variables + <../reference/variables>`. + + """ + + +class ProxyError(InvalidHandshake): + """ + Raised when failing to connect to a proxy. + + """ + + +class InvalidProxyMessage(ProxyError): + """ + Raised when an HTTP proxy response is malformed. + + """ + + +class InvalidProxyStatus(ProxyError): + """ + Raised when an HTTP proxy rejects the connection. + + """ + + def __init__(self, response: http11.Response) -> None: + self.response = response + + def __str__(self) -> str: + return f"proxy rejected connection: HTTP {self.response.status_code:d}" + + +class InvalidMessage(InvalidHandshake): + """ + Raised when a handshake request or response is malformed. + + """ + + +class InvalidStatus(InvalidHandshake): + """ + Raised when a handshake response rejects the WebSocket upgrade. + + """ + + def __init__(self, response: http11.Response) -> None: + self.response = response + + def __str__(self) -> str: + return ( + f"server rejected WebSocket connection: HTTP {self.response.status_code:d}" + ) + + +class InvalidHeader(InvalidHandshake): + """ + Raised when an HTTP header doesn't have a valid format or value. + + """ + + def __init__(self, name: str, value: str | None = None) -> None: + self.name = name + self.value = value + + def __str__(self) -> str: + if self.value is None: + return f"missing {self.name} header" + elif self.value == "": + return f"empty {self.name} header" + else: + return f"invalid {self.name} header: {self.value}" + + +class InvalidHeaderFormat(InvalidHeader): + """ + Raised when an HTTP header cannot be parsed. + + The format of the header doesn't match the grammar for that header. + + """ + + def __init__(self, name: str, error: str, header: str, pos: int) -> None: + super().__init__(name, f"{error} at {pos} in {header}") + + +class InvalidHeaderValue(InvalidHeader): + """ + Raised when an HTTP header has a wrong value. + + The format of the header is correct but the value isn't acceptable. + + """ + + +class InvalidOrigin(InvalidHeader): + """ + Raised when the Origin header in a request isn't allowed. + + """ + + def __init__(self, origin: str | None) -> None: + super().__init__("Origin", origin) + + +class InvalidUpgrade(InvalidHeader): + """ + Raised when the Upgrade or Connection header isn't correct. + + """ + + +class NegotiationError(InvalidHandshake): + """ + Raised when negotiating an extension or a subprotocol fails. + + """ + + +class DuplicateParameter(NegotiationError): + """ + Raised when a parameter name is repeated in an extension header. + + """ + + def __init__(self, name: str) -> None: + self.name = name + + def __str__(self) -> str: + return f"duplicate parameter: {self.name}" + + +class InvalidParameterName(NegotiationError): + """ + Raised when a parameter name in an extension header is invalid. + + """ + + def __init__(self, name: str) -> None: + self.name = name + + def __str__(self) -> str: + return f"invalid parameter name: {self.name}" + + +class InvalidParameterValue(NegotiationError): + """ + Raised when a parameter value in an extension header is invalid. + + """ + + def __init__(self, name: str, value: str | None) -> None: + self.name = name + self.value = value + + def __str__(self) -> str: + if self.value is None: + return f"missing value for parameter {self.name}" + elif self.value == "": + return f"empty value for parameter {self.name}" + else: + return f"invalid value for parameter {self.name}: {self.value}" + + +class ProtocolError(WebSocketException): + """ + Raised when receiving or sending a frame that breaks the protocol. + + The Sans-I/O implementation raises this exception when: + + * receiving or sending a frame that contains invalid data; + * receiving or sending an invalid sequence of frames. + + """ + + +class PayloadTooBig(WebSocketException): + """ + Raised when parsing a frame with a payload that exceeds the maximum size. + + The Sans-I/O layer uses this exception internally. It doesn't bubble up to + the I/O layer. + + The :meth:`~websockets.extensions.Extension.decode` method of extensions + must raise :exc:`PayloadTooBig` if decoding a frame would exceed the limit. + + """ + + def __init__( + self, + size_or_message: int | None | str, + max_size: int | None = None, + current_size: int | None = None, + ) -> None: + if isinstance(size_or_message, str): + assert max_size is None + assert current_size is None + warnings.warn( # deprecated in 14.0 - 2024-11-09 + "PayloadTooBig(message) is deprecated; " + "change to PayloadTooBig(size, max_size)", + DeprecationWarning, + ) + self.message: str | None = size_or_message + else: + self.message = None + self.size: int | None = size_or_message + assert max_size is not None + self.max_size: int = max_size + self.current_size: int | None = None + self.set_current_size(current_size) + + def __str__(self) -> str: + if self.message is not None: + return self.message + else: + message = "frame " + if self.size is not None: + message += f"with {self.size} bytes " + if self.current_size is not None: + message += f"after reading {self.current_size} bytes " + message += f"exceeds limit of {self.max_size} bytes" + return message + + def set_current_size(self, current_size: int | None) -> None: + assert self.current_size is None + if current_size is not None: + self.max_size += current_size + self.current_size = current_size + + +class InvalidState(WebSocketException, AssertionError): + """ + Raised when sending a frame is forbidden in the current state. + + Specifically, the Sans-I/O layer raises this exception when: + + * sending a data frame to a connection in a state other + :attr:`~websockets.protocol.State.OPEN`; + * sending a control frame to a connection in a state other than + :attr:`~websockets.protocol.State.OPEN` or + :attr:`~websockets.protocol.State.CLOSING`. + + """ + + +class ConcurrencyError(WebSocketException, RuntimeError): + """ + Raised when receiving or sending messages concurrently. + + WebSocket is a connection-oriented protocol. Reads must be serialized; so + must be writes. However, reading and writing concurrently is possible. + + """ + + +# At the bottom to break import cycles created by type annotations. +from . import frames, http11 # noqa: E402 + + +lazy_import( + globals(), + deprecated_aliases={ + # deprecated in 14.0 - 2024-11-09 + "AbortHandshake": ".legacy.exceptions", + "InvalidStatusCode": ".legacy.exceptions", + "RedirectHandshake": ".legacy.exceptions", + "WebSocketProtocolError": ".legacy.exceptions", + }, +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/extensions/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/extensions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..84d77e4aff3c4c22b80299b7466088514c007ede --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/extensions/__init__.py @@ -0,0 +1,4 @@ +from .base import * + + +__all__ = ["Extension", "ClientExtensionFactory", "ServerExtensionFactory"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/extensions/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/extensions/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0bdfc313f9d4d84f34e53a659d77744de124e60 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/extensions/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/extensions/__pycache__/base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/extensions/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..915cdc895c8d8d11bdefe9cbfdaaa5ad7b1dde19 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/extensions/__pycache__/base.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/extensions/__pycache__/permessage_deflate.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/extensions/__pycache__/permessage_deflate.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a94e658c6491302d7a434905121b0ccc9ede51bb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/extensions/__pycache__/permessage_deflate.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/extensions/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/extensions/base.py new file mode 100644 index 0000000000000000000000000000000000000000..e5b55f616b03084f19454552fa203ef84b4b2d83 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/extensions/base.py @@ -0,0 +1,123 @@ +from __future__ import annotations + +from collections.abc import Sequence + +from ..frames import Frame +from ..typing import ExtensionName, ExtensionParameter + + +__all__ = ["Extension", "ClientExtensionFactory", "ServerExtensionFactory"] + + +class Extension: + """ + Base class for extensions. + + """ + + name: ExtensionName + """Extension identifier.""" + + def decode(self, frame: Frame, *, max_size: int | None = None) -> Frame: + """ + Decode an incoming frame. + + Args: + frame: Incoming frame. + max_size: Maximum payload size in bytes. + + Returns: + Decoded frame. + + Raises: + PayloadTooBig: If decoding the payload exceeds ``max_size``. + + """ + raise NotImplementedError + + def encode(self, frame: Frame) -> Frame: + """ + Encode an outgoing frame. + + Args: + frame: Outgoing frame. + + Returns: + Encoded frame. + + """ + raise NotImplementedError + + +class ClientExtensionFactory: + """ + Base class for client-side extension factories. + + """ + + name: ExtensionName + """Extension identifier.""" + + def get_request_params(self) -> Sequence[ExtensionParameter]: + """ + Build parameters to send to the server for this extension. + + Returns: + Parameters to send to the server. + + """ + raise NotImplementedError + + def process_response_params( + self, + params: Sequence[ExtensionParameter], + accepted_extensions: Sequence[Extension], + ) -> Extension: + """ + Process parameters received from the server. + + Args: + params: Parameters received from the server for this extension. + accepted_extensions: List of previously accepted extensions. + + Returns: + An extension instance. + + Raises: + NegotiationError: If parameters aren't acceptable. + + """ + raise NotImplementedError + + +class ServerExtensionFactory: + """ + Base class for server-side extension factories. + + """ + + name: ExtensionName + """Extension identifier.""" + + def process_request_params( + self, + params: Sequence[ExtensionParameter], + accepted_extensions: Sequence[Extension], + ) -> tuple[list[ExtensionParameter], Extension]: + """ + Process parameters received from the client. + + Args: + params: Parameters received from the client for this extension. + accepted_extensions: List of previously accepted extensions. + + Returns: + To accept the offer, parameters to send to the client for this + extension and an extension instance. + + Raises: + NegotiationError: To reject the offer, if parameters received from + the client aren't acceptable. + + """ + raise NotImplementedError diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/extensions/permessage_deflate.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/extensions/permessage_deflate.py new file mode 100644 index 0000000000000000000000000000000000000000..87f7d4b8bb12b0a32ed1cd4a62722fb3b13e9cc6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/extensions/permessage_deflate.py @@ -0,0 +1,699 @@ +from __future__ import annotations + +import zlib +from collections.abc import Sequence +from typing import Any, Literal + +from .. import frames +from ..exceptions import ( + DuplicateParameter, + InvalidParameterName, + InvalidParameterValue, + NegotiationError, + PayloadTooBig, + ProtocolError, +) +from ..typing import BytesLike, ExtensionName, ExtensionParameter +from .base import ClientExtensionFactory, Extension, ServerExtensionFactory + + +__all__ = [ + "PerMessageDeflate", + "ClientPerMessageDeflateFactory", + "enable_client_permessage_deflate", + "ServerPerMessageDeflateFactory", + "enable_server_permessage_deflate", +] + +_EMPTY_UNCOMPRESSED_BLOCK = b"\x00\x00\xff\xff" + +_MAX_WINDOW_BITS_VALUES = [str(bits) for bits in range(8, 16)] + + +class PerMessageDeflate(Extension): + """ + Per-Message Deflate extension. + + """ + + name = ExtensionName("permessage-deflate") + + def __init__( + self, + remote_no_context_takeover: bool, + local_no_context_takeover: bool, + remote_max_window_bits: int, + local_max_window_bits: int, + compress_settings: dict[Any, Any] | None = None, + ) -> None: + """ + Configure the Per-Message Deflate extension. + + """ + if compress_settings is None: + compress_settings = {} + + assert remote_no_context_takeover in [False, True] + assert local_no_context_takeover in [False, True] + assert 8 <= remote_max_window_bits <= 15 + assert 8 <= local_max_window_bits <= 15 + assert "wbits" not in compress_settings + + self.remote_no_context_takeover = remote_no_context_takeover + self.local_no_context_takeover = local_no_context_takeover + self.remote_max_window_bits = remote_max_window_bits + self.local_max_window_bits = local_max_window_bits + self.compress_settings = compress_settings + + if not self.remote_no_context_takeover: + self.decoder = zlib.decompressobj(wbits=-self.remote_max_window_bits) + + if not self.local_no_context_takeover: + self.encoder = zlib.compressobj( + wbits=-self.local_max_window_bits, + **self.compress_settings, + ) + + # To handle continuation frames properly, we must keep track of + # whether that initial frame was encoded. + self.decode_cont_data = False + # There's no need for self.encode_cont_data because we always encode + # outgoing frames, so it would always be True. + + def __repr__(self) -> str: + return ( + f"PerMessageDeflate(" + f"remote_no_context_takeover={self.remote_no_context_takeover}, " + f"local_no_context_takeover={self.local_no_context_takeover}, " + f"remote_max_window_bits={self.remote_max_window_bits}, " + f"local_max_window_bits={self.local_max_window_bits})" + ) + + def decode( + self, + frame: frames.Frame, + *, + max_size: int | None = None, + ) -> frames.Frame: + """ + Decode an incoming frame. + + """ + # Skip control frames. + if frame.opcode in frames.CTRL_OPCODES: + return frame + + # Handle continuation data frames: + # - skip if the message isn't encoded + # - reset "decode continuation data" flag if it's a final frame + if frame.opcode is frames.OP_CONT: + if not self.decode_cont_data: + return frame + if frame.fin: + self.decode_cont_data = False + + # Handle text and binary data frames: + # - skip if the message isn't encoded + # - unset the rsv1 flag on the first frame of a compressed message + # - set "decode continuation data" flag if it's a non-final frame + else: + if not frame.rsv1: + return frame + if not frame.fin: + self.decode_cont_data = True + + # Re-initialize per-message decoder. + if self.remote_no_context_takeover: + self.decoder = zlib.decompressobj(wbits=-self.remote_max_window_bits) + + # Uncompress data. Protect against zip bombs by preventing zlib from + # decompressing more than max_length bytes (except when the limit is + # disabled with max_size = None). + data: BytesLike + if frame.fin and len(frame.data) < 2044: + # Profiling shows that appending four bytes, which makes a copy, is + # faster than calling decompress() again when data is less than 2kB. + data = bytes(frame.data) + _EMPTY_UNCOMPRESSED_BLOCK + else: + data = frame.data + max_length = 0 if max_size is None else max_size + try: + data = self.decoder.decompress(data, max_length) + if self.decoder.unconsumed_tail: + assert max_size is not None # help mypy + raise PayloadTooBig(None, max_size) + if frame.fin and len(frame.data) >= 2044: + # This cannot generate additional data. + self.decoder.decompress(_EMPTY_UNCOMPRESSED_BLOCK) + except zlib.error as exc: + raise ProtocolError("decompression failed") from exc + + # Allow garbage collection of the decoder if it won't be reused. + if frame.fin and self.remote_no_context_takeover: + del self.decoder + + return frames.Frame( + frame.opcode, + data, + frame.fin, + # Unset the rsv1 flag on the first frame of a compressed message. + False, + frame.rsv2, + frame.rsv3, + ) + + def encode(self, frame: frames.Frame) -> frames.Frame: + """ + Encode an outgoing frame. + + """ + # Skip control frames. + if frame.opcode in frames.CTRL_OPCODES: + return frame + + # Since we always encode messages, there's no "encode continuation + # data" flag similar to "decode continuation data" at this time. + + if frame.opcode is not frames.OP_CONT: + # Re-initialize per-message decoder. + if self.local_no_context_takeover: + self.encoder = zlib.compressobj( + wbits=-self.local_max_window_bits, + **self.compress_settings, + ) + + # Compress data. + data: BytesLike + data = self.encoder.compress(frame.data) + self.encoder.flush(zlib.Z_SYNC_FLUSH) + if frame.fin: + # Sync flush generates between 5 or 6 bytes, ending with the bytes + # 0x00 0x00 0xff 0xff, which must be removed. + assert data[-4:] == _EMPTY_UNCOMPRESSED_BLOCK + # Making a copy is faster than memoryview(a)[:-4] until 2kB. + if len(data) < 2048: + data = data[:-4] + else: + data = memoryview(data)[:-4] + + # Allow garbage collection of the encoder if it won't be reused. + if frame.fin and self.local_no_context_takeover: + del self.encoder + + return frames.Frame( + frame.opcode, + data, + frame.fin, + # Set the rsv1 flag on the first frame of a compressed message. + frame.opcode is not frames.OP_CONT, + frame.rsv2, + frame.rsv3, + ) + + +def _build_parameters( + server_no_context_takeover: bool, + client_no_context_takeover: bool, + server_max_window_bits: int | None, + client_max_window_bits: int | Literal[True] | None, +) -> list[ExtensionParameter]: + """ + Build a list of ``(name, value)`` pairs for some compression parameters. + + """ + params: list[ExtensionParameter] = [] + if server_no_context_takeover: + params.append(("server_no_context_takeover", None)) + if client_no_context_takeover: + params.append(("client_no_context_takeover", None)) + if server_max_window_bits: + params.append(("server_max_window_bits", str(server_max_window_bits))) + if client_max_window_bits is True: # only in handshake requests + params.append(("client_max_window_bits", None)) + elif client_max_window_bits: + params.append(("client_max_window_bits", str(client_max_window_bits))) + return params + + +def _extract_parameters( + params: Sequence[ExtensionParameter], *, is_server: bool +) -> tuple[bool, bool, int | None, int | Literal[True] | None]: + """ + Extract compression parameters from a list of ``(name, value)`` pairs. + + If ``is_server`` is :obj:`True`, ``client_max_window_bits`` may be + provided without a value. This is only allowed in handshake requests. + + """ + server_no_context_takeover: bool = False + client_no_context_takeover: bool = False + server_max_window_bits: int | None = None + client_max_window_bits: int | Literal[True] | None = None + + for name, value in params: + if name == "server_no_context_takeover": + if server_no_context_takeover: + raise DuplicateParameter(name) + if value is None: + server_no_context_takeover = True + else: + raise InvalidParameterValue(name, value) + + elif name == "client_no_context_takeover": + if client_no_context_takeover: + raise DuplicateParameter(name) + if value is None: + client_no_context_takeover = True + else: + raise InvalidParameterValue(name, value) + + elif name == "server_max_window_bits": + if server_max_window_bits is not None: + raise DuplicateParameter(name) + if value in _MAX_WINDOW_BITS_VALUES: + server_max_window_bits = int(value) + else: + raise InvalidParameterValue(name, value) + + elif name == "client_max_window_bits": + if client_max_window_bits is not None: + raise DuplicateParameter(name) + if is_server and value is None: # only in handshake requests + client_max_window_bits = True + elif value in _MAX_WINDOW_BITS_VALUES: + client_max_window_bits = int(value) + else: + raise InvalidParameterValue(name, value) + + else: + raise InvalidParameterName(name) + + return ( + server_no_context_takeover, + client_no_context_takeover, + server_max_window_bits, + client_max_window_bits, + ) + + +class ClientPerMessageDeflateFactory(ClientExtensionFactory): + """ + Client-side extension factory for the Per-Message Deflate extension. + + Parameters behave as described in `section 7.1 of RFC 7692`_. + + .. _section 7.1 of RFC 7692: https://datatracker.ietf.org/doc/html/rfc7692#section-7.1 + + Set them to :obj:`True` to include them in the negotiation offer without a + value or to an integer value to include them with this value. + + Args: + server_no_context_takeover: Prevent server from using context takeover. + client_no_context_takeover: Prevent client from using context takeover. + server_max_window_bits: Maximum size of the server's LZ77 sliding window + in bits, between 8 and 15. + client_max_window_bits: Maximum size of the client's LZ77 sliding window + in bits, between 8 and 15, or :obj:`True` to indicate support without + setting a limit. + compress_settings: Additional keyword arguments for :func:`zlib.compressobj`, + excluding ``wbits``. + + """ + + name = ExtensionName("permessage-deflate") + + def __init__( + self, + server_no_context_takeover: bool = False, + client_no_context_takeover: bool = False, + server_max_window_bits: int | None = None, + client_max_window_bits: int | Literal[True] | None = True, + compress_settings: dict[str, Any] | None = None, + ) -> None: + """ + Configure the Per-Message Deflate extension factory. + + """ + if not (server_max_window_bits is None or 8 <= server_max_window_bits <= 15): + raise ValueError("server_max_window_bits must be between 8 and 15") + if not ( + client_max_window_bits is None + or client_max_window_bits is True + or 8 <= client_max_window_bits <= 15 + ): + raise ValueError("client_max_window_bits must be between 8 and 15") + if compress_settings is not None and "wbits" in compress_settings: + raise ValueError( + "compress_settings must not include wbits, " + "set client_max_window_bits instead" + ) + + self.server_no_context_takeover = server_no_context_takeover + self.client_no_context_takeover = client_no_context_takeover + self.server_max_window_bits = server_max_window_bits + self.client_max_window_bits = client_max_window_bits + self.compress_settings = compress_settings + + def get_request_params(self) -> Sequence[ExtensionParameter]: + """ + Build request parameters. + + """ + return _build_parameters( + self.server_no_context_takeover, + self.client_no_context_takeover, + self.server_max_window_bits, + self.client_max_window_bits, + ) + + def process_response_params( + self, + params: Sequence[ExtensionParameter], + accepted_extensions: Sequence[Extension], + ) -> PerMessageDeflate: + """ + Process response parameters. + + Return an extension instance. + + """ + if any(other.name == self.name for other in accepted_extensions): + raise NegotiationError(f"received duplicate {self.name}") + + # Request parameters are available in instance variables. + + # Load response parameters in local variables. + ( + server_no_context_takeover, + client_no_context_takeover, + server_max_window_bits, + client_max_window_bits, + ) = _extract_parameters(params, is_server=False) + + # After comparing the request and the response, the final + # configuration must be available in the local variables. + + # server_no_context_takeover + # + # Req. Resp. Result + # ------ ------ -------------------------------------------------- + # False False False + # False True True + # True False Error! + # True True True + + if self.server_no_context_takeover: + if not server_no_context_takeover: + raise NegotiationError("expected server_no_context_takeover") + + # client_no_context_takeover + # + # Req. Resp. Result + # ------ ------ -------------------------------------------------- + # False False False + # False True True + # True False True - must change value + # True True True + + if self.client_no_context_takeover: + if not client_no_context_takeover: + client_no_context_takeover = True + + # server_max_window_bits + + # Req. Resp. Result + # ------ ------ -------------------------------------------------- + # None None None + # None 8≤M≤15 M + # 8≤N≤15 None Error! + # 8≤N≤15 8≤M≤N M + # 8≤N≤15 N self.server_max_window_bits: + raise NegotiationError("unsupported server_max_window_bits") + + # client_max_window_bits + + # Req. Resp. Result + # ------ ------ -------------------------------------------------- + # None None None + # None 8≤M≤15 Error! + # True None None + # True 8≤M≤15 M + # 8≤N≤15 None N - must change value + # 8≤N≤15 8≤M≤N M + # 8≤N≤15 N self.client_max_window_bits: + raise NegotiationError("unsupported client_max_window_bits") + + return PerMessageDeflate( + server_no_context_takeover, # remote_no_context_takeover + client_no_context_takeover, # local_no_context_takeover + server_max_window_bits or 15, # remote_max_window_bits + client_max_window_bits or 15, # local_max_window_bits + self.compress_settings, + ) + + +def enable_client_permessage_deflate( + extensions: Sequence[ClientExtensionFactory] | None, +) -> Sequence[ClientExtensionFactory]: + """ + Enable Per-Message Deflate with default settings in client extensions. + + If the extension is already present, perhaps with non-default settings, + the configuration isn't changed. + + """ + if extensions is None: + extensions = [] + if not any( + extension_factory.name == ClientPerMessageDeflateFactory.name + for extension_factory in extensions + ): + extensions = list(extensions) + [ + ClientPerMessageDeflateFactory( + compress_settings={"memLevel": 5}, + ) + ] + return extensions + + +class ServerPerMessageDeflateFactory(ServerExtensionFactory): + """ + Server-side extension factory for the Per-Message Deflate extension. + + Parameters behave as described in `section 7.1 of RFC 7692`_. + + .. _section 7.1 of RFC 7692: https://datatracker.ietf.org/doc/html/rfc7692#section-7.1 + + Set them to :obj:`True` to include them in the negotiation offer without a + value or to an integer value to include them with this value. + + Args: + server_no_context_takeover: Prevent server from using context takeover. + client_no_context_takeover: Prevent client from using context takeover. + server_max_window_bits: Maximum size of the server's LZ77 sliding window + in bits, between 8 and 15. + client_max_window_bits: Maximum size of the client's LZ77 sliding window + in bits, between 8 and 15. + compress_settings: Additional keyword arguments for :func:`zlib.compressobj`, + excluding ``wbits``. + require_client_max_window_bits: Do not enable compression at all if + client doesn't advertise support for ``client_max_window_bits``; + the default behavior is to enable compression without enforcing + ``client_max_window_bits``. + + """ + + name = ExtensionName("permessage-deflate") + + def __init__( + self, + server_no_context_takeover: bool = False, + client_no_context_takeover: bool = False, + server_max_window_bits: int | None = None, + client_max_window_bits: int | None = None, + compress_settings: dict[str, Any] | None = None, + require_client_max_window_bits: bool = False, + ) -> None: + """ + Configure the Per-Message Deflate extension factory. + + """ + if not (server_max_window_bits is None or 8 <= server_max_window_bits <= 15): + raise ValueError("server_max_window_bits must be between 8 and 15") + if not (client_max_window_bits is None or 8 <= client_max_window_bits <= 15): + raise ValueError("client_max_window_bits must be between 8 and 15") + if compress_settings is not None and "wbits" in compress_settings: + raise ValueError( + "compress_settings must not include wbits, " + "set server_max_window_bits instead" + ) + if client_max_window_bits is None and require_client_max_window_bits: + raise ValueError( + "require_client_max_window_bits is enabled, " + "but client_max_window_bits isn't configured" + ) + + self.server_no_context_takeover = server_no_context_takeover + self.client_no_context_takeover = client_no_context_takeover + self.server_max_window_bits = server_max_window_bits + self.client_max_window_bits = client_max_window_bits + self.compress_settings = compress_settings + self.require_client_max_window_bits = require_client_max_window_bits + + def process_request_params( + self, + params: Sequence[ExtensionParameter], + accepted_extensions: Sequence[Extension], + ) -> tuple[list[ExtensionParameter], PerMessageDeflate]: + """ + Process request parameters. + + Return response params and an extension instance. + + """ + if any(other.name == self.name for other in accepted_extensions): + raise NegotiationError(f"skipped duplicate {self.name}") + + # Load request parameters in local variables. + ( + server_no_context_takeover, + client_no_context_takeover, + server_max_window_bits, + client_max_window_bits, + ) = _extract_parameters(params, is_server=True) + + # Configuration parameters are available in instance variables. + + # After comparing the request and the configuration, the response must + # be available in the local variables. + + # server_no_context_takeover + # + # Config Req. Resp. + # ------ ------ -------------------------------------------------- + # False False False + # False True True + # True False True - must change value to True + # True True True + + if self.server_no_context_takeover: + if not server_no_context_takeover: + server_no_context_takeover = True + + # client_no_context_takeover + # + # Config Req. Resp. + # ------ ------ -------------------------------------------------- + # False False False + # False True True (or False) + # True False True - must change value to True + # True True True (or False) + + if self.client_no_context_takeover: + if not client_no_context_takeover: + client_no_context_takeover = True + + # server_max_window_bits + + # Config Req. Resp. + # ------ ------ -------------------------------------------------- + # None None None + # None 8≤M≤15 M + # 8≤N≤15 None N - must change value + # 8≤N≤15 8≤M≤N M + # 8≤N≤15 N self.server_max_window_bits: + server_max_window_bits = self.server_max_window_bits + + # client_max_window_bits + + # Config Req. Resp. + # ------ ------ -------------------------------------------------- + # None None None + # None True None - must change value + # None 8≤M≤15 M (or None) + # 8≤N≤15 None None or Error! + # 8≤N≤15 True N - must change value + # 8≤N≤15 8≤M≤N M (or None) + # 8≤N≤15 N Sequence[ServerExtensionFactory]: + """ + Enable Per-Message Deflate with default settings in server extensions. + + If the extension is already present, perhaps with non-default settings, + the configuration isn't changed. + + """ + if extensions is None: + extensions = [] + if not any( + ext_factory.name == ServerPerMessageDeflateFactory.name + for ext_factory in extensions + ): + extensions = list(extensions) + [ + ServerPerMessageDeflateFactory( + server_max_window_bits=12, + client_max_window_bits=12, + compress_settings={"memLevel": 5}, + ) + ] + return extensions diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/frames.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/frames.py new file mode 100644 index 0000000000000000000000000000000000000000..db1955ac32724941686b78f89baf68e5f6350e9d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/frames.py @@ -0,0 +1,431 @@ +from __future__ import annotations + +import dataclasses +import enum +import io +import os +import secrets +import struct +from collections.abc import Generator, Sequence +from typing import Callable + +from .exceptions import PayloadTooBig, ProtocolError +from .typing import BytesLike + + +try: + from .speedups import apply_mask +except ImportError: + from .utils import apply_mask + + +__all__ = [ + "Opcode", + "OP_CONT", + "OP_TEXT", + "OP_BINARY", + "OP_CLOSE", + "OP_PING", + "OP_PONG", + "DATA_OPCODES", + "CTRL_OPCODES", + "CloseCode", + "Frame", + "Close", +] + + +class Opcode(enum.IntEnum): + """Opcode values for WebSocket frames.""" + + CONT, TEXT, BINARY = 0x00, 0x01, 0x02 + CLOSE, PING, PONG = 0x08, 0x09, 0x0A + + +OP_CONT = Opcode.CONT +OP_TEXT = Opcode.TEXT +OP_BINARY = Opcode.BINARY +OP_CLOSE = Opcode.CLOSE +OP_PING = Opcode.PING +OP_PONG = Opcode.PONG + +DATA_OPCODES = OP_CONT, OP_TEXT, OP_BINARY +CTRL_OPCODES = OP_CLOSE, OP_PING, OP_PONG + + +class CloseCode(enum.IntEnum): + """Close code values for WebSocket close frames.""" + + NORMAL_CLOSURE = 1000 + GOING_AWAY = 1001 + PROTOCOL_ERROR = 1002 + UNSUPPORTED_DATA = 1003 + # 1004 is reserved + NO_STATUS_RCVD = 1005 + ABNORMAL_CLOSURE = 1006 + INVALID_DATA = 1007 + POLICY_VIOLATION = 1008 + MESSAGE_TOO_BIG = 1009 + MANDATORY_EXTENSION = 1010 + INTERNAL_ERROR = 1011 + SERVICE_RESTART = 1012 + TRY_AGAIN_LATER = 1013 + BAD_GATEWAY = 1014 + TLS_HANDSHAKE = 1015 + + +# See https://www.iana.org/assignments/websocket/websocket.xhtml +CLOSE_CODE_EXPLANATIONS: dict[int, str] = { + CloseCode.NORMAL_CLOSURE: "OK", + CloseCode.GOING_AWAY: "going away", + CloseCode.PROTOCOL_ERROR: "protocol error", + CloseCode.UNSUPPORTED_DATA: "unsupported data", + CloseCode.NO_STATUS_RCVD: "no status received [internal]", + CloseCode.ABNORMAL_CLOSURE: "abnormal closure [internal]", + CloseCode.INVALID_DATA: "invalid frame payload data", + CloseCode.POLICY_VIOLATION: "policy violation", + CloseCode.MESSAGE_TOO_BIG: "message too big", + CloseCode.MANDATORY_EXTENSION: "mandatory extension", + CloseCode.INTERNAL_ERROR: "internal error", + CloseCode.SERVICE_RESTART: "service restart", + CloseCode.TRY_AGAIN_LATER: "try again later", + CloseCode.BAD_GATEWAY: "bad gateway", + CloseCode.TLS_HANDSHAKE: "TLS handshake failure [internal]", +} + + +# Close code that are allowed in a close frame. +# Using a set optimizes `code in EXTERNAL_CLOSE_CODES`. +EXTERNAL_CLOSE_CODES = { + CloseCode.NORMAL_CLOSURE, + CloseCode.GOING_AWAY, + CloseCode.PROTOCOL_ERROR, + CloseCode.UNSUPPORTED_DATA, + CloseCode.INVALID_DATA, + CloseCode.POLICY_VIOLATION, + CloseCode.MESSAGE_TOO_BIG, + CloseCode.MANDATORY_EXTENSION, + CloseCode.INTERNAL_ERROR, + CloseCode.SERVICE_RESTART, + CloseCode.TRY_AGAIN_LATER, + CloseCode.BAD_GATEWAY, +} + + +OK_CLOSE_CODES = { + CloseCode.NORMAL_CLOSURE, + CloseCode.GOING_AWAY, + CloseCode.NO_STATUS_RCVD, +} + + +@dataclasses.dataclass +class Frame: + """ + WebSocket frame. + + Attributes: + opcode: Opcode. + data: Payload data. + fin: FIN bit. + rsv1: RSV1 bit. + rsv2: RSV2 bit. + rsv3: RSV3 bit. + + Only these fields are needed. The MASK bit, payload length and masking-key + are handled on the fly when parsing and serializing frames. + + """ + + opcode: Opcode + data: BytesLike + fin: bool = True + rsv1: bool = False + rsv2: bool = False + rsv3: bool = False + + # Configure if you want to see more in logs. Should be a multiple of 3. + MAX_LOG_SIZE = int(os.environ.get("WEBSOCKETS_MAX_LOG_SIZE", "75")) + + def __str__(self) -> str: + """ + Return a human-readable representation of a frame. + + """ + coding = None + length = f"{len(self.data)} byte{'' if len(self.data) == 1 else 's'}" + non_final = "" if self.fin else "continued" + + if self.opcode is OP_TEXT: + # Decoding only the beginning and the end is needlessly hard. + # Decode the entire payload then elide later if necessary. + data = repr(bytes(self.data).decode()) + elif self.opcode is OP_BINARY: + # We'll show at most the first 16 bytes and the last 8 bytes. + # Encode just what we need, plus two dummy bytes to elide later. + binary = self.data + if len(binary) > self.MAX_LOG_SIZE // 3: + cut = (self.MAX_LOG_SIZE // 3 - 1) // 3 # by default cut = 8 + binary = b"".join([binary[: 2 * cut], b"\x00\x00", binary[-cut:]]) + data = " ".join(f"{byte:02x}" for byte in binary) + elif self.opcode is OP_CLOSE: + data = str(Close.parse(self.data)) + elif self.data: + # We don't know if a Continuation frame contains text or binary. + # Ping and Pong frames could contain UTF-8. + # Attempt to decode as UTF-8 and display it as text; fallback to + # binary. If self.data is a memoryview, it has no decode() method, + # which raises AttributeError. + try: + data = repr(bytes(self.data).decode()) + coding = "text" + except (UnicodeDecodeError, AttributeError): + binary = self.data + if len(binary) > self.MAX_LOG_SIZE // 3: + cut = (self.MAX_LOG_SIZE // 3 - 1) // 3 # by default cut = 8 + binary = b"".join([binary[: 2 * cut], b"\x00\x00", binary[-cut:]]) + data = " ".join(f"{byte:02x}" for byte in binary) + coding = "binary" + else: + data = "''" + + if len(data) > self.MAX_LOG_SIZE: + cut = self.MAX_LOG_SIZE // 3 - 1 # by default cut = 24 + data = data[: 2 * cut] + "..." + data[-cut:] + + metadata = ", ".join(filter(None, [coding, length, non_final])) + + return f"{self.opcode.name} {data} [{metadata}]" + + @classmethod + def parse( + cls, + read_exact: Callable[[int], Generator[None, None, bytes | bytearray]], + *, + mask: bool, + max_size: int | None = None, + extensions: Sequence[extensions.Extension] | None = None, + ) -> Generator[None, None, Frame]: + """ + Parse a WebSocket frame. + + This is a generator-based coroutine. + + Args: + read_exact: Generator-based coroutine that reads the requested + bytes or raises an exception if there isn't enough data. + mask: Whether the frame should be masked i.e. whether the read + happens on the server side. + max_size: Maximum payload size in bytes. + extensions: List of extensions, applied in reverse order. + + Raises: + EOFError: If the connection is closed without a full WebSocket frame. + PayloadTooBig: If the frame's payload size exceeds ``max_size``. + ProtocolError: If the frame contains incorrect values. + + """ + # Read the header. + data = yield from read_exact(2) + head1, head2 = struct.unpack("!BB", data) + + # While not Pythonic, this is marginally faster than calling bool(). + fin = True if head1 & 0b10000000 else False + rsv1 = True if head1 & 0b01000000 else False + rsv2 = True if head1 & 0b00100000 else False + rsv3 = True if head1 & 0b00010000 else False + + try: + opcode = Opcode(head1 & 0b00001111) + except ValueError as exc: + raise ProtocolError("invalid opcode") from exc + + if (True if head2 & 0b10000000 else False) != mask: + raise ProtocolError("incorrect masking") + + length = head2 & 0b01111111 + if length == 126: + data = yield from read_exact(2) + (length,) = struct.unpack("!H", data) + elif length == 127: + data = yield from read_exact(8) + (length,) = struct.unpack("!Q", data) + if max_size is not None and length > max_size: + raise PayloadTooBig(length, max_size) + if mask: + mask_bytes = yield from read_exact(4) + + # Read the data. + data = yield from read_exact(length) + if mask: + data = apply_mask(data, mask_bytes) + + frame = cls(opcode, data, fin, rsv1, rsv2, rsv3) + + if extensions is None: + extensions = [] + for extension in reversed(extensions): + frame = extension.decode(frame, max_size=max_size) + + frame.check() + + return frame + + def serialize( + self, + *, + mask: bool, + extensions: Sequence[extensions.Extension] | None = None, + ) -> bytes: + """ + Serialize a WebSocket frame. + + Args: + mask: Whether the frame should be masked i.e. whether the write + happens on the client side. + extensions: List of extensions, applied in order. + + Raises: + ProtocolError: If the frame contains incorrect values. + + """ + self.check() + + if extensions is None: + extensions = [] + for extension in extensions: + self = extension.encode(self) + + output = io.BytesIO() + + # Prepare the header. + head1 = ( + (0b10000000 if self.fin else 0) + | (0b01000000 if self.rsv1 else 0) + | (0b00100000 if self.rsv2 else 0) + | (0b00010000 if self.rsv3 else 0) + | self.opcode + ) + + head2 = 0b10000000 if mask else 0 + + length = len(self.data) + if length < 126: + output.write(struct.pack("!BB", head1, head2 | length)) + elif length < 65536: + output.write(struct.pack("!BBH", head1, head2 | 126, length)) + else: + output.write(struct.pack("!BBQ", head1, head2 | 127, length)) + + if mask: + mask_bytes = secrets.token_bytes(4) + output.write(mask_bytes) + + # Prepare the data. + data: BytesLike + if mask: + data = apply_mask(self.data, mask_bytes) + else: + data = self.data + output.write(data) + + return output.getvalue() + + def check(self) -> None: + """ + Check that reserved bits and opcode have acceptable values. + + Raises: + ProtocolError: If a reserved bit or the opcode is invalid. + + """ + if self.rsv1 or self.rsv2 or self.rsv3: + raise ProtocolError("reserved bits must be 0") + + if self.opcode in CTRL_OPCODES: + if len(self.data) > 125: + raise ProtocolError("control frame too long") + if not self.fin: + raise ProtocolError("fragmented control frame") + + +@dataclasses.dataclass +class Close: + """ + Code and reason for WebSocket close frames. + + Attributes: + code: Close code. + reason: Close reason. + + """ + + code: CloseCode | int + reason: str + + def __str__(self) -> str: + """ + Return a human-readable representation of a close code and reason. + + """ + if 3000 <= self.code < 4000: + explanation = "registered" + elif 4000 <= self.code < 5000: + explanation = "private use" + else: + explanation = CLOSE_CODE_EXPLANATIONS.get(self.code, "unknown") + result = f"{self.code} ({explanation})" + + if self.reason: + result = f"{result} {self.reason}" + + return result + + @classmethod + def parse(cls, data: BytesLike) -> Close: + """ + Parse the payload of a close frame. + + Args: + data: Payload of the close frame. + + Raises: + ProtocolError: If data is ill-formed. + UnicodeDecodeError: If the reason isn't valid UTF-8. + + """ + if isinstance(data, memoryview): + raise AssertionError("only compressed outgoing frames use memoryview") + if len(data) >= 2: + (code,) = struct.unpack("!H", data[:2]) + reason = data[2:].decode() + close = cls(code, reason) + close.check() + return close + elif len(data) == 0: + return cls(CloseCode.NO_STATUS_RCVD, "") + else: + raise ProtocolError("close frame too short") + + def serialize(self) -> bytes: + """ + Serialize the payload of a close frame. + + """ + self.check() + return struct.pack("!H", self.code) + self.reason.encode() + + def check(self) -> None: + """ + Check that the close code has a valid value for a close frame. + + Raises: + ProtocolError: If the close code is invalid. + + """ + if not (self.code in EXTERNAL_CLOSE_CODES or 3000 <= self.code < 5000): + raise ProtocolError("invalid status code") + + +# At the bottom to break import cycles created by type annotations. +from . import extensions # noqa: E402 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/headers.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/headers.py new file mode 100644 index 0000000000000000000000000000000000000000..0bfb255376f01a078134f825cf56610a381ab4ab --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/headers.py @@ -0,0 +1,586 @@ +from __future__ import annotations + +import base64 +import binascii +import ipaddress +import re +from collections.abc import Sequence +from typing import Callable, TypeVar, cast + +from .exceptions import InvalidHeaderFormat, InvalidHeaderValue +from .typing import ( + ConnectionOption, + ExtensionHeader, + ExtensionName, + ExtensionParameter, + Subprotocol, + UpgradeProtocol, +) + + +__all__ = [ + "build_host", + "parse_connection", + "parse_upgrade", + "parse_extension", + "build_extension", + "parse_subprotocol", + "build_subprotocol", + "validate_subprotocols", + "build_www_authenticate_basic", + "parse_authorization_basic", + "build_authorization_basic", +] + + +T = TypeVar("T") + + +def build_host( + host: str, + port: int, + secure: bool, + *, + always_include_port: bool = False, +) -> str: + """ + Build a ``Host`` header. + + """ + # https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.2 + # IPv6 addresses must be enclosed in brackets. + try: + address = ipaddress.ip_address(host) + except ValueError: + # host is a hostname + pass + else: + # host is an IP address + if address.version == 6: + host = f"[{host}]" + + if always_include_port or port != (443 if secure else 80): + host = f"{host}:{port}" + + return host + + +# To avoid a dependency on a parsing library, we implement manually the ABNF +# described in https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 and +# https://datatracker.ietf.org/doc/html/rfc7230#appendix-B. + + +def peek_ahead(header: str, pos: int) -> str | None: + """ + Return the next character from ``header`` at the given position. + + Return :obj:`None` at the end of ``header``. + + We never need to peek more than one character ahead. + + """ + return None if pos == len(header) else header[pos] + + +_OWS_re = re.compile(r"[\t ]*") + + +def parse_OWS(header: str, pos: int) -> int: + """ + Parse optional whitespace from ``header`` at the given position. + + Return the new position. + + The whitespace itself isn't returned because it isn't significant. + + """ + # There's always a match, possibly empty, whose content doesn't matter. + match = _OWS_re.match(header, pos) + assert match is not None + return match.end() + + +_token_re = re.compile(r"[-!#$%&\'*+.^_`|~0-9a-zA-Z]+") + + +def parse_token(header: str, pos: int, header_name: str) -> tuple[str, int]: + """ + Parse a token from ``header`` at the given position. + + Return the token value and the new position. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + match = _token_re.match(header, pos) + if match is None: + raise InvalidHeaderFormat(header_name, "expected token", header, pos) + return match.group(), match.end() + + +_quoted_string_re = re.compile( + r'"(?:[\x09\x20-\x21\x23-\x5b\x5d-\x7e]|\\[\x09\x20-\x7e\x80-\xff])*"' +) + + +_unquote_re = re.compile(r"\\([\x09\x20-\x7e\x80-\xff])") + + +def parse_quoted_string(header: str, pos: int, header_name: str) -> tuple[str, int]: + """ + Parse a quoted string from ``header`` at the given position. + + Return the unquoted value and the new position. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + match = _quoted_string_re.match(header, pos) + if match is None: + raise InvalidHeaderFormat(header_name, "expected quoted string", header, pos) + return _unquote_re.sub(r"\1", match.group()[1:-1]), match.end() + + +_quotable_re = re.compile(r"[\x09\x20-\x7e\x80-\xff]*") + + +_quote_re = re.compile(r"([\x22\x5c])") + + +def build_quoted_string(value: str) -> str: + """ + Format ``value`` as a quoted string. + + This is the reverse of :func:`parse_quoted_string`. + + """ + match = _quotable_re.fullmatch(value) + if match is None: + raise ValueError("invalid characters for quoted-string encoding") + return '"' + _quote_re.sub(r"\\\1", value) + '"' + + +def parse_list( + parse_item: Callable[[str, int, str], tuple[T, int]], + header: str, + pos: int, + header_name: str, +) -> list[T]: + """ + Parse a comma-separated list from ``header`` at the given position. + + This is appropriate for parsing values with the following grammar: + + 1#item + + ``parse_item`` parses one item. + + ``header`` is assumed not to start or end with whitespace. + + (This function is designed for parsing an entire header value and + :func:`~websockets.http.read_headers` strips whitespace from values.) + + Return a list of items. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + # Per https://datatracker.ietf.org/doc/html/rfc7230#section-7, "a recipient + # MUST parse and ignore a reasonable number of empty list elements"; + # hence while loops that remove extra delimiters. + + # Remove extra delimiters before the first item. + while peek_ahead(header, pos) == ",": + pos = parse_OWS(header, pos + 1) + + items = [] + while True: + # Loop invariant: a item starts at pos in header. + item, pos = parse_item(header, pos, header_name) + items.append(item) + pos = parse_OWS(header, pos) + + # We may have reached the end of the header. + if pos == len(header): + break + + # There must be a delimiter after each element except the last one. + if peek_ahead(header, pos) == ",": + pos = parse_OWS(header, pos + 1) + else: + raise InvalidHeaderFormat(header_name, "expected comma", header, pos) + + # Remove extra delimiters before the next item. + while peek_ahead(header, pos) == ",": + pos = parse_OWS(header, pos + 1) + + # We may have reached the end of the header. + if pos == len(header): + break + + # Since we only advance in the header by one character with peek_ahead() + # or with the end position of a regex match, we can't overshoot the end. + assert pos == len(header) + + return items + + +def parse_connection_option( + header: str, pos: int, header_name: str +) -> tuple[ConnectionOption, int]: + """ + Parse a Connection option from ``header`` at the given position. + + Return the protocol value and the new position. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + item, pos = parse_token(header, pos, header_name) + return cast(ConnectionOption, item), pos + + +def parse_connection(header: str) -> list[ConnectionOption]: + """ + Parse a ``Connection`` header. + + Return a list of HTTP connection options. + + Args + header: value of the ``Connection`` header. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + return parse_list(parse_connection_option, header, 0, "Connection") + + +_protocol_re = re.compile( + r"[-!#$%&\'*+.^_`|~0-9a-zA-Z]+(?:/[-!#$%&\'*+.^_`|~0-9a-zA-Z]+)?" +) + + +def parse_upgrade_protocol( + header: str, pos: int, header_name: str +) -> tuple[UpgradeProtocol, int]: + """ + Parse an Upgrade protocol from ``header`` at the given position. + + Return the protocol value and the new position. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + match = _protocol_re.match(header, pos) + if match is None: + raise InvalidHeaderFormat(header_name, "expected protocol", header, pos) + return cast(UpgradeProtocol, match.group()), match.end() + + +def parse_upgrade(header: str) -> list[UpgradeProtocol]: + """ + Parse an ``Upgrade`` header. + + Return a list of HTTP protocols. + + Args: + header: Value of the ``Upgrade`` header. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + return parse_list(parse_upgrade_protocol, header, 0, "Upgrade") + + +def parse_extension_item_param( + header: str, pos: int, header_name: str +) -> tuple[ExtensionParameter, int]: + """ + Parse a single extension parameter from ``header`` at the given position. + + Return a ``(name, value)`` pair and the new position. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + # Extract parameter name. + name, pos = parse_token(header, pos, header_name) + pos = parse_OWS(header, pos) + # Extract parameter value, if there is one. + value: str | None = None + if peek_ahead(header, pos) == "=": + pos = parse_OWS(header, pos + 1) + if peek_ahead(header, pos) == '"': + pos_before = pos # for proper error reporting below + value, pos = parse_quoted_string(header, pos, header_name) + # https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 says: + # the value after quoted-string unescaping MUST conform to + # the 'token' ABNF. + if _token_re.fullmatch(value) is None: + raise InvalidHeaderFormat( + header_name, "invalid quoted header content", header, pos_before + ) + else: + value, pos = parse_token(header, pos, header_name) + pos = parse_OWS(header, pos) + + return (name, value), pos + + +def parse_extension_item( + header: str, pos: int, header_name: str +) -> tuple[ExtensionHeader, int]: + """ + Parse an extension definition from ``header`` at the given position. + + Return an ``(extension name, parameters)`` pair, where ``parameters`` is a + list of ``(name, value)`` pairs, and the new position. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + # Extract extension name. + name, pos = parse_token(header, pos, header_name) + pos = parse_OWS(header, pos) + # Extract all parameters. + parameters = [] + while peek_ahead(header, pos) == ";": + pos = parse_OWS(header, pos + 1) + parameter, pos = parse_extension_item_param(header, pos, header_name) + parameters.append(parameter) + return (cast(ExtensionName, name), parameters), pos + + +def parse_extension(header: str) -> list[ExtensionHeader]: + """ + Parse a ``Sec-WebSocket-Extensions`` header. + + Return a list of WebSocket extensions and their parameters in this format:: + + [ + ( + 'extension name', + [ + ('parameter name', 'parameter value'), + .... + ] + ), + ... + ] + + Parameter values are :obj:`None` when no value is provided. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + return parse_list(parse_extension_item, header, 0, "Sec-WebSocket-Extensions") + + +parse_extension_list = parse_extension # alias for backwards compatibility + + +def build_extension_item( + name: ExtensionName, parameters: Sequence[ExtensionParameter] +) -> str: + """ + Build an extension definition. + + This is the reverse of :func:`parse_extension_item`. + + """ + return "; ".join( + [cast(str, name)] + + [ + # Quoted strings aren't necessary because values are always tokens. + name if value is None else f"{name}={value}" + for name, value in parameters + ] + ) + + +def build_extension(extensions: Sequence[ExtensionHeader]) -> str: + """ + Build a ``Sec-WebSocket-Extensions`` header. + + This is the reverse of :func:`parse_extension`. + + """ + return ", ".join( + build_extension_item(name, parameters) for name, parameters in extensions + ) + + +build_extension_list = build_extension # alias for backwards compatibility + + +def parse_subprotocol_item( + header: str, pos: int, header_name: str +) -> tuple[Subprotocol, int]: + """ + Parse a subprotocol from ``header`` at the given position. + + Return the subprotocol value and the new position. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + item, pos = parse_token(header, pos, header_name) + return cast(Subprotocol, item), pos + + +def parse_subprotocol(header: str) -> list[Subprotocol]: + """ + Parse a ``Sec-WebSocket-Protocol`` header. + + Return a list of WebSocket subprotocols. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + return parse_list(parse_subprotocol_item, header, 0, "Sec-WebSocket-Protocol") + + +parse_subprotocol_list = parse_subprotocol # alias for backwards compatibility + + +def build_subprotocol(subprotocols: Sequence[Subprotocol]) -> str: + """ + Build a ``Sec-WebSocket-Protocol`` header. + + This is the reverse of :func:`parse_subprotocol`. + + """ + return ", ".join(subprotocols) + + +build_subprotocol_list = build_subprotocol # alias for backwards compatibility + + +def validate_subprotocols(subprotocols: Sequence[Subprotocol]) -> None: + """ + Validate that ``subprotocols`` is suitable for :func:`build_subprotocol`. + + """ + if not isinstance(subprotocols, Sequence): + raise TypeError("subprotocols must be a list") + if isinstance(subprotocols, str): + raise TypeError("subprotocols must be a list, not a str") + for subprotocol in subprotocols: + if not _token_re.fullmatch(subprotocol): + raise ValueError(f"invalid subprotocol: {subprotocol}") + + +def build_www_authenticate_basic(realm: str) -> str: + """ + Build a ``WWW-Authenticate`` header for HTTP Basic Auth. + + Args: + realm: Identifier of the protection space. + + """ + # https://datatracker.ietf.org/doc/html/rfc7617#section-2 + realm = build_quoted_string(realm) + charset = build_quoted_string("UTF-8") + return f"Basic realm={realm}, charset={charset}" + + +_token68_re = re.compile(r"[A-Za-z0-9-._~+/]+=*") + + +def parse_token68(header: str, pos: int, header_name: str) -> tuple[str, int]: + """ + Parse a token68 from ``header`` at the given position. + + Return the token value and the new position. + + Raises: + InvalidHeaderFormat: On invalid inputs. + + """ + match = _token68_re.match(header, pos) + if match is None: + raise InvalidHeaderFormat(header_name, "expected token68", header, pos) + return match.group(), match.end() + + +def parse_end(header: str, pos: int, header_name: str) -> None: + """ + Check that parsing reached the end of header. + + """ + if pos < len(header): + raise InvalidHeaderFormat(header_name, "trailing data", header, pos) + + +def parse_authorization_basic(header: str) -> tuple[str, str]: + """ + Parse an ``Authorization`` header for HTTP Basic Auth. + + Return a ``(username, password)`` tuple. + + Args: + header: Value of the ``Authorization`` header. + + Raises: + InvalidHeaderFormat: On invalid inputs. + InvalidHeaderValue: On unsupported inputs. + + """ + # https://datatracker.ietf.org/doc/html/rfc7235#section-2.1 + # https://datatracker.ietf.org/doc/html/rfc7617#section-2 + scheme, pos = parse_token(header, 0, "Authorization") + if scheme.lower() != "basic": + raise InvalidHeaderValue( + "Authorization", + f"unsupported scheme: {scheme}", + ) + if peek_ahead(header, pos) != " ": + raise InvalidHeaderFormat( + "Authorization", "expected space after scheme", header, pos + ) + pos += 1 + basic_credentials, pos = parse_token68(header, pos, "Authorization") + parse_end(header, pos, "Authorization") + + try: + user_pass = base64.b64decode(basic_credentials.encode()).decode() + except binascii.Error: + raise InvalidHeaderValue( + "Authorization", + "expected base64-encoded credentials", + ) from None + try: + username, password = user_pass.split(":", 1) + except ValueError: + raise InvalidHeaderValue( + "Authorization", + "expected username:password credentials", + ) from None + + return username, password + + +def build_authorization_basic(username: str, password: str) -> str: + """ + Build an ``Authorization`` header for HTTP Basic Auth. + + This is the reverse of :func:`parse_authorization_basic`. + + """ + # https://datatracker.ietf.org/doc/html/rfc7617#section-2 + assert ":" not in username + user_pass = f"{username}:{password}" + basic_credentials = base64.b64encode(user_pass.encode()).decode() + return "Basic " + basic_credentials diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/http.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/http.py new file mode 100644 index 0000000000000000000000000000000000000000..24a0ee310cd5c8a88bec90b2a0aab39dd6e6c61e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/http.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import warnings + +from .datastructures import Headers, MultipleValuesError # noqa: F401 + + +with warnings.catch_warnings(): + # Suppress redundant DeprecationWarning raised by websockets.legacy. + warnings.filterwarnings("ignore", category=DeprecationWarning) + from .legacy.http import read_request, read_response # noqa: F401 + + +warnings.warn( # deprecated in 9.0 - 2021-09-01 + "Headers and MultipleValuesError were moved " + "from websockets.http to websockets.datastructures" + "and read_request and read_response were moved " + "from websockets.http to websockets.legacy.http", + DeprecationWarning, +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/http11.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/http11.py new file mode 100644 index 0000000000000000000000000000000000000000..f548611b41d74b99a62190fad18269330b906c3d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/http11.py @@ -0,0 +1,438 @@ +from __future__ import annotations + +import dataclasses +import os +import re +import sys +import warnings +from collections.abc import Generator +from typing import Callable + +from .datastructures import Headers +from .exceptions import SecurityError +from .version import version as websockets_version + + +__all__ = [ + "SERVER", + "USER_AGENT", + "Request", + "Response", +] + + +PYTHON_VERSION = "{}.{}".format(*sys.version_info) + +# User-Agent header for HTTP requests. +USER_AGENT = os.environ.get( + "WEBSOCKETS_USER_AGENT", + f"Python/{PYTHON_VERSION} websockets/{websockets_version}", +) + +# Server header for HTTP responses. +SERVER = os.environ.get( + "WEBSOCKETS_SERVER", + f"Python/{PYTHON_VERSION} websockets/{websockets_version}", +) + +# Maximum total size of headers is around 128 * 8 KiB = 1 MiB. +MAX_NUM_HEADERS = int(os.environ.get("WEBSOCKETS_MAX_NUM_HEADERS", "128")) + +# Limit request line and header lines. 8KiB is the most common default +# configuration of popular HTTP servers. +MAX_LINE_LENGTH = int(os.environ.get("WEBSOCKETS_MAX_LINE_LENGTH", "8192")) + +# Support for HTTP response bodies is intended to read an error message +# returned by a server. It isn't designed to perform large file transfers. +MAX_BODY_SIZE = int(os.environ.get("WEBSOCKETS_MAX_BODY_SIZE", "1_048_576")) # 1 MiB + + +def d(value: bytes | bytearray) -> str: + """ + Decode a bytestring for interpolating into an error message. + + """ + return value.decode(errors="backslashreplace") + + +# See https://datatracker.ietf.org/doc/html/rfc7230#appendix-B. + +# Regex for validating header names. + +_token_re = re.compile(rb"[-!#$%&\'*+.^_`|~0-9a-zA-Z]+") + +# Regex for validating header values. + +# We don't attempt to support obsolete line folding. + +# Include HTAB (\x09), SP (\x20), VCHAR (\x21-\x7e), obs-text (\x80-\xff). + +# The ABNF is complicated because it attempts to express that optional +# whitespace is ignored. We strip whitespace and don't revalidate that. + +# See also https://www.rfc-editor.org/errata_search.php?rfc=7230&eid=4189 + +_value_re = re.compile(rb"[\x09\x20-\x7e\x80-\xff]*") + + +@dataclasses.dataclass +class Request: + """ + WebSocket handshake request. + + Attributes: + path: Request path, including optional query. + headers: Request headers. + """ + + path: str + headers: Headers + # body isn't useful is the context of this library. + + _exception: Exception | None = None + + @property + def exception(self) -> Exception | None: # pragma: no cover + warnings.warn( # deprecated in 10.3 - 2022-04-17 + "Request.exception is deprecated; use ServerProtocol.handshake_exc instead", + DeprecationWarning, + ) + return self._exception + + @classmethod + def parse( + cls, + read_line: Callable[[int], Generator[None, None, bytes | bytearray]], + ) -> Generator[None, None, Request]: + """ + Parse a WebSocket handshake request. + + This is a generator-based coroutine. + + The request path isn't URL-decoded or validated in any way. + + The request path and headers are expected to contain only ASCII + characters. Other characters are represented with surrogate escapes. + + :meth:`parse` doesn't attempt to read the request body because + WebSocket handshake requests don't have one. If the request contains a + body, it may be read from the data stream after :meth:`parse` returns. + + Args: + read_line: Generator-based coroutine that reads a LF-terminated + line or raises an exception if there isn't enough data + + Raises: + EOFError: If the connection is closed without a full HTTP request. + SecurityError: If the request exceeds a security limit. + ValueError: If the request isn't well formatted. + + """ + # https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.1 + + # Parsing is simple because fixed values are expected for method and + # version and because path isn't checked. Since WebSocket software tends + # to implement HTTP/1.1 strictly, there's little need for lenient parsing. + + try: + request_line = yield from parse_line(read_line) + except EOFError as exc: + raise EOFError("connection closed while reading HTTP request line") from exc + + try: + method, raw_path, protocol = request_line.split(b" ", 2) + except ValueError: # not enough values to unpack (expected 3, got 1-2) + raise ValueError(f"invalid HTTP request line: {d(request_line)}") from None + if protocol != b"HTTP/1.1": + raise ValueError( + f"unsupported protocol; expected HTTP/1.1: {d(request_line)}" + ) + if method != b"GET": + raise ValueError(f"unsupported HTTP method; expected GET; got {d(method)}") + path = raw_path.decode("ascii", "surrogateescape") + + headers = yield from parse_headers(read_line) + + # https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.3 + + if "Transfer-Encoding" in headers: + raise NotImplementedError("transfer codings aren't supported") + + if "Content-Length" in headers: + # Some devices send a Content-Length header with a value of 0. + # This raises ValueError if Content-Length isn't an integer too. + if int(headers["Content-Length"]) != 0: + raise ValueError("unsupported request body") + + return cls(path, headers) + + def serialize(self) -> bytes: + """ + Serialize a WebSocket handshake request. + + """ + # Since the request line and headers only contain ASCII characters, + # we can keep this simple. + request = f"GET {self.path} HTTP/1.1\r\n".encode() + request += self.headers.serialize() + return request + + +@dataclasses.dataclass +class Response: + """ + WebSocket handshake response. + + Attributes: + status_code: Response code. + reason_phrase: Response reason. + headers: Response headers. + body: Response body. + + """ + + status_code: int + reason_phrase: str + headers: Headers + body: bytes | bytearray = b"" + + _exception: Exception | None = None + + @property + def exception(self) -> Exception | None: # pragma: no cover + warnings.warn( # deprecated in 10.3 - 2022-04-17 + "Response.exception is deprecated; " + "use ClientProtocol.handshake_exc instead", + DeprecationWarning, + ) + return self._exception + + @classmethod + def parse( + cls, + read_line: Callable[[int], Generator[None, None, bytes | bytearray]], + read_exact: Callable[[int], Generator[None, None, bytes | bytearray]], + read_to_eof: Callable[[int], Generator[None, None, bytes | bytearray]], + proxy: bool = False, + ) -> Generator[None, None, Response]: + """ + Parse a WebSocket handshake response. + + This is a generator-based coroutine. + + The reason phrase and headers are expected to contain only ASCII + characters. Other characters are represented with surrogate escapes. + + Args: + read_line: Generator-based coroutine that reads a LF-terminated + line or raises an exception if there isn't enough data. + read_exact: Generator-based coroutine that reads the requested + bytes or raises an exception if there isn't enough data. + read_to_eof: Generator-based coroutine that reads until the end + of the stream. + + Raises: + EOFError: If the connection is closed without a full HTTP response. + SecurityError: If the response exceeds a security limit. + LookupError: If the response isn't well formatted. + ValueError: If the response isn't well formatted. + + """ + # https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2 + + try: + status_line = yield from parse_line(read_line) + except EOFError as exc: + raise EOFError("connection closed while reading HTTP status line") from exc + + try: + protocol, raw_status_code, raw_reason = status_line.split(b" ", 2) + except ValueError: # not enough values to unpack (expected 3, got 1-2) + raise ValueError(f"invalid HTTP status line: {d(status_line)}") from None + if proxy: # some proxies still use HTTP/1.0 + if protocol not in [b"HTTP/1.1", b"HTTP/1.0"]: + raise ValueError( + f"unsupported protocol; expected HTTP/1.1 or HTTP/1.0: " + f"{d(status_line)}" + ) + else: + if protocol != b"HTTP/1.1": + raise ValueError( + f"unsupported protocol; expected HTTP/1.1: {d(status_line)}" + ) + try: + status_code = int(raw_status_code) + except ValueError: # invalid literal for int() with base 10 + raise ValueError( + f"invalid status code; expected integer; got {d(raw_status_code)}" + ) from None + if not 100 <= status_code < 600: + raise ValueError( + f"invalid status code; expected 100–599; got {d(raw_status_code)}" + ) + if not _value_re.fullmatch(raw_reason): + raise ValueError(f"invalid HTTP reason phrase: {d(raw_reason)}") + reason = raw_reason.decode("ascii", "surrogateescape") + + headers = yield from parse_headers(read_line) + + body: bytes | bytearray + if proxy: + body = b"" + else: + body = yield from read_body( + status_code, headers, read_line, read_exact, read_to_eof + ) + + return cls(status_code, reason, headers, body) + + def serialize(self) -> bytes: + """ + Serialize a WebSocket handshake response. + + """ + # Since the status line and headers only contain ASCII characters, + # we can keep this simple. + response = f"HTTP/1.1 {self.status_code} {self.reason_phrase}\r\n".encode() + response += self.headers.serialize() + response += self.body + return response + + +def parse_line( + read_line: Callable[[int], Generator[None, None, bytes | bytearray]], +) -> Generator[None, None, bytes | bytearray]: + """ + Parse a single line. + + CRLF is stripped from the return value. + + Args: + read_line: Generator-based coroutine that reads a LF-terminated line + or raises an exception if there isn't enough data. + + Raises: + EOFError: If the connection is closed without a CRLF. + SecurityError: If the response exceeds a security limit. + + """ + try: + line = yield from read_line(MAX_LINE_LENGTH) + except RuntimeError: + raise SecurityError("line too long") + # Not mandatory but safe - https://datatracker.ietf.org/doc/html/rfc7230#section-3.5 + if not line.endswith(b"\r\n"): + raise EOFError("line without CRLF") + return line[:-2] + + +def parse_headers( + read_line: Callable[[int], Generator[None, None, bytes | bytearray]], +) -> Generator[None, None, Headers]: + """ + Parse HTTP headers. + + Non-ASCII characters are represented with surrogate escapes. + + Args: + read_line: Generator-based coroutine that reads a LF-terminated line + or raises an exception if there isn't enough data. + + Raises: + EOFError: If the connection is closed without complete headers. + SecurityError: If the request exceeds a security limit. + ValueError: If the request isn't well formatted. + + """ + # https://datatracker.ietf.org/doc/html/rfc7230#section-3.2 + + # We don't attempt to support obsolete line folding. + + headers = Headers() + for _ in range(MAX_NUM_HEADERS + 1): + try: + line = yield from parse_line(read_line) + except EOFError as exc: + raise EOFError("connection closed while reading HTTP headers") from exc + if line == b"": + break + + try: + raw_name, raw_value = line.split(b":", 1) + except ValueError: # not enough values to unpack (expected 2, got 1) + raise ValueError(f"invalid HTTP header line: {d(line)}") from None + if not _token_re.fullmatch(raw_name): + raise ValueError(f"invalid HTTP header name: {d(raw_name)}") + raw_value = raw_value.strip(b" \t") + if not _value_re.fullmatch(raw_value): + raise ValueError(f"invalid HTTP header value: {d(raw_value)}") + + name = raw_name.decode("ascii") # guaranteed to be ASCII at this point + value = raw_value.decode("ascii", "surrogateescape") + headers[name] = value + + else: + raise SecurityError("too many HTTP headers") + + return headers + + +def read_body( + status_code: int, + headers: Headers, + read_line: Callable[[int], Generator[None, None, bytes | bytearray]], + read_exact: Callable[[int], Generator[None, None, bytes | bytearray]], + read_to_eof: Callable[[int], Generator[None, None, bytes | bytearray]], +) -> Generator[None, None, bytes | bytearray]: + # https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.3 + + # Since websockets only does GET requests (no HEAD, no CONNECT), all + # responses except 1xx, 204, and 304 include a message body. + if 100 <= status_code < 200 or status_code == 204 or status_code == 304: + return b"" + + # MultipleValuesError is sufficiently unlikely that we don't attempt to + # handle it when accessing headers. Instead we document that its parent + # class, LookupError, may be raised. + # Conversions from str to int are protected by sys.set_int_max_str_digits.. + + elif (coding := headers.get("Transfer-Encoding")) is not None: + if coding != "chunked": + raise NotImplementedError(f"transfer coding {coding} isn't supported") + + body = b"" + while True: + chunk_size_line = yield from parse_line(read_line) + raw_chunk_size = chunk_size_line.split(b";", 1)[0] + # Set a lower limit than default_max_str_digits; 1 EB is plenty. + if len(raw_chunk_size) > 15: + str_chunk_size = raw_chunk_size.decode(errors="backslashreplace") + raise SecurityError(f"chunk too large: 0x{str_chunk_size} bytes") + chunk_size = int(raw_chunk_size, 16) + if chunk_size == 0: + break + if len(body) + chunk_size > MAX_BODY_SIZE: + raise SecurityError( + f"chunk too large: {chunk_size} bytes after {len(body)} bytes" + ) + body += yield from read_exact(chunk_size) + if (yield from read_exact(2)) != b"\r\n": + raise ValueError("chunk without CRLF") + # Read the trailer. + yield from parse_headers(read_line) + return body + + elif (raw_content_length := headers.get("Content-Length")) is not None: + # Set a lower limit than default_max_str_digits; 1 EiB is plenty. + if len(raw_content_length) > 18: + raise SecurityError(f"body too large: {raw_content_length} bytes") + content_length = int(raw_content_length) + if content_length > MAX_BODY_SIZE: + raise SecurityError(f"body too large: {content_length} bytes") + return (yield from read_exact(content_length)) + + else: + try: + return (yield from read_to_eof(MAX_BODY_SIZE)) + except RuntimeError: + raise SecurityError(f"body too large: over {MAX_BODY_SIZE} bytes") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/imports.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/imports.py new file mode 100644 index 0000000000000000000000000000000000000000..b86166408438ee23208a62241c2da6fee7a45ec5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/imports.py @@ -0,0 +1,100 @@ +from __future__ import annotations + +import warnings +from collections.abc import Iterable +from typing import Any + + +__all__ = ["lazy_import"] + + +def import_name(name: str, source: str, namespace: dict[str, Any]) -> Any: + """ + Import ``name`` from ``source`` in ``namespace``. + + There are two use cases: + + - ``name`` is an object defined in ``source``; + - ``name`` is a submodule of ``source``. + + Neither :func:`__import__` nor :func:`~importlib.import_module` does + exactly this. :func:`__import__` is closer to the intended behavior. + + """ + level = 0 + while source[level] == ".": + level += 1 + assert level < len(source), "importing from parent isn't supported" + module = __import__(source[level:], namespace, None, [name], level) + return getattr(module, name) + + +def lazy_import( + namespace: dict[str, Any], + aliases: dict[str, str] | None = None, + deprecated_aliases: dict[str, str] | None = None, +) -> None: + """ + Provide lazy, module-level imports. + + Typical use:: + + __getattr__, __dir__ = lazy_import( + globals(), + aliases={ + "": "", + ... + }, + deprecated_aliases={ + ..., + } + ) + + This function defines ``__getattr__`` and ``__dir__`` per :pep:`562`. + + """ + if aliases is None: + aliases = {} + if deprecated_aliases is None: + deprecated_aliases = {} + + namespace_set = set(namespace) + aliases_set = set(aliases) + deprecated_aliases_set = set(deprecated_aliases) + + assert not namespace_set & aliases_set, "namespace conflict" + assert not namespace_set & deprecated_aliases_set, "namespace conflict" + assert not aliases_set & deprecated_aliases_set, "namespace conflict" + + package = namespace["__name__"] + + def __getattr__(name: str) -> Any: + assert aliases is not None # mypy cannot figure this out + try: + source = aliases[name] + except KeyError: + pass + else: + return import_name(name, source, namespace) + + assert deprecated_aliases is not None # mypy cannot figure this out + try: + source = deprecated_aliases[name] + except KeyError: + pass + else: + warnings.warn( + f"{package}.{name} is deprecated", + DeprecationWarning, + stacklevel=2, + ) + return import_name(name, source, namespace) + + raise AttributeError(f"module {package!r} has no attribute {name!r}") + + namespace["__getattr__"] = __getattr__ + + def __dir__() -> Iterable[str]: + return sorted(namespace_set | aliases_set | deprecated_aliases_set) + + namespace["__dir__"] = __dir__ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..070ec2d04a0e48f86364c8ebf99bfd9f2124836b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__init__.py @@ -0,0 +1,11 @@ +from __future__ import annotations + +import warnings + + +warnings.warn( # deprecated in 14.0 - 2024-11-09 + "websockets.legacy is deprecated; " + "see https://websockets.readthedocs.io/en/stable/howto/upgrade.html " + "for upgrade instructions", + DeprecationWarning, +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..116c94671fe3bf41d81453226128521656b659de Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/auth.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/auth.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4d2937394763dbc68fab84168e578e2876848d3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/auth.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/client.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/client.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21b6cff6009da4dace6a7c6ed7969d00d9776ec7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/client.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/exceptions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/exceptions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a96c4ab2b36ae1dc08abaeef120c87c3bf4fab34 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/exceptions.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/framing.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/framing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e3f20e9505a4892405038059dc0bd9fb6c65055 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/framing.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/handshake.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/handshake.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78fbd11d54a686165232ccd6f0d3bce20e500f23 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/handshake.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/http.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/http.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78fc64eadc834ef7fde0fcfe4e8362f2ae7e3d8e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/http.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/protocol.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/protocol.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee522d37214394076c3d6f17fc74db5f50c4df6c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/protocol.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/server.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11fa0b2c14c1021dee620861440e8721ed150475 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/__pycache__/server.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/auth.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..853f379bb3af6bb637c311bb23401d3a10331ea1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/auth.py @@ -0,0 +1,190 @@ +from __future__ import annotations + +import functools +import hmac +import http +from collections.abc import Awaitable, Iterable +from typing import Any, Callable, cast + +from ..datastructures import Headers +from ..exceptions import InvalidHeader +from ..headers import build_www_authenticate_basic, parse_authorization_basic +from .server import HTTPResponse, WebSocketServerProtocol + + +__all__ = ["BasicAuthWebSocketServerProtocol", "basic_auth_protocol_factory"] + +Credentials = tuple[str, str] + + +def is_credentials(value: Any) -> bool: + try: + username, password = value + except (TypeError, ValueError): + return False + else: + return isinstance(username, str) and isinstance(password, str) + + +class BasicAuthWebSocketServerProtocol(WebSocketServerProtocol): + """ + WebSocket server protocol that enforces HTTP Basic Auth. + + """ + + realm: str = "" + """ + Scope of protection. + + If provided, it should contain only ASCII characters because the + encoding of non-ASCII characters is undefined. + """ + + username: str | None = None + """Username of the authenticated user.""" + + def __init__( + self, + *args: Any, + realm: str | None = None, + check_credentials: Callable[[str, str], Awaitable[bool]] | None = None, + **kwargs: Any, + ) -> None: + if realm is not None: + self.realm = realm # shadow class attribute + self._check_credentials = check_credentials + super().__init__(*args, **kwargs) + + async def check_credentials(self, username: str, password: str) -> bool: + """ + Check whether credentials are authorized. + + This coroutine may be overridden in a subclass, for example to + authenticate against a database or an external service. + + Args: + username: HTTP Basic Auth username. + password: HTTP Basic Auth password. + + Returns: + :obj:`True` if the handshake should continue; + :obj:`False` if it should fail with an HTTP 401 error. + + """ + if self._check_credentials is not None: + return await self._check_credentials(username, password) + + return False + + async def process_request( + self, + path: str, + request_headers: Headers, + ) -> HTTPResponse | None: + """ + Check HTTP Basic Auth and return an HTTP 401 response if needed. + + """ + try: + authorization = request_headers["Authorization"] + except KeyError: + return ( + http.HTTPStatus.UNAUTHORIZED, + [("WWW-Authenticate", build_www_authenticate_basic(self.realm))], + b"Missing credentials\n", + ) + + try: + username, password = parse_authorization_basic(authorization) + except InvalidHeader: + return ( + http.HTTPStatus.UNAUTHORIZED, + [("WWW-Authenticate", build_www_authenticate_basic(self.realm))], + b"Unsupported credentials\n", + ) + + if not await self.check_credentials(username, password): + return ( + http.HTTPStatus.UNAUTHORIZED, + [("WWW-Authenticate", build_www_authenticate_basic(self.realm))], + b"Invalid credentials\n", + ) + + self.username = username + + return await super().process_request(path, request_headers) + + +def basic_auth_protocol_factory( + realm: str | None = None, + credentials: Credentials | Iterable[Credentials] | None = None, + check_credentials: Callable[[str, str], Awaitable[bool]] | None = None, + create_protocol: Callable[..., BasicAuthWebSocketServerProtocol] | None = None, +) -> Callable[..., BasicAuthWebSocketServerProtocol]: + """ + Protocol factory that enforces HTTP Basic Auth. + + :func:`basic_auth_protocol_factory` is designed to integrate with + :func:`~websockets.legacy.server.serve` like this:: + + serve( + ..., + create_protocol=basic_auth_protocol_factory( + realm="my dev server", + credentials=("hello", "iloveyou"), + ) + ) + + Args: + realm: Scope of protection. It should contain only ASCII characters + because the encoding of non-ASCII characters is undefined. + Refer to section 2.2 of :rfc:`7235` for details. + credentials: Hard coded authorized credentials. It can be a + ``(username, password)`` pair or a list of such pairs. + check_credentials: Coroutine that verifies credentials. + It receives ``username`` and ``password`` arguments + and returns a :class:`bool`. One of ``credentials`` or + ``check_credentials`` must be provided but not both. + create_protocol: Factory that creates the protocol. By default, this + is :class:`BasicAuthWebSocketServerProtocol`. It can be replaced + by a subclass. + Raises: + TypeError: If the ``credentials`` or ``check_credentials`` argument is + wrong. + + """ + if (credentials is None) == (check_credentials is None): + raise TypeError("provide either credentials or check_credentials") + + if credentials is not None: + if is_credentials(credentials): + credentials_list = [cast(Credentials, credentials)] + elif isinstance(credentials, Iterable): + credentials_list = list(cast(Iterable[Credentials], credentials)) + if not all(is_credentials(item) for item in credentials_list): + raise TypeError(f"invalid credentials argument: {credentials}") + else: + raise TypeError(f"invalid credentials argument: {credentials}") + + credentials_dict = dict(credentials_list) + + async def check_credentials(username: str, password: str) -> bool: + try: + expected_password = credentials_dict[username] + except KeyError: + return False + return hmac.compare_digest(expected_password, password) + + if create_protocol is None: + create_protocol = BasicAuthWebSocketServerProtocol + + # Help mypy and avoid this error: "type[BasicAuthWebSocketServerProtocol] | + # Callable[..., BasicAuthWebSocketServerProtocol]" not callable [misc] + create_protocol = cast( + Callable[..., BasicAuthWebSocketServerProtocol], create_protocol + ) + return functools.partial( + create_protocol, + realm=realm, + check_credentials=check_credentials, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/client.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/client.py new file mode 100644 index 0000000000000000000000000000000000000000..41ce2a35be4b4eb44b47878daf952dab54388cbc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/client.py @@ -0,0 +1,703 @@ +from __future__ import annotations + +import asyncio +import functools +import logging +import os +import random +import traceback +import urllib.parse +import warnings +from collections.abc import AsyncIterator, Generator, Sequence +from types import TracebackType +from typing import Any, Callable, cast + +from ..asyncio.compatibility import asyncio_timeout +from ..datastructures import Headers, HeadersLike +from ..exceptions import ( + InvalidHeader, + InvalidHeaderValue, + InvalidMessage, + NegotiationError, + SecurityError, +) +from ..extensions import ClientExtensionFactory, Extension +from ..extensions.permessage_deflate import enable_client_permessage_deflate +from ..headers import ( + build_authorization_basic, + build_extension, + build_host, + build_subprotocol, + parse_extension, + parse_subprotocol, + validate_subprotocols, +) +from ..http11 import USER_AGENT +from ..typing import ExtensionHeader, LoggerLike, Origin, Subprotocol +from ..uri import WebSocketURI, parse_uri +from .exceptions import InvalidStatusCode, RedirectHandshake +from .handshake import build_request, check_response +from .http import read_response +from .protocol import WebSocketCommonProtocol + + +__all__ = ["connect", "unix_connect", "WebSocketClientProtocol"] + + +class WebSocketClientProtocol(WebSocketCommonProtocol): + """ + WebSocket client connection. + + :class:`WebSocketClientProtocol` provides :meth:`recv` and :meth:`send` + coroutines for receiving and sending messages. + + It supports asynchronous iteration to receive messages:: + + async for message in websocket: + await process(message) + + The iterator exits normally when the connection is closed with close code + 1000 (OK) or 1001 (going away) or without a close code. It raises + a :exc:`~websockets.exceptions.ConnectionClosedError` when the connection + is closed with any other code. + + See :func:`connect` for the documentation of ``logger``, ``origin``, + ``extensions``, ``subprotocols``, ``extra_headers``, and + ``user_agent_header``. + + See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the + documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``, + ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``. + + """ + + is_client = True + side = "client" + + def __init__( + self, + *, + logger: LoggerLike | None = None, + origin: Origin | None = None, + extensions: Sequence[ClientExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + extra_headers: HeadersLike | None = None, + user_agent_header: str | None = USER_AGENT, + **kwargs: Any, + ) -> None: + if logger is None: + logger = logging.getLogger("websockets.client") + super().__init__(logger=logger, **kwargs) + self.origin = origin + self.available_extensions = extensions + self.available_subprotocols = subprotocols + self.extra_headers = extra_headers + self.user_agent_header = user_agent_header + + def write_http_request(self, path: str, headers: Headers) -> None: + """ + Write request line and headers to the HTTP request. + + """ + self.path = path + self.request_headers = headers + + if self.debug: + self.logger.debug("> GET %s HTTP/1.1", path) + for key, value in headers.raw_items(): + self.logger.debug("> %s: %s", key, value) + + # Since the path and headers only contain ASCII characters, + # we can keep this simple. + request = f"GET {path} HTTP/1.1\r\n" + request += str(headers) + + self.transport.write(request.encode()) + + async def read_http_response(self) -> tuple[int, Headers]: + """ + Read status line and headers from the HTTP response. + + If the response contains a body, it may be read from ``self.reader`` + after this coroutine returns. + + Raises: + InvalidMessage: If the HTTP message is malformed or isn't an + HTTP/1.1 GET response. + + """ + try: + status_code, reason, headers = await read_response(self.reader) + except Exception as exc: + raise InvalidMessage("did not receive a valid HTTP response") from exc + + if self.debug: + self.logger.debug("< HTTP/1.1 %d %s", status_code, reason) + for key, value in headers.raw_items(): + self.logger.debug("< %s: %s", key, value) + + self.response_headers = headers + + return status_code, self.response_headers + + @staticmethod + def process_extensions( + headers: Headers, + available_extensions: Sequence[ClientExtensionFactory] | None, + ) -> list[Extension]: + """ + Handle the Sec-WebSocket-Extensions HTTP response header. + + Check that each extension is supported, as well as its parameters. + + Return the list of accepted extensions. + + Raise :exc:`~websockets.exceptions.InvalidHandshake` to abort the + connection. + + :rfc:`6455` leaves the rules up to the specification of each + :extension. + + To provide this level of flexibility, for each extension accepted by + the server, we check for a match with each extension available in the + client configuration. If no match is found, an exception is raised. + + If several variants of the same extension are accepted by the server, + it may be configured several times, which won't make sense in general. + Extensions must implement their own requirements. For this purpose, + the list of previously accepted extensions is provided. + + Other requirements, for example related to mandatory extensions or the + order of extensions, may be implemented by overriding this method. + + """ + accepted_extensions: list[Extension] = [] + + header_values = headers.get_all("Sec-WebSocket-Extensions") + + if header_values: + if available_extensions is None: + raise NegotiationError("no extensions supported") + + parsed_header_values: list[ExtensionHeader] = sum( + [parse_extension(header_value) for header_value in header_values], [] + ) + + for name, response_params in parsed_header_values: + for extension_factory in available_extensions: + # Skip non-matching extensions based on their name. + if extension_factory.name != name: + continue + + # Skip non-matching extensions based on their params. + try: + extension = extension_factory.process_response_params( + response_params, accepted_extensions + ) + except NegotiationError: + continue + + # Add matching extension to the final list. + accepted_extensions.append(extension) + + # Break out of the loop once we have a match. + break + + # If we didn't break from the loop, no extension in our list + # matched what the server sent. Fail the connection. + else: + raise NegotiationError( + f"Unsupported extension: " + f"name = {name}, params = {response_params}" + ) + + return accepted_extensions + + @staticmethod + def process_subprotocol( + headers: Headers, available_subprotocols: Sequence[Subprotocol] | None + ) -> Subprotocol | None: + """ + Handle the Sec-WebSocket-Protocol HTTP response header. + + Check that it contains exactly one supported subprotocol. + + Return the selected subprotocol. + + """ + subprotocol: Subprotocol | None = None + + header_values = headers.get_all("Sec-WebSocket-Protocol") + + if header_values: + if available_subprotocols is None: + raise NegotiationError("no subprotocols supported") + + parsed_header_values: Sequence[Subprotocol] = sum( + [parse_subprotocol(header_value) for header_value in header_values], [] + ) + + if len(parsed_header_values) > 1: + raise InvalidHeaderValue( + "Sec-WebSocket-Protocol", + f"multiple values: {', '.join(parsed_header_values)}", + ) + + subprotocol = parsed_header_values[0] + + if subprotocol not in available_subprotocols: + raise NegotiationError(f"unsupported subprotocol: {subprotocol}") + + return subprotocol + + async def handshake( + self, + wsuri: WebSocketURI, + origin: Origin | None = None, + available_extensions: Sequence[ClientExtensionFactory] | None = None, + available_subprotocols: Sequence[Subprotocol] | None = None, + extra_headers: HeadersLike | None = None, + ) -> None: + """ + Perform the client side of the opening handshake. + + Args: + wsuri: URI of the WebSocket server. + origin: Value of the ``Origin`` header. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + extra_headers: Arbitrary HTTP headers to add to the handshake request. + + Raises: + InvalidHandshake: If the handshake fails. + + """ + request_headers = Headers() + + request_headers["Host"] = build_host(wsuri.host, wsuri.port, wsuri.secure) + + if wsuri.user_info: + request_headers["Authorization"] = build_authorization_basic( + *wsuri.user_info + ) + + if origin is not None: + request_headers["Origin"] = origin + + key = build_request(request_headers) + + if available_extensions is not None: + extensions_header = build_extension( + [ + (extension_factory.name, extension_factory.get_request_params()) + for extension_factory in available_extensions + ] + ) + request_headers["Sec-WebSocket-Extensions"] = extensions_header + + if available_subprotocols is not None: + protocol_header = build_subprotocol(available_subprotocols) + request_headers["Sec-WebSocket-Protocol"] = protocol_header + + if self.extra_headers is not None: + request_headers.update(self.extra_headers) + + if self.user_agent_header: + request_headers.setdefault("User-Agent", self.user_agent_header) + + self.write_http_request(wsuri.resource_name, request_headers) + + status_code, response_headers = await self.read_http_response() + if status_code in (301, 302, 303, 307, 308): + if "Location" not in response_headers: + raise InvalidHeader("Location") + raise RedirectHandshake(response_headers["Location"]) + elif status_code != 101: + raise InvalidStatusCode(status_code, response_headers) + + check_response(response_headers, key) + + self.extensions = self.process_extensions( + response_headers, available_extensions + ) + + self.subprotocol = self.process_subprotocol( + response_headers, available_subprotocols + ) + + self.connection_open() + + +class Connect: + """ + Connect to the WebSocket server at ``uri``. + + Awaiting :func:`connect` yields a :class:`WebSocketClientProtocol` which + can then be used to send and receive messages. + + :func:`connect` can be used as a asynchronous context manager:: + + async with connect(...) as websocket: + ... + + The connection is closed automatically when exiting the context. + + :func:`connect` can be used as an infinite asynchronous iterator to + reconnect automatically on errors:: + + async for websocket in connect(...): + try: + ... + except websockets.exceptions.ConnectionClosed: + continue + + The connection is closed automatically after each iteration of the loop. + + If an error occurs while establishing the connection, :func:`connect` + retries with exponential backoff. The backoff delay starts at three + seconds and increases up to one minute. + + If an error occurs in the body of the loop, you can handle the exception + and :func:`connect` will reconnect with the next iteration; or you can + let the exception bubble up and break out of the loop. This lets you + decide which errors trigger a reconnection and which errors are fatal. + + Args: + uri: URI of the WebSocket server. + create_protocol: Factory for the :class:`asyncio.Protocol` managing + the connection. It defaults to :class:`WebSocketClientProtocol`. + Set it to a wrapper or a subclass to customize connection handling. + logger: Logger for this client. + It defaults to ``logging.getLogger("websockets.client")``. + See the :doc:`logging guide <../../topics/logging>` for details. + compression: The "permessage-deflate" extension is enabled by default. + Set ``compression`` to :obj:`None` to disable it. See the + :doc:`compression guide <../../topics/compression>` for details. + origin: Value of the ``Origin`` header, for servers that require it. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + extra_headers: Arbitrary HTTP headers to add to the handshake request. + user_agent_header: Value of the ``User-Agent`` request header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. + Setting it to :obj:`None` removes the header. + open_timeout: Timeout for opening the connection in seconds. + :obj:`None` disables the timeout. + + See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the + documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``, + ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``. + + Any other keyword arguments are passed the event loop's + :meth:`~asyncio.loop.create_connection` method. + + For example: + + * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enforce TLS + settings. When connecting to a ``wss://`` URI, if ``ssl`` isn't + provided, a TLS context is created + with :func:`~ssl.create_default_context`. + + * You can set ``host`` and ``port`` to connect to a different host and + port from those found in ``uri``. This only changes the destination of + the TCP connection. The host name from ``uri`` is still used in the TLS + handshake for secure connections and in the ``Host`` header. + + Raises: + InvalidURI: If ``uri`` isn't a valid WebSocket URI. + OSError: If the TCP connection fails. + InvalidHandshake: If the opening handshake fails. + ~asyncio.TimeoutError: If the opening handshake times out. + + """ + + MAX_REDIRECTS_ALLOWED = int(os.environ.get("WEBSOCKETS_MAX_REDIRECTS", "10")) + + def __init__( + self, + uri: str, + *, + create_protocol: Callable[..., WebSocketClientProtocol] | None = None, + logger: LoggerLike | None = None, + compression: str | None = "deflate", + origin: Origin | None = None, + extensions: Sequence[ClientExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + extra_headers: HeadersLike | None = None, + user_agent_header: str | None = USER_AGENT, + open_timeout: float | None = 10, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = None, + max_size: int | None = 2**20, + max_queue: int | None = 2**5, + read_limit: int = 2**16, + write_limit: int = 2**16, + **kwargs: Any, + ) -> None: + # Backwards compatibility: close_timeout used to be called timeout. + timeout: float | None = kwargs.pop("timeout", None) + if timeout is None: + timeout = 10 + else: + warnings.warn("rename timeout to close_timeout", DeprecationWarning) + # If both are specified, timeout is ignored. + if close_timeout is None: + close_timeout = timeout + + # Backwards compatibility: create_protocol used to be called klass. + klass: type[WebSocketClientProtocol] | None = kwargs.pop("klass", None) + if klass is None: + klass = WebSocketClientProtocol + else: + warnings.warn("rename klass to create_protocol", DeprecationWarning) + # If both are specified, klass is ignored. + if create_protocol is None: + create_protocol = klass + + # Backwards compatibility: recv() used to return None on closed connections + legacy_recv: bool = kwargs.pop("legacy_recv", False) + + # Backwards compatibility: the loop parameter used to be supported. + _loop: asyncio.AbstractEventLoop | None = kwargs.pop("loop", None) + if _loop is None: + loop = asyncio.get_event_loop() + else: + loop = _loop + warnings.warn("remove loop argument", DeprecationWarning) + + wsuri = parse_uri(uri) + if wsuri.secure: + kwargs.setdefault("ssl", True) + elif kwargs.get("ssl") is not None: + raise ValueError( + "connect() received a ssl argument for a ws:// URI, " + "use a wss:// URI to enable TLS" + ) + + if compression == "deflate": + extensions = enable_client_permessage_deflate(extensions) + elif compression is not None: + raise ValueError(f"unsupported compression: {compression}") + + if subprotocols is not None: + validate_subprotocols(subprotocols) + + # Help mypy and avoid this error: "type[WebSocketClientProtocol] | + # Callable[..., WebSocketClientProtocol]" not callable [misc] + create_protocol = cast(Callable[..., WebSocketClientProtocol], create_protocol) + factory = functools.partial( + create_protocol, + logger=logger, + origin=origin, + extensions=extensions, + subprotocols=subprotocols, + extra_headers=extra_headers, + user_agent_header=user_agent_header, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_size=max_size, + max_queue=max_queue, + read_limit=read_limit, + write_limit=write_limit, + host=wsuri.host, + port=wsuri.port, + secure=wsuri.secure, + legacy_recv=legacy_recv, + loop=_loop, + ) + + if kwargs.pop("unix", False): + path: str | None = kwargs.pop("path", None) + create_connection = functools.partial( + loop.create_unix_connection, factory, path, **kwargs + ) + else: + host: str | None + port: int | None + if kwargs.get("sock") is None: + host, port = wsuri.host, wsuri.port + else: + # If sock is given, host and port shouldn't be specified. + host, port = None, None + if kwargs.get("ssl"): + kwargs.setdefault("server_hostname", wsuri.host) + # If host and port are given, override values from the URI. + host = kwargs.pop("host", host) + port = kwargs.pop("port", port) + create_connection = functools.partial( + loop.create_connection, factory, host, port, **kwargs + ) + + self.open_timeout = open_timeout + if logger is None: + logger = logging.getLogger("websockets.client") + self.logger = logger + + # This is a coroutine function. + self._create_connection = create_connection + self._uri = uri + self._wsuri = wsuri + + def handle_redirect(self, uri: str) -> None: + # Update the state of this instance to connect to a new URI. + old_uri = self._uri + old_wsuri = self._wsuri + new_uri = urllib.parse.urljoin(old_uri, uri) + new_wsuri = parse_uri(new_uri) + + # Forbid TLS downgrade. + if old_wsuri.secure and not new_wsuri.secure: + raise SecurityError("redirect from WSS to WS") + + same_origin = ( + old_wsuri.secure == new_wsuri.secure + and old_wsuri.host == new_wsuri.host + and old_wsuri.port == new_wsuri.port + ) + + # Rewrite secure, host, and port for cross-origin redirects. + # This preserves connection overrides with the host and port + # arguments if the redirect points to the same host and port. + if not same_origin: + factory = self._create_connection.args[0] + # Support TLS upgrade. + if not old_wsuri.secure and new_wsuri.secure: + factory.keywords["secure"] = True + self._create_connection.keywords.setdefault("ssl", True) + # Replace secure, host, and port arguments of the protocol factory. + factory = functools.partial( + factory.func, + *factory.args, + **dict(factory.keywords, host=new_wsuri.host, port=new_wsuri.port), + ) + # Replace secure, host, and port arguments of create_connection. + self._create_connection = functools.partial( + self._create_connection.func, + *(factory, new_wsuri.host, new_wsuri.port), + **self._create_connection.keywords, + ) + + # Set the new WebSocket URI. This suffices for same-origin redirects. + self._uri = new_uri + self._wsuri = new_wsuri + + # async for ... in connect(...): + + BACKOFF_INITIAL = float(os.environ.get("WEBSOCKETS_BACKOFF_INITIAL_DELAY", "5")) + BACKOFF_MIN = float(os.environ.get("WEBSOCKETS_BACKOFF_MIN_DELAY", "3.1")) + BACKOFF_MAX = float(os.environ.get("WEBSOCKETS_BACKOFF_MAX_DELAY", "90.0")) + BACKOFF_FACTOR = float(os.environ.get("WEBSOCKETS_BACKOFF_FACTOR", "1.618")) + + async def __aiter__(self) -> AsyncIterator[WebSocketClientProtocol]: + backoff_delay = self.BACKOFF_MIN / self.BACKOFF_FACTOR + while True: + try: + async with self as protocol: + yield protocol + except Exception as exc: + # Add a random initial delay between 0 and 5 seconds. + # See 7.2.3. Recovering from Abnormal Closure in RFC 6455. + if backoff_delay == self.BACKOFF_MIN: + initial_delay = random.random() * self.BACKOFF_INITIAL + self.logger.info( + "connect failed; reconnecting in %.1f seconds: %s", + initial_delay, + traceback.format_exception_only(exc)[0].strip(), + ) + await asyncio.sleep(initial_delay) + else: + self.logger.info( + "connect failed again; retrying in %d seconds: %s", + int(backoff_delay), + traceback.format_exception_only(exc)[0].strip(), + ) + await asyncio.sleep(int(backoff_delay)) + # Increase delay with truncated exponential backoff. + backoff_delay = backoff_delay * self.BACKOFF_FACTOR + backoff_delay = min(backoff_delay, self.BACKOFF_MAX) + continue + else: + # Connection succeeded - reset backoff delay + backoff_delay = self.BACKOFF_MIN + + # async with connect(...) as ...: + + async def __aenter__(self) -> WebSocketClientProtocol: + return await self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + await self.protocol.close() + + # ... = await connect(...) + + def __await__(self) -> Generator[Any, None, WebSocketClientProtocol]: + # Create a suitable iterator by calling __await__ on a coroutine. + return self.__await_impl__().__await__() + + async def __await_impl__(self) -> WebSocketClientProtocol: + async with asyncio_timeout(self.open_timeout): + for _redirects in range(self.MAX_REDIRECTS_ALLOWED): + _transport, protocol = await self._create_connection() + try: + await protocol.handshake( + self._wsuri, + origin=protocol.origin, + available_extensions=protocol.available_extensions, + available_subprotocols=protocol.available_subprotocols, + extra_headers=protocol.extra_headers, + ) + except RedirectHandshake as exc: + protocol.fail_connection() + await protocol.wait_closed() + self.handle_redirect(exc.uri) + # Avoid leaking a connected socket when the handshake fails. + except (Exception, asyncio.CancelledError): + protocol.fail_connection() + await protocol.wait_closed() + raise + else: + self.protocol = protocol + return protocol + else: + raise SecurityError("too many redirects") + + # ... = yield from connect(...) - remove when dropping Python < 3.11 + + __iter__ = __await__ + + +connect = Connect + + +def unix_connect( + path: str | None = None, + uri: str = "ws://localhost/", + **kwargs: Any, +) -> Connect: + """ + Similar to :func:`connect`, but for connecting to a Unix socket. + + This function builds upon the event loop's + :meth:`~asyncio.loop.create_unix_connection` method. + + It is only available on Unix. + + It's mainly useful for debugging servers listening on Unix sockets. + + Args: + path: File system path to the Unix socket. + uri: URI of the WebSocket server; the host is used in the TLS + handshake for secure connections and in the ``Host`` header. + + """ + return connect(uri=uri, path=path, unix=True, **kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/exceptions.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..03d7ac6d31bd025afb1e8ae67132ab691915e154 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/exceptions.py @@ -0,0 +1,71 @@ +import http + +from .. import datastructures +from ..exceptions import ( + InvalidHandshake, + # InvalidMessage was incorrectly moved here in versions 14.0 and 14.1. + InvalidMessage, # noqa: F401 + ProtocolError as WebSocketProtocolError, # noqa: F401 +) +from ..typing import StatusLike + + +class InvalidStatusCode(InvalidHandshake): + """ + Raised when a handshake response status code is invalid. + + """ + + def __init__(self, status_code: int, headers: datastructures.Headers) -> None: + self.status_code = status_code + self.headers = headers + + def __str__(self) -> str: + return f"server rejected WebSocket connection: HTTP {self.status_code}" + + +class AbortHandshake(InvalidHandshake): + """ + Raised to abort the handshake on purpose and return an HTTP response. + + This exception is an implementation detail. + + The public API is + :meth:`~websockets.legacy.server.WebSocketServerProtocol.process_request`. + + Attributes: + status (~http.HTTPStatus): HTTP status code. + headers (Headers): HTTP response headers. + body (bytes): HTTP response body. + """ + + def __init__( + self, + status: StatusLike, + headers: datastructures.HeadersLike, + body: bytes = b"", + ) -> None: + # If a user passes an int instead of an HTTPStatus, fix it automatically. + self.status = http.HTTPStatus(status) + self.headers = datastructures.Headers(headers) + self.body = body + + def __str__(self) -> str: + return ( + f"HTTP {self.status:d}, {len(self.headers)} headers, {len(self.body)} bytes" + ) + + +class RedirectHandshake(InvalidHandshake): + """ + Raised when a handshake gets redirected. + + This exception is an implementation detail. + + """ + + def __init__(self, uri: str) -> None: + self.uri = uri + + def __str__(self) -> str: + return f"redirect to {self.uri}" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/framing.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/framing.py new file mode 100644 index 0000000000000000000000000000000000000000..e63e7a28cbc5886929ad444d65c13efc50f5af0b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/framing.py @@ -0,0 +1,224 @@ +from __future__ import annotations + +import struct +from collections.abc import Awaitable, Sequence +from typing import Any, Callable, NamedTuple + +from .. import extensions, frames +from ..exceptions import PayloadTooBig, ProtocolError +from ..typing import BytesLike, DataLike + + +try: + from ..speedups import apply_mask +except ImportError: + from ..utils import apply_mask + + +class Frame(NamedTuple): + fin: bool + opcode: frames.Opcode + data: BytesLike + rsv1: bool = False + rsv2: bool = False + rsv3: bool = False + + @property + def new_frame(self) -> frames.Frame: + return frames.Frame( + self.opcode, + self.data, + self.fin, + self.rsv1, + self.rsv2, + self.rsv3, + ) + + def __str__(self) -> str: + return str(self.new_frame) + + def check(self) -> None: + return self.new_frame.check() + + @classmethod + async def read( + cls, + reader: Callable[[int], Awaitable[bytes]], + *, + mask: bool, + max_size: int | None = None, + extensions: Sequence[extensions.Extension] | None = None, + ) -> Frame: + """ + Read a WebSocket frame. + + Args: + reader: Coroutine that reads exactly the requested number of + bytes, unless the end of file is reached. + mask: Whether the frame should be masked i.e. whether the read + happens on the server side. + max_size: Maximum payload size in bytes. + extensions: List of extensions, applied in reverse order. + + Raises: + PayloadTooBig: If the frame exceeds ``max_size``. + ProtocolError: If the frame contains incorrect values. + + """ + + # Read the header. + data = await reader(2) + head1, head2 = struct.unpack("!BB", data) + + # While not Pythonic, this is marginally faster than calling bool(). + fin = True if head1 & 0b10000000 else False + rsv1 = True if head1 & 0b01000000 else False + rsv2 = True if head1 & 0b00100000 else False + rsv3 = True if head1 & 0b00010000 else False + + try: + opcode = frames.Opcode(head1 & 0b00001111) + except ValueError as exc: + raise ProtocolError("invalid opcode") from exc + + if (True if head2 & 0b10000000 else False) != mask: + raise ProtocolError("incorrect masking") + + length = head2 & 0b01111111 + if length == 126: + data = await reader(2) + (length,) = struct.unpack("!H", data) + elif length == 127: + data = await reader(8) + (length,) = struct.unpack("!Q", data) + if max_size is not None and length > max_size: + raise PayloadTooBig(length, max_size) + if mask: + mask_bits = await reader(4) + + # Read the data. + data = await reader(length) + if mask: + data = apply_mask(data, mask_bits) + + new_frame = frames.Frame(opcode, data, fin, rsv1, rsv2, rsv3) + + if extensions is None: + extensions = [] + for extension in reversed(extensions): + new_frame = extension.decode(new_frame, max_size=max_size) + + new_frame.check() + + return cls( + new_frame.fin, + new_frame.opcode, + new_frame.data, + new_frame.rsv1, + new_frame.rsv2, + new_frame.rsv3, + ) + + def write( + self, + write: Callable[[bytes], Any], + *, + mask: bool, + extensions: Sequence[extensions.Extension] | None = None, + ) -> None: + """ + Write a WebSocket frame. + + Args: + frame: Frame to write. + write: Function that writes bytes. + mask: Whether the frame should be masked i.e. whether the write + happens on the client side. + extensions: List of extensions, applied in order. + + Raises: + ProtocolError: If the frame contains incorrect values. + + """ + # The frame is written in a single call to write in order to prevent + # TCP fragmentation. See #68 for details. This also makes it safe to + # send frames concurrently from multiple coroutines. + write(self.new_frame.serialize(mask=mask, extensions=extensions)) + + +def prepare_data(data: DataLike) -> tuple[int, BytesLike]: + """ + Convert a string or byte-like object to an opcode and a bytes-like object. + + This function is designed for data frames. + + If ``data`` is a :class:`str`, return ``OP_TEXT`` and a :class:`bytes` + object encoding ``data`` in UTF-8. + + If ``data`` is a bytes-like object, return ``OP_BINARY`` and a bytes-like + object. + + Raises: + TypeError: If ``data`` doesn't have a supported type. + + """ + if isinstance(data, str): + return frames.Opcode.TEXT, data.encode() + elif isinstance(data, BytesLike): + return frames.Opcode.BINARY, data + else: + raise TypeError("data must be str or bytes-like") + + +def prepare_ctrl(data: DataLike) -> bytes: + """ + Convert a string or byte-like object to bytes. + + This function is designed for ping and pong frames. + + If ``data`` is a :class:`str`, return a :class:`bytes` object encoding + ``data`` in UTF-8. + + If ``data`` is a bytes-like object, return a :class:`bytes` object. + + Raises: + TypeError: If ``data`` doesn't have a supported type. + + """ + if isinstance(data, str): + return data.encode() + elif isinstance(data, BytesLike): + return bytes(data) + else: + raise TypeError("data must be str or bytes-like") + + +# Backwards compatibility with previously documented public APIs +encode_data = prepare_ctrl + +# Backwards compatibility with previously documented public APIs +from ..frames import Close # noqa: E402 F401, I001 + + +def parse_close(data: bytes) -> tuple[int, str]: + """ + Parse the payload from a close frame. + + Returns: + Close code and reason. + + Raises: + ProtocolError: If data is ill-formed. + UnicodeDecodeError: If the reason isn't valid UTF-8. + + """ + close = Close.parse(data) + return close.code, close.reason + + +def serialize_close(code: int, reason: str) -> bytes: + """ + Serialize the payload for a close frame. + + """ + return Close(code, reason).serialize() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/handshake.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/handshake.py new file mode 100644 index 0000000000000000000000000000000000000000..312db7a458591c75c1081da99bdd5168ac2bbba5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/handshake.py @@ -0,0 +1,158 @@ +from __future__ import annotations + +import base64 +import binascii + +from ..datastructures import Headers, MultipleValuesError +from ..exceptions import InvalidHeader, InvalidHeaderValue, InvalidUpgrade +from ..headers import parse_connection, parse_upgrade +from ..typing import ConnectionOption, UpgradeProtocol +from ..utils import accept_key as accept, generate_key + + +__all__ = ["build_request", "check_request", "build_response", "check_response"] + + +def build_request(headers: Headers) -> str: + """ + Build a handshake request to send to the server. + + Update request headers passed in argument. + + Args: + headers: Handshake request headers. + + Returns: + ``key`` that must be passed to :func:`check_response`. + + """ + key = generate_key() + headers["Upgrade"] = "websocket" + headers["Connection"] = "Upgrade" + headers["Sec-WebSocket-Key"] = key + headers["Sec-WebSocket-Version"] = "13" + return key + + +def check_request(headers: Headers) -> str: + """ + Check a handshake request received from the client. + + This function doesn't verify that the request is an HTTP/1.1 or higher GET + request and doesn't perform ``Host`` and ``Origin`` checks. These controls + are usually performed earlier in the HTTP request handling code. They're + the responsibility of the caller. + + Args: + headers: Handshake request headers. + + Returns: + ``key`` that must be passed to :func:`build_response`. + + Raises: + InvalidHandshake: If the handshake request is invalid. + Then, the server must return a 400 Bad Request error. + + """ + connection: list[ConnectionOption] = sum( + [parse_connection(value) for value in headers.get_all("Connection")], [] + ) + + if not any(value.lower() == "upgrade" for value in connection): + raise InvalidUpgrade("Connection", ", ".join(connection)) + + upgrade: list[UpgradeProtocol] = sum( + [parse_upgrade(value) for value in headers.get_all("Upgrade")], [] + ) + + # For compatibility with non-strict implementations, ignore case when + # checking the Upgrade header. The RFC always uses "websocket", except + # in section 11.2. (IANA registration) where it uses "WebSocket". + if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"): + raise InvalidUpgrade("Upgrade", ", ".join(upgrade)) + + try: + s_w_key = headers["Sec-WebSocket-Key"] + except KeyError as exc: + raise InvalidHeader("Sec-WebSocket-Key") from exc + except MultipleValuesError as exc: + raise InvalidHeader("Sec-WebSocket-Key", "multiple values") from exc + + try: + raw_key = base64.b64decode(s_w_key.encode(), validate=True) + except binascii.Error as exc: + raise InvalidHeaderValue("Sec-WebSocket-Key", s_w_key) from exc + if len(raw_key) != 16: + raise InvalidHeaderValue("Sec-WebSocket-Key", s_w_key) + + try: + s_w_version = headers["Sec-WebSocket-Version"] + except KeyError as exc: + raise InvalidHeader("Sec-WebSocket-Version") from exc + except MultipleValuesError as exc: + raise InvalidHeader("Sec-WebSocket-Version", "multiple values") from exc + + if s_w_version != "13": + raise InvalidHeaderValue("Sec-WebSocket-Version", s_w_version) + + return s_w_key + + +def build_response(headers: Headers, key: str) -> None: + """ + Build a handshake response to send to the client. + + Update response headers passed in argument. + + Args: + headers: Handshake response headers. + key: Returned by :func:`check_request`. + + """ + headers["Upgrade"] = "websocket" + headers["Connection"] = "Upgrade" + headers["Sec-WebSocket-Accept"] = accept(key) + + +def check_response(headers: Headers, key: str) -> None: + """ + Check a handshake response received from the server. + + This function doesn't verify that the response is an HTTP/1.1 or higher + response with a 101 status code. These controls are the responsibility of + the caller. + + Args: + headers: Handshake response headers. + key: Returned by :func:`build_request`. + + Raises: + InvalidHandshake: If the handshake response is invalid. + + """ + connection: list[ConnectionOption] = sum( + [parse_connection(value) for value in headers.get_all("Connection")], [] + ) + + if not any(value.lower() == "upgrade" for value in connection): + raise InvalidUpgrade("Connection", " ".join(connection)) + + upgrade: list[UpgradeProtocol] = sum( + [parse_upgrade(value) for value in headers.get_all("Upgrade")], [] + ) + + # For compatibility with non-strict implementations, ignore case when + # checking the Upgrade header. The RFC always uses "websocket", except + # in section 11.2. (IANA registration) where it uses "WebSocket". + if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"): + raise InvalidUpgrade("Upgrade", ", ".join(upgrade)) + + try: + s_w_accept = headers["Sec-WebSocket-Accept"] + except KeyError as exc: + raise InvalidHeader("Sec-WebSocket-Accept") from exc + except MultipleValuesError as exc: + raise InvalidHeader("Sec-WebSocket-Accept", "multiple values") from exc + + if s_w_accept != accept(key): + raise InvalidHeaderValue("Sec-WebSocket-Accept", s_w_accept) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/http.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/http.py new file mode 100644 index 0000000000000000000000000000000000000000..cca5f14eb85f5b69079861724be71a025a863c72 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/http.py @@ -0,0 +1,201 @@ +from __future__ import annotations + +import asyncio +import os +import re + +from ..datastructures import Headers +from ..exceptions import SecurityError + + +__all__ = ["read_request", "read_response"] + +MAX_NUM_HEADERS = int(os.environ.get("WEBSOCKETS_MAX_NUM_HEADERS", "128")) +MAX_LINE_LENGTH = int(os.environ.get("WEBSOCKETS_MAX_LINE_LENGTH", "8192")) + + +def d(value: bytes) -> str: + """ + Decode a bytestring for interpolating into an error message. + + """ + return value.decode(errors="backslashreplace") + + +# See https://datatracker.ietf.org/doc/html/rfc7230#appendix-B. + +# Regex for validating header names. + +_token_re = re.compile(rb"[-!#$%&\'*+.^_`|~0-9a-zA-Z]+") + +# Regex for validating header values. + +# We don't attempt to support obsolete line folding. + +# Include HTAB (\x09), SP (\x20), VCHAR (\x21-\x7e), obs-text (\x80-\xff). + +# The ABNF is complicated because it attempts to express that optional +# whitespace is ignored. We strip whitespace and don't revalidate that. + +# See also https://www.rfc-editor.org/errata_search.php?rfc=7230&eid=4189 + +_value_re = re.compile(rb"[\x09\x20-\x7e\x80-\xff]*") + + +async def read_request(stream: asyncio.StreamReader) -> tuple[str, Headers]: + """ + Read an HTTP/1.1 GET request and return ``(path, headers)``. + + ``path`` isn't URL-decoded or validated in any way. + + ``path`` and ``headers`` are expected to contain only ASCII characters. + Other characters are represented with surrogate escapes. + + :func:`read_request` doesn't attempt to read the request body because + WebSocket handshake requests don't have one. If the request contains a + body, it may be read from ``stream`` after this coroutine returns. + + Args: + stream: Input to read the request from. + + Raises: + EOFError: If the connection is closed without a full HTTP request. + SecurityError: If the request exceeds a security limit. + ValueError: If the request isn't well formatted. + + """ + # https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.1 + + # Parsing is simple because fixed values are expected for method and + # version and because path isn't checked. Since WebSocket software tends + # to implement HTTP/1.1 strictly, there's little need for lenient parsing. + + try: + request_line = await read_line(stream) + except EOFError as exc: + raise EOFError("connection closed while reading HTTP request line") from exc + + try: + method, raw_path, version = request_line.split(b" ", 2) + except ValueError: # not enough values to unpack (expected 3, got 1-2) + raise ValueError(f"invalid HTTP request line: {d(request_line)}") from None + + if method != b"GET": + raise ValueError(f"unsupported HTTP method: {d(method)}") + if version != b"HTTP/1.1": + raise ValueError(f"unsupported HTTP version: {d(version)}") + path = raw_path.decode("ascii", "surrogateescape") + + headers = await read_headers(stream) + + return path, headers + + +async def read_response(stream: asyncio.StreamReader) -> tuple[int, str, Headers]: + """ + Read an HTTP/1.1 response and return ``(status_code, reason, headers)``. + + ``reason`` and ``headers`` are expected to contain only ASCII characters. + Other characters are represented with surrogate escapes. + + :func:`read_request` doesn't attempt to read the response body because + WebSocket handshake responses don't have one. If the response contains a + body, it may be read from ``stream`` after this coroutine returns. + + Args: + stream: Input to read the response from. + + Raises: + EOFError: If the connection is closed without a full HTTP response. + SecurityError: If the response exceeds a security limit. + ValueError: If the response isn't well formatted. + + """ + # https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2 + + # As in read_request, parsing is simple because a fixed value is expected + # for version, status_code is a 3-digit number, and reason can be ignored. + + try: + status_line = await read_line(stream) + except EOFError as exc: + raise EOFError("connection closed while reading HTTP status line") from exc + + try: + version, raw_status_code, raw_reason = status_line.split(b" ", 2) + except ValueError: # not enough values to unpack (expected 3, got 1-2) + raise ValueError(f"invalid HTTP status line: {d(status_line)}") from None + + if version != b"HTTP/1.1": + raise ValueError(f"unsupported HTTP version: {d(version)}") + try: + status_code = int(raw_status_code) + except ValueError: # invalid literal for int() with base 10 + raise ValueError(f"invalid HTTP status code: {d(raw_status_code)}") from None + if not 100 <= status_code < 1000: + raise ValueError(f"unsupported HTTP status code: {d(raw_status_code)}") + if not _value_re.fullmatch(raw_reason): + raise ValueError(f"invalid HTTP reason phrase: {d(raw_reason)}") + reason = raw_reason.decode() + + headers = await read_headers(stream) + + return status_code, reason, headers + + +async def read_headers(stream: asyncio.StreamReader) -> Headers: + """ + Read HTTP headers from ``stream``. + + Non-ASCII characters are represented with surrogate escapes. + + """ + # https://datatracker.ietf.org/doc/html/rfc7230#section-3.2 + + # We don't attempt to support obsolete line folding. + + headers = Headers() + for _ in range(MAX_NUM_HEADERS + 1): + try: + line = await read_line(stream) + except EOFError as exc: + raise EOFError("connection closed while reading HTTP headers") from exc + if line == b"": + break + + try: + raw_name, raw_value = line.split(b":", 1) + except ValueError: # not enough values to unpack (expected 2, got 1) + raise ValueError(f"invalid HTTP header line: {d(line)}") from None + if not _token_re.fullmatch(raw_name): + raise ValueError(f"invalid HTTP header name: {d(raw_name)}") + raw_value = raw_value.strip(b" \t") + if not _value_re.fullmatch(raw_value): + raise ValueError(f"invalid HTTP header value: {d(raw_value)}") + + name = raw_name.decode("ascii") # guaranteed to be ASCII at this point + value = raw_value.decode("ascii", "surrogateescape") + headers[name] = value + + else: + raise SecurityError("too many HTTP headers") + + return headers + + +async def read_line(stream: asyncio.StreamReader) -> bytes: + """ + Read a single line from ``stream``. + + CRLF is stripped from the return value. + + """ + # Security: this is bounded by the StreamReader's limit (default = 32 KiB). + line = await stream.readline() + # Security: this guarantees header values are small (hard-coded = 8 KiB) + if len(line) > MAX_LINE_LENGTH: + raise SecurityError("line too long") + # Not mandatory but safe - https://datatracker.ietf.org/doc/html/rfc7230#section-3.5 + if not line.endswith(b"\r\n"): + raise EOFError("line without CRLF") + return line[:-2] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/protocol.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..6feddff49139b0e5127f6a0fc3f1587ff8fc5f7a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/protocol.py @@ -0,0 +1,1635 @@ +from __future__ import annotations + +import asyncio +import codecs +import collections +import logging +import random +import ssl +import struct +import sys +import time +import traceback +import uuid +import warnings +from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Iterable, Mapping +from typing import Any, Callable, Deque, cast + +from ..asyncio.compatibility import asyncio_timeout +from ..datastructures import Headers +from ..exceptions import ( + ConnectionClosed, + ConnectionClosedError, + ConnectionClosedOK, + InvalidState, + PayloadTooBig, + ProtocolError, +) +from ..extensions import Extension +from ..frames import ( + OK_CLOSE_CODES, + OP_BINARY, + OP_CLOSE, + OP_CONT, + OP_PING, + OP_PONG, + OP_TEXT, + Close, + CloseCode, + Opcode, +) +from ..protocol import State +from ..typing import BytesLike, Data, DataLike, LoggerLike, Subprotocol +from .framing import Frame, prepare_ctrl, prepare_data + + +__all__ = ["WebSocketCommonProtocol"] + + +# In order to ensure consistency, the code always checks the current value of +# WebSocketCommonProtocol.state before assigning a new value and never yields +# between the check and the assignment. + + +class WebSocketCommonProtocol(asyncio.Protocol): + """ + WebSocket connection. + + :class:`WebSocketCommonProtocol` provides APIs shared between WebSocket + servers and clients. You shouldn't use it directly. Instead, use + :class:`~websockets.legacy.client.WebSocketClientProtocol` or + :class:`~websockets.legacy.server.WebSocketServerProtocol`. + + This documentation focuses on low-level details that aren't covered in the + documentation of :class:`~websockets.legacy.client.WebSocketClientProtocol` + and :class:`~websockets.legacy.server.WebSocketServerProtocol` for the sake + of simplicity. + + Once the connection is open, a Ping_ frame is sent every ``ping_interval`` + seconds. This serves as a keepalive. It helps keeping the connection open, + especially in the presence of proxies with short timeouts on inactive + connections. Set ``ping_interval`` to :obj:`None` to disable this behavior. + + .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2 + + If the corresponding Pong_ frame isn't received within ``ping_timeout`` + seconds, the connection is considered unusable and is closed with code 1011. + This ensures that the remote endpoint remains responsive. Set + ``ping_timeout`` to :obj:`None` to disable this behavior. + + .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3 + + See the discussion of :doc:`keepalive <../../topics/keepalive>` for details. + + The ``close_timeout`` parameter defines a maximum wait time for completing + the closing handshake and terminating the TCP connection. For legacy + reasons, :meth:`close` completes in at most ``5 * close_timeout`` seconds + for clients and ``4 * close_timeout`` for servers. + + ``close_timeout`` is a parameter of the protocol because websockets usually + calls :meth:`close` implicitly upon exit: + + * on the client side, when using :func:`~websockets.legacy.client.connect` + as a context manager; + * on the server side, when the connection handler terminates. + + To apply a timeout to any other API, wrap it in :func:`~asyncio.timeout` or + :func:`~asyncio.wait_for`. + + The ``max_size`` parameter enforces the maximum size for incoming messages + in bytes. The default value is 1 MiB. If a larger message is received, + :meth:`recv` will raise :exc:`~websockets.exceptions.ConnectionClosedError` + and the connection will be closed with code 1009. + + The ``max_queue`` parameter sets the maximum length of the queue that + holds incoming messages. The default value is ``32``. Messages are added + to an in-memory queue when they're received; then :meth:`recv` pops from + that queue. In order to prevent excessive memory consumption when + messages are received faster than they can be processed, the queue must + be bounded. If the queue fills up, the protocol stops processing incoming + data until :meth:`recv` is called. In this situation, various receive + buffers (at least in :mod:`asyncio` and in the OS) will fill up, then the + TCP receive window will shrink, slowing down transmission to avoid packet + loss. + + Since Python can use up to 4 bytes of memory to represent a single + character, each connection may use up to ``4 * max_size * max_queue`` + bytes of memory to store incoming messages. By default, this is 128 MiB. + You may want to lower the limits, depending on your application's + requirements. + + The ``read_limit`` argument sets the high-water limit of the buffer for + incoming bytes. The low-water limit is half the high-water limit. The + default value is 64 KiB, half of asyncio's default (based on the current + implementation of :class:`~asyncio.StreamReader`). + + The ``write_limit`` argument sets the high-water limit of the buffer for + outgoing bytes. The low-water limit is a quarter of the high-water limit. + The default value is 64 KiB, equal to asyncio's default (based on the + current implementation of ``FlowControlMixin``). + + See the discussion of :doc:`memory usage <../../topics/memory>` for details. + + Args: + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.protocol")``. + See the :doc:`logging guide <../../topics/logging>` for details. + ping_interval: Interval between keepalive pings in seconds. + :obj:`None` disables keepalive. + ping_timeout: Timeout for keepalive pings in seconds. + :obj:`None` disables timeouts. + close_timeout: Timeout for closing the connection in seconds. + For legacy reasons, the actual timeout is 4 or 5 times larger. + max_size: Maximum size of incoming messages in bytes. + :obj:`None` disables the limit. + max_queue: Maximum number of incoming messages in receive buffer. + :obj:`None` disables the limit. + read_limit: High-water mark of read buffer in bytes. + write_limit: High-water mark of write buffer in bytes. + + """ + + # There are only two differences between the client-side and server-side + # behavior: masking the payload and closing the underlying TCP connection. + # Set is_client = True/False and side = "client"/"server" to pick a side. + is_client: bool + side: str = "undefined" + + def __init__( + self, + *, + logger: LoggerLike | None = None, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = None, + max_size: int | None = 2**20, + max_queue: int | None = 2**5, + read_limit: int = 2**16, + write_limit: int = 2**16, + # The following arguments are kept only for backwards compatibility. + host: str | None = None, + port: int | None = None, + secure: bool | None = None, + legacy_recv: bool = False, + loop: asyncio.AbstractEventLoop | None = None, + timeout: float | None = None, + ) -> None: + if legacy_recv: # pragma: no cover + warnings.warn("legacy_recv is deprecated", DeprecationWarning) + + # Backwards compatibility: close_timeout used to be called timeout. + if timeout is None: + timeout = 10 + else: + warnings.warn("rename timeout to close_timeout", DeprecationWarning) + # If both are specified, timeout is ignored. + if close_timeout is None: + close_timeout = timeout + + # Backwards compatibility: the loop parameter used to be supported. + if loop is None: + loop = asyncio.get_event_loop() + else: + warnings.warn("remove loop argument", DeprecationWarning) + + self.ping_interval = ping_interval + self.ping_timeout = ping_timeout + self.close_timeout = close_timeout + self.max_size = max_size + self.max_queue = max_queue + self.read_limit = read_limit + self.write_limit = write_limit + + # Unique identifier. For logs. + self.id: uuid.UUID = uuid.uuid4() + """Unique identifier of the connection. Useful in logs.""" + + # Logger or LoggerAdapter for this connection. + if logger is None: + logger = logging.getLogger("websockets.protocol") + self.logger: LoggerLike = logging.LoggerAdapter(logger, {"websocket": self}) + """Logger for this connection.""" + + # Track if DEBUG is enabled. Shortcut logging calls if it isn't. + self.debug = logger.isEnabledFor(logging.DEBUG) + + self.loop = loop + + self._host = host + self._port = port + self._secure = secure + self.legacy_recv = legacy_recv + + # Configure read buffer limits. The high-water limit is defined by + # ``self.read_limit``. The ``limit`` argument controls the line length + # limit and half the buffer limit of :class:`~asyncio.StreamReader`. + # That's why it must be set to half of ``self.read_limit``. + self.reader = asyncio.StreamReader(limit=read_limit // 2, loop=loop) + + # Copied from asyncio.FlowControlMixin + self._paused = False + self._drain_waiter: asyncio.Future[None] | None = None + + # This class implements the data transfer and closing handshake, which + # are shared between the client-side and the server-side. + # Subclasses implement the opening handshake and, on success, execute + # :meth:`connection_open` to change the state to OPEN. + self.state = State.CONNECTING + if self.debug: + self.logger.debug("= connection is CONNECTING") + + # HTTP protocol parameters. + self.path: str + """Path of the opening handshake request.""" + self.request_headers: Headers + """Opening handshake request headers.""" + self.response_headers: Headers + """Opening handshake response headers.""" + + # WebSocket protocol parameters. + self.extensions: list[Extension] = [] + self.subprotocol: Subprotocol | None = None + """Subprotocol, if one was negotiated.""" + + # Close code and reason, set when a close frame is sent or received. + self.close_rcvd: Close | None = None + self.close_sent: Close | None = None + self.close_rcvd_then_sent: bool | None = None + + # Completed when the connection state becomes CLOSED. Translates the + # :meth:`connection_lost` callback to a :class:`~asyncio.Future` + # that can be awaited. (Other :class:`~asyncio.Protocol` callbacks are + # translated by ``self.stream_reader``). + self.connection_lost_waiter: asyncio.Future[None] = loop.create_future() + + # Queue of received messages. + self.messages: Deque[Data] = collections.deque() + self._pop_message_waiter: asyncio.Future[None] | None = None + self._put_message_waiter: asyncio.Future[None] | None = None + + # Protect sending fragmented messages. + self._fragmented_message_waiter: asyncio.Future[None] | None = None + + # Mapping of ping IDs to pong waiters, in chronological order. + self.pings: dict[bytes, tuple[asyncio.Future[float], float]] = {} + + self.latency: float = 0 + """ + Latency of the connection, in seconds. + + Latency is defined as the round-trip time of the connection. It is + measured by sending a Ping frame and waiting for a matching Pong frame. + Before the first measurement, :attr:`latency` is ``0``. + + By default, websockets enables a :ref:`keepalive ` mechanism + that sends Ping frames automatically at regular intervals. You can also + send Ping frames and measure latency with :meth:`ping`. + """ + + # Task running the data transfer. + self.transfer_data_task: asyncio.Task[None] + + # Exception that occurred during data transfer, if any. + self.transfer_data_exc: BaseException | None = None + + # Task sending keepalive pings. + self.keepalive_ping_task: asyncio.Task[None] + + # Task closing the TCP connection. + self.close_connection_task: asyncio.Task[None] + + # Copied from asyncio.FlowControlMixin + async def _drain_helper(self) -> None: # pragma: no cover + if self.connection_lost_waiter.done(): + raise ConnectionResetError("Connection lost") + if not self._paused: + return + waiter = self._drain_waiter + assert waiter is None or waiter.cancelled() + waiter = self.loop.create_future() + self._drain_waiter = waiter + await waiter + + # Copied from asyncio.StreamWriter + async def _drain(self) -> None: # pragma: no cover + if self.reader is not None: + exc = self.reader.exception() + if exc is not None: + raise exc + if self.transport is not None: + if self.transport.is_closing(): + # Yield to the event loop so connection_lost() may be + # called. Without this, _drain_helper() would return + # immediately, and code that calls + # write(...); yield from drain() + # in a loop would never call connection_lost(), so it + # would not see an error when the socket is closed. + await asyncio.sleep(0) + await self._drain_helper() + + def connection_open(self) -> None: + """ + Callback when the WebSocket opening handshake completes. + + Enter the OPEN state and start the data transfer phase. + + """ + # 4.1. The WebSocket Connection is Established. + assert self.state is State.CONNECTING + self.state = State.OPEN + if self.debug: + self.logger.debug("= connection is OPEN") + # Start the task that receives incoming WebSocket messages. + self.transfer_data_task = self.loop.create_task(self.transfer_data()) + # Start the task that sends pings at regular intervals. + self.keepalive_ping_task = self.loop.create_task(self.keepalive_ping()) + # Start the task that eventually closes the TCP connection. + self.close_connection_task = self.loop.create_task(self.close_connection()) + + @property + def host(self) -> str | None: + alternative = "remote_address" if self.is_client else "local_address" + warnings.warn(f"use {alternative}[0] instead of host", DeprecationWarning) + return self._host + + @property + def port(self) -> int | None: + alternative = "remote_address" if self.is_client else "local_address" + warnings.warn(f"use {alternative}[1] instead of port", DeprecationWarning) + return self._port + + @property + def secure(self) -> bool | None: + warnings.warn("don't use secure", DeprecationWarning) + return self._secure + + # Public API + + @property + def local_address(self) -> Any: + """ + Local address of the connection. + + For IPv4 connections, this is a ``(host, port)`` tuple. + + The format of the address depends on the address family; + see :meth:`~socket.socket.getsockname`. + + :obj:`None` if the TCP connection isn't established yet. + + """ + try: + transport = self.transport + except AttributeError: + return None + else: + return transport.get_extra_info("sockname") + + @property + def remote_address(self) -> Any: + """ + Remote address of the connection. + + For IPv4 connections, this is a ``(host, port)`` tuple. + + The format of the address depends on the address family; + see :meth:`~socket.socket.getpeername`. + + :obj:`None` if the TCP connection isn't established yet. + + """ + try: + transport = self.transport + except AttributeError: + return None + else: + return transport.get_extra_info("peername") + + @property + def open(self) -> bool: + """ + :obj:`True` when the connection is open; :obj:`False` otherwise. + + This attribute may be used to detect disconnections. However, this + approach is discouraged per the EAFP_ principle. Instead, you should + handle :exc:`~websockets.exceptions.ConnectionClosed` exceptions. + + .. _EAFP: https://docs.python.org/3/glossary.html#term-eafp + + """ + return self.state is State.OPEN and not self.transfer_data_task.done() + + @property + def closed(self) -> bool: + """ + :obj:`True` when the connection is closed; :obj:`False` otherwise. + + Be aware that both :attr:`open` and :attr:`closed` are :obj:`False` + during the opening and closing sequences. + + """ + return self.state is State.CLOSED + + @property + def close_code(self) -> int | None: + """ + WebSocket close code, defined in `section 7.1.5 of RFC 6455`_. + + .. _section 7.1.5 of RFC 6455: + https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 + + :obj:`None` if the connection isn't closed yet. + + """ + if self.state is not State.CLOSED: + return None + elif self.close_rcvd is None: + return CloseCode.ABNORMAL_CLOSURE + else: + return self.close_rcvd.code + + @property + def close_reason(self) -> str | None: + """ + WebSocket close reason, defined in `section 7.1.6 of RFC 6455`_. + + .. _section 7.1.6 of RFC 6455: + https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 + + :obj:`None` if the connection isn't closed yet. + + """ + if self.state is not State.CLOSED: + return None + elif self.close_rcvd is None: + return "" + else: + return self.close_rcvd.reason + + async def __aiter__(self) -> AsyncIterator[Data]: + """ + Iterate on incoming messages. + + The iterator exits normally when the connection is closed with the close + code 1000 (OK) or 1001 (going away) or without a close code. + + It raises a :exc:`~websockets.exceptions.ConnectionClosedError` + exception when the connection is closed with any other code. + + """ + try: + while True: + yield await self.recv() + except ConnectionClosedOK: + return + + async def recv(self) -> Data: + """ + Receive the next message. + + When the connection is closed, :meth:`recv` raises + :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises + :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal + connection closure and + :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol + error or a network failure. This is how you detect the end of the + message stream. + + Canceling :meth:`recv` is safe. There's no risk of losing the next + message. The next invocation of :meth:`recv` will return it. + + This makes it possible to enforce a timeout by wrapping :meth:`recv` in + :func:`~asyncio.timeout` or :func:`~asyncio.wait_for`. + + Returns: + A string (:class:`str`) for a Text_ frame. A bytestring + (:class:`bytes`) for a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + Raises: + ConnectionClosed: When the connection is closed. + RuntimeError: If two coroutines call :meth:`recv` concurrently. + + """ + if self._pop_message_waiter is not None: + raise RuntimeError( + "cannot call recv while another coroutine " + "is already waiting for the next message" + ) + + # Don't await self.ensure_open() here: + # - messages could be available in the queue even if the connection + # is closed; + # - messages could be received before the closing frame even if the + # connection is closing. + + # Wait until there's a message in the queue (if necessary) or the + # connection is closed. + while len(self.messages) <= 0: + pop_message_waiter: asyncio.Future[None] = self.loop.create_future() + self._pop_message_waiter = pop_message_waiter + try: + # If asyncio.wait() is canceled, it doesn't cancel + # pop_message_waiter and self.transfer_data_task. + await asyncio.wait( + [pop_message_waiter, self.transfer_data_task], + return_when=asyncio.FIRST_COMPLETED, + ) + finally: + self._pop_message_waiter = None + + # If asyncio.wait(...) exited because self.transfer_data_task + # completed before receiving a new message, raise a suitable + # exception (or return None if legacy_recv is enabled). + if not pop_message_waiter.done(): + if self.legacy_recv: + return None # type: ignore + else: + # Wait until the connection is closed to raise + # ConnectionClosed with the correct code and reason. + await self.ensure_open() + + # Pop a message from the queue. + message = self.messages.popleft() + + # Notify transfer_data(). + if self._put_message_waiter is not None: + self._put_message_waiter.set_result(None) + self._put_message_waiter = None + + return message + + async def send( + self, + message: DataLike | Iterable[DataLike] | AsyncIterable[DataLike], + ) -> None: + """ + Send a message. + + A string (:class:`str`) is sent as a Text_ frame. A bytestring or + bytes-like object (:class:`bytes`, :class:`bytearray`, or + :class:`memoryview`) is sent as a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + :meth:`send` also accepts an iterable or an asynchronous iterable of + strings, bytestrings, or bytes-like objects to enable fragmentation_. + Each item is treated as a message fragment and sent in its own frame. + All items must be of the same type, or else :meth:`send` will raise a + :exc:`TypeError` and the connection will be closed. + + .. _fragmentation: https://datatracker.ietf.org/doc/html/rfc6455#section-5.4 + + :meth:`send` rejects dict-like objects because this is often an error. + (If you want to send the keys of a dict-like object as fragments, call + its :meth:`~dict.keys` method and pass the result to :meth:`send`.) + + Canceling :meth:`send` is discouraged. Instead, you should close the + connection with :meth:`close`. Indeed, there are only two situations + where :meth:`send` may yield control to the event loop and then get + canceled; in both cases, :meth:`close` has the same effect and is + more clear: + + 1. The write buffer is full. If you don't want to wait until enough + data is sent, your only alternative is to close the connection. + :meth:`close` will likely time out then abort the TCP connection. + 2. ``message`` is an asynchronous iterator that yields control. + Stopping in the middle of a fragmented message will cause a + protocol error and the connection will be closed. + + When the connection is closed, :meth:`send` raises + :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it + raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal + connection closure and + :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol + error or a network failure. + + Args: + message: Message to send. + + Raises: + ConnectionClosed: When the connection is closed. + TypeError: If ``message`` doesn't have a supported type. + + """ + await self.ensure_open() + + # While sending a fragmented message, prevent sending other messages + # until all fragments are sent. + while self._fragmented_message_waiter is not None: + await asyncio.shield(self._fragmented_message_waiter) + + # Unfragmented message -- this case must be handled first because + # strings and bytes-like objects are iterable. + + if isinstance(message, (str, bytes, bytearray, memoryview)): + opcode, data = prepare_data(message) + await self.write_frame(True, opcode, data) + + # Catch a common mistake -- passing a dict to send(). + + elif isinstance(message, Mapping): + raise TypeError("data is a dict-like object") + + # Fragmented message -- regular iterator. + + elif isinstance(message, Iterable): + iter_message = iter(message) + try: + fragment = next(iter_message) + except StopIteration: + return + opcode, data = prepare_data(fragment) + + self._fragmented_message_waiter = self.loop.create_future() + try: + # First fragment. + await self.write_frame(False, opcode, data) + + # Other fragments. + for fragment in iter_message: + confirm_opcode, data = prepare_data(fragment) + if confirm_opcode != opcode: + raise TypeError("data contains inconsistent types") + await self.write_frame(False, OP_CONT, data) + + # Final fragment. + await self.write_frame(True, OP_CONT, b"") + + except (Exception, asyncio.CancelledError): + # We're half-way through a fragmented message and we can't + # complete it. This makes the connection unusable. + self.fail_connection(CloseCode.INTERNAL_ERROR) + raise + + finally: + self._fragmented_message_waiter.set_result(None) + self._fragmented_message_waiter = None + + # Fragmented message -- asynchronous iterator + + elif isinstance(message, AsyncIterable): + # Implement aiter_message = aiter(message) without aiter + # Work around https://github.com/python/mypy/issues/5738 + aiter_message = cast( + Callable[[AsyncIterable[DataLike]], AsyncIterator[DataLike]], + type(message).__aiter__, + )(message) + try: + # Implement fragment = anext(aiter_message) without anext + # Work around https://github.com/python/mypy/issues/5738 + fragment = await cast( + Callable[[AsyncIterator[DataLike]], Awaitable[DataLike]], + type(aiter_message).__anext__, + )(aiter_message) + except StopAsyncIteration: + return + opcode, data = prepare_data(fragment) + + self._fragmented_message_waiter = self.loop.create_future() + try: + # First fragment. + await self.write_frame(False, opcode, data) + + # Other fragments. + async for fragment in aiter_message: + confirm_opcode, data = prepare_data(fragment) + if confirm_opcode != opcode: + raise TypeError("data contains inconsistent types") + await self.write_frame(False, OP_CONT, data) + + # Final fragment. + await self.write_frame(True, OP_CONT, b"") + + except (Exception, asyncio.CancelledError): + # We're half-way through a fragmented message and we can't + # complete it. This makes the connection unusable. + self.fail_connection(CloseCode.INTERNAL_ERROR) + raise + + finally: + self._fragmented_message_waiter.set_result(None) + self._fragmented_message_waiter = None + + else: + raise TypeError("data must be str, bytes-like, or iterable") + + async def close( + self, + code: int = CloseCode.NORMAL_CLOSURE, + reason: str = "", + ) -> None: + """ + Perform the closing handshake. + + :meth:`close` waits for the other end to complete the handshake and + for the TCP connection to terminate. As a consequence, there's no need + to await :meth:`wait_closed` after :meth:`close`. + + :meth:`close` is idempotent: it doesn't do anything once the + connection is closed. + + Wrapping :func:`close` in :func:`~asyncio.create_task` is safe, given + that errors during connection termination aren't particularly useful. + + Canceling :meth:`close` is discouraged. If it takes too long, you can + set a shorter ``close_timeout``. If you don't want to wait, let the + Python process exit, then the OS will take care of closing the TCP + connection. + + Args: + code: WebSocket close code. + reason: WebSocket close reason. + + """ + try: + async with asyncio_timeout(self.close_timeout): + await self.write_close_frame(Close(code, reason)) + except asyncio.TimeoutError: + # If the close frame cannot be sent because the send buffers + # are full, the closing handshake won't complete anyway. + # Fail the connection to shut down faster. + self.fail_connection() + + # If no close frame is received within the timeout, asyncio_timeout() + # cancels the data transfer task and raises TimeoutError. + + # If close() is called multiple times concurrently and one of these + # calls hits the timeout, the data transfer task will be canceled. + # Other calls will receive a CancelledError here. + + try: + # If close() is canceled during the wait, self.transfer_data_task + # is canceled before the timeout elapses. + async with asyncio_timeout(self.close_timeout): + await self.transfer_data_task + except (asyncio.TimeoutError, asyncio.CancelledError): + pass + + # Wait for the close connection task to close the TCP connection. + await asyncio.shield(self.close_connection_task) + + async def wait_closed(self) -> None: + """ + Wait until the connection is closed. + + This coroutine is identical to the :attr:`closed` attribute, except it + can be awaited. + + This can make it easier to detect connection termination, regardless + of its cause, in tasks that interact with the WebSocket connection. + + """ + await asyncio.shield(self.connection_lost_waiter) + + async def ping(self, data: DataLike | None = None) -> Awaitable[float]: + """ + Send a Ping_. + + .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2 + + A ping may serve as a keepalive, as a check that the remote endpoint + received all messages up to this point, or to measure :attr:`latency`. + + Canceling :meth:`ping` is discouraged. If :meth:`ping` doesn't return + immediately, it means the write buffer is full. If you don't want to + wait, you should close the connection. + + Canceling the :class:`~asyncio.Future` returned by :meth:`ping` has no + effect. + + Args: + data: Payload of the ping. A string will be encoded to UTF-8. + If ``data`` is :obj:`None`, the payload is four random bytes. + + Returns: + A future that will be completed when the corresponding pong is + received. You can ignore it if you don't intend to wait. The result + of the future is the latency of the connection in seconds. + + :: + + pong_waiter = await ws.ping() + # only if you want to wait for the corresponding pong + latency = await pong_waiter + + Raises: + ConnectionClosed: When the connection is closed. + RuntimeError: If another ping was sent with the same data and + the corresponding pong wasn't received yet. + + """ + await self.ensure_open() + + if data is not None: + data = prepare_ctrl(data) + + # Protect against duplicates if a payload is explicitly set. + if data in self.pings: + raise RuntimeError("already waiting for a pong with the same data") + + # Generate a unique random payload otherwise. + while data is None or data in self.pings: + data = struct.pack("!I", random.getrandbits(32)) + + pong_waiter = self.loop.create_future() + # Resolution of time.monotonic() may be too low on Windows. + ping_timestamp = time.perf_counter() + self.pings[data] = (pong_waiter, ping_timestamp) + + await self.write_frame(True, OP_PING, data) + + return asyncio.shield(pong_waiter) + + async def pong(self, data: DataLike = b"") -> None: + """ + Send a Pong_. + + .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3 + + An unsolicited pong may serve as a unidirectional heartbeat. + + Canceling :meth:`pong` is discouraged. If :meth:`pong` doesn't return + immediately, it means the write buffer is full. If you don't want to + wait, you should close the connection. + + Args: + data: Payload of the pong. A string will be encoded to UTF-8. + + Raises: + ConnectionClosed: When the connection is closed. + + """ + await self.ensure_open() + + data = prepare_ctrl(data) + + await self.write_frame(True, OP_PONG, data) + + # Private methods - no guarantees. + + def connection_closed_exc(self) -> ConnectionClosed: + exc: ConnectionClosed + if ( + self.close_rcvd is not None + and self.close_rcvd.code in OK_CLOSE_CODES + and self.close_sent is not None + and self.close_sent.code in OK_CLOSE_CODES + ): + exc = ConnectionClosedOK( + self.close_rcvd, + self.close_sent, + self.close_rcvd_then_sent, + ) + else: + exc = ConnectionClosedError( + self.close_rcvd, + self.close_sent, + self.close_rcvd_then_sent, + ) + # Chain to the exception that terminated data transfer, if any. + exc.__cause__ = self.transfer_data_exc + return exc + + async def ensure_open(self) -> None: + """ + Check that the WebSocket connection is open. + + Raise :exc:`~websockets.exceptions.ConnectionClosed` if it isn't. + + """ + # Handle cases from most common to least common for performance. + if self.state is State.OPEN: + # If self.transfer_data_task exited without a closing handshake, + # self.close_connection_task may be closing the connection, going + # straight from OPEN to CLOSED. + if self.transfer_data_task.done(): + await asyncio.shield(self.close_connection_task) + raise self.connection_closed_exc() + else: + return + + if self.state is State.CLOSED: + raise self.connection_closed_exc() + + if self.state is State.CLOSING: + # If we started the closing handshake, wait for its completion to + # get the proper close code and reason. self.close_connection_task + # will complete within 4 or 5 * close_timeout after close(). The + # CLOSING state also occurs when failing the connection. In that + # case self.close_connection_task will complete even faster. + await asyncio.shield(self.close_connection_task) + raise self.connection_closed_exc() + + # Control may only reach this point in buggy third-party subclasses. + assert self.state is State.CONNECTING + raise InvalidState("WebSocket connection isn't established yet") + + async def transfer_data(self) -> None: + """ + Read incoming messages and put them in a queue. + + This coroutine runs in a task until the closing handshake is started. + + """ + try: + while True: + message = await self.read_message() + + # Exit the loop when receiving a close frame. + if message is None: + break + + # Wait until there's room in the queue (if necessary). + if self.max_queue is not None: + while len(self.messages) >= self.max_queue: + self._put_message_waiter = self.loop.create_future() + try: + await asyncio.shield(self._put_message_waiter) + finally: + self._put_message_waiter = None + + # Put the message in the queue. + self.messages.append(message) + + # Notify recv(). + if self._pop_message_waiter is not None: + self._pop_message_waiter.set_result(None) + self._pop_message_waiter = None + + except asyncio.CancelledError as exc: + self.transfer_data_exc = exc + # If fail_connection() cancels this task, avoid logging the error + # twice and failing the connection again. + raise + + except ProtocolError as exc: + self.transfer_data_exc = exc + self.fail_connection(CloseCode.PROTOCOL_ERROR) + + except (ConnectionError, TimeoutError, EOFError, ssl.SSLError) as exc: + # Reading data with self.reader.readexactly may raise: + # - most subclasses of ConnectionError if the TCP connection + # breaks, is reset, or is aborted; + # - TimeoutError if the TCP connection times out; + # - IncompleteReadError, a subclass of EOFError, if fewer + # bytes are available than requested; + # - ssl.SSLError if the other side infringes the TLS protocol. + self.transfer_data_exc = exc + self.fail_connection(CloseCode.ABNORMAL_CLOSURE) + + except UnicodeDecodeError as exc: + self.transfer_data_exc = exc + self.fail_connection(CloseCode.INVALID_DATA) + + except PayloadTooBig as exc: + self.transfer_data_exc = exc + self.fail_connection(CloseCode.MESSAGE_TOO_BIG) + + except Exception as exc: + # This shouldn't happen often because exceptions expected under + # regular circumstances are handled above. If it does, consider + # catching and handling more exceptions. + self.logger.error("data transfer failed", exc_info=True) + + self.transfer_data_exc = exc + self.fail_connection(CloseCode.INTERNAL_ERROR) + + async def read_message(self) -> Data | None: + """ + Read a single message from the connection. + + Re-assemble data frames if the message is fragmented. + + Return :obj:`None` when the closing handshake is started. + + """ + frame = await self.read_data_frame(max_size=self.max_size) + + # A close frame was received. + if frame is None: + return None + + if frame.opcode == OP_TEXT: + text = True + elif frame.opcode == OP_BINARY: + text = False + else: # frame.opcode == OP_CONT + raise ProtocolError("unexpected opcode") + + # Shortcut for the common case - no fragmentation + if frame.fin: + if isinstance(frame.data, memoryview): + raise AssertionError("only compressed outgoing frames use memoryview") + return frame.data.decode() if text else bytes(frame.data) + + # 5.4. Fragmentation + fragments: list[DataLike] = [] + max_size = self.max_size + if text: + decoder_factory = codecs.getincrementaldecoder("utf-8") + decoder = decoder_factory(errors="strict") + if max_size is None: + + def append(frame: Frame) -> None: + nonlocal fragments + fragments.append(decoder.decode(frame.data, frame.fin)) + + else: + + def append(frame: Frame) -> None: + nonlocal fragments, max_size + fragments.append(decoder.decode(frame.data, frame.fin)) + assert isinstance(max_size, int) + max_size -= len(frame.data) + + else: + if max_size is None: + + def append(frame: Frame) -> None: + nonlocal fragments + fragments.append(frame.data) + + else: + + def append(frame: Frame) -> None: + nonlocal fragments, max_size + fragments.append(frame.data) + assert isinstance(max_size, int) + max_size -= len(frame.data) + + append(frame) + + while not frame.fin: + frame = await self.read_data_frame(max_size=max_size) + if frame is None: + raise ProtocolError("incomplete fragmented message") + if frame.opcode != OP_CONT: + raise ProtocolError("unexpected opcode") + append(frame) + + return ("" if text else b"").join(fragments) + + async def read_data_frame(self, max_size: int | None) -> Frame | None: + """ + Read a single data frame from the connection. + + Process control frames received before the next data frame. + + Return :obj:`None` if a close frame is encountered before any data frame. + + """ + # 6.2. Receiving Data + while True: + frame = await self.read_frame(max_size) + + # 5.5. Control Frames + if frame.opcode == OP_CLOSE: + # 7.1.5. The WebSocket Connection Close Code + # 7.1.6. The WebSocket Connection Close Reason + self.close_rcvd = Close.parse(frame.data) + if self.close_sent is not None: + self.close_rcvd_then_sent = False + try: + # Echo the original data instead of re-serializing it with + # Close.serialize() because that fails when the close frame + # is empty and Close.parse() synthesizes a 1005 close code. + await self.write_close_frame(self.close_rcvd, frame.data) + except ConnectionClosed: + # Connection closed before we could echo the close frame. + pass + return None + + elif frame.opcode == OP_PING: + # Answer pings, unless connection is CLOSING. + if self.state is State.OPEN: + try: + await self.pong(frame.data) + except ConnectionClosed: + # Connection closed while draining write buffer. + pass + + elif frame.opcode == OP_PONG: + if frame.data in self.pings: + pong_timestamp = time.perf_counter() + # Sending a pong for only the most recent ping is legal. + # Acknowledge all previous pings too in that case. + ping_id = None + ping_ids = [] + for ping_id, (pong_waiter, ping_timestamp) in self.pings.items(): + ping_ids.append(ping_id) + if not pong_waiter.done(): + pong_waiter.set_result(pong_timestamp - ping_timestamp) + if ping_id == frame.data: + self.latency = pong_timestamp - ping_timestamp + break + else: + raise AssertionError("solicited pong not found in pings") + # Remove acknowledged pings from self.pings. + for ping_id in ping_ids: + del self.pings[ping_id] + + # 5.6. Data Frames + else: + return frame + + async def read_frame(self, max_size: int | None) -> Frame: + """ + Read a single frame from the connection. + + """ + frame = await Frame.read( + self.reader.readexactly, + mask=not self.is_client, + max_size=max_size, + extensions=self.extensions, + ) + if self.debug: + self.logger.debug("< %s", frame) + return frame + + def write_frame_sync(self, fin: bool, opcode: int, data: BytesLike) -> None: + frame = Frame(fin, Opcode(opcode), data) + if self.debug: + self.logger.debug("> %s", frame) + frame.write( + self.transport.write, + mask=self.is_client, + extensions=self.extensions, + ) + + async def drain(self) -> None: + try: + # Handle flow control automatically. + await self._drain() + except ConnectionError: + # Terminate the connection if the socket died. + self.fail_connection() + # Wait until the connection is closed to raise ConnectionClosed + # with the correct code and reason. + await self.ensure_open() + + async def write_frame( + self, fin: bool, opcode: int, data: BytesLike, *, _state: int = State.OPEN + ) -> None: + # Defensive assertion for protocol compliance. + if self.state is not _state: # pragma: no cover + raise InvalidState( + f"Cannot write to a WebSocket in the {self.state.name} state" + ) + self.write_frame_sync(fin, opcode, data) + await self.drain() + + async def write_close_frame( + self, close: Close, data: BytesLike | None = None + ) -> None: + """ + Write a close frame if and only if the connection state is OPEN. + + This dedicated coroutine must be used for writing close frames to + ensure that at most one close frame is sent on a given connection. + + """ + # Test and set the connection state before sending the close frame to + # avoid sending two frames in case of concurrent calls. + if self.state is State.OPEN: + # 7.1.3. The WebSocket Closing Handshake is Started + self.state = State.CLOSING + if self.debug: + self.logger.debug("= connection is CLOSING") + + self.close_sent = close + if self.close_rcvd is not None: + self.close_rcvd_then_sent = True + if data is None: + data = close.serialize() + + # 7.1.2. Start the WebSocket Closing Handshake + await self.write_frame(True, OP_CLOSE, data, _state=State.CLOSING) + + async def keepalive_ping(self) -> None: + """ + Send a Ping frame and wait for a Pong frame at regular intervals. + + This coroutine exits when the connection terminates and one of the + following happens: + + - :meth:`ping` raises :exc:`ConnectionClosed`, or + - :meth:`close_connection` cancels :attr:`keepalive_ping_task`. + + """ + if self.ping_interval is None: + return + + try: + while True: + await asyncio.sleep(self.ping_interval) + + if self.debug: + self.logger.debug("% sending keepalive ping") + pong_waiter = await self.ping() + + if self.ping_timeout is not None: + try: + async with asyncio_timeout(self.ping_timeout): + # Raises CancelledError if the connection is closed, + # when close_connection() cancels keepalive_ping(). + # Raises ConnectionClosed if the connection is lost, + # when connection_lost() calls abort_pings(). + await pong_waiter + if self.debug: + self.logger.debug("% received keepalive pong") + except asyncio.TimeoutError: + if self.debug: + self.logger.debug("- timed out waiting for keepalive pong") + self.fail_connection( + CloseCode.INTERNAL_ERROR, + "keepalive ping timeout", + ) + break + + except ConnectionClosed: + pass + + except Exception: + self.logger.error("keepalive ping failed", exc_info=True) + + async def close_connection(self) -> None: + """ + 7.1.1. Close the WebSocket Connection + + When the opening handshake succeeds, :meth:`connection_open` starts + this coroutine in a task. It waits for the data transfer phase to + complete then it closes the TCP connection cleanly. + + When the opening handshake fails, :meth:`fail_connection` does the + same. There's no data transfer phase in that case. + + """ + try: + # Wait for the data transfer phase to complete. + if hasattr(self, "transfer_data_task"): + try: + await self.transfer_data_task + except asyncio.CancelledError: + pass + + # Cancel the keepalive ping task. + if hasattr(self, "keepalive_ping_task"): + self.keepalive_ping_task.cancel() + + # A client should wait for a TCP close from the server. + if self.is_client and hasattr(self, "transfer_data_task"): + if await self.wait_for_connection_lost(): + return + if self.debug: + self.logger.debug("- timed out waiting for TCP close") + + # Half-close the TCP connection if possible (when there's no TLS). + if self.transport.can_write_eof(): + if self.debug: + self.logger.debug("x half-closing TCP connection") + # write_eof() doesn't document which exceptions it raises. + # "[Errno 107] Transport endpoint is not connected" happens + # but it isn't completely clear under which circumstances. + # uvloop can raise RuntimeError here. + try: + self.transport.write_eof() + except (OSError, RuntimeError): # pragma: no cover + pass + + if await self.wait_for_connection_lost(): + return + if self.debug: + self.logger.debug("- timed out waiting for TCP close") + + finally: + # The try/finally ensures that the transport never remains open, + # even if this coroutine is canceled (for example). + await self.close_transport() + + async def close_transport(self) -> None: + """ + Close the TCP connection. + + """ + # If connection_lost() was called, the TCP connection is closed. + # However, if TLS is enabled, the transport still needs closing. + # Else asyncio complains: ResourceWarning: unclosed transport. + if self.connection_lost_waiter.done() and self.transport.is_closing(): + return + + # Close the TCP connection. Buffers are flushed asynchronously. + if self.debug: + self.logger.debug("x closing TCP connection") + self.transport.close() + + if await self.wait_for_connection_lost(): + return + if self.debug: + self.logger.debug("- timed out waiting for TCP close") + + # Abort the TCP connection. Buffers are discarded. + if self.debug: + self.logger.debug("x aborting TCP connection") + self.transport.abort() + + # connection_lost() is called quickly after aborting. + await self.wait_for_connection_lost() + + async def wait_for_connection_lost(self) -> bool: + """ + Wait until the TCP connection is closed or ``self.close_timeout`` elapses. + + Return :obj:`True` if the connection is closed and :obj:`False` + otherwise. + + """ + if not self.connection_lost_waiter.done(): + try: + async with asyncio_timeout(self.close_timeout): + await asyncio.shield(self.connection_lost_waiter) + except asyncio.TimeoutError: + pass + # Re-check self.connection_lost_waiter.done() synchronously because + # connection_lost() could run between the moment the timeout occurs + # and the moment this coroutine resumes running. + return self.connection_lost_waiter.done() + + def fail_connection( + self, + code: int = CloseCode.ABNORMAL_CLOSURE, + reason: str = "", + ) -> None: + """ + 7.1.7. Fail the WebSocket Connection + + This requires: + + 1. Stopping all processing of incoming data, which means canceling + :attr:`transfer_data_task`. The close code will be 1006 unless a + close frame was received earlier. + + 2. Sending a close frame with an appropriate code if the opening + handshake succeeded and the other side is likely to process it. + + 3. Closing the connection. :meth:`close_connection` takes care of + this once :attr:`transfer_data_task` exits after being canceled. + + (The specification describes these steps in the opposite order.) + + """ + if self.debug: + self.logger.debug("! failing connection with code %d", code) + + # Cancel transfer_data_task if the opening handshake succeeded. + # cancel() is idempotent and ignored if the task is done already. + if hasattr(self, "transfer_data_task"): + self.transfer_data_task.cancel() + + # Send a close frame when the state is OPEN (a close frame was already + # sent if it's CLOSING), except when failing the connection because of + # an error reading from or writing to the network. + # Don't send a close frame if the connection is broken. + if code != CloseCode.ABNORMAL_CLOSURE and self.state is State.OPEN: + close = Close(code, reason) + + # Write the close frame without draining the write buffer. + + # Keeping fail_connection() synchronous guarantees it can't + # get stuck and simplifies the implementation of the callers. + # Not drainig the write buffer is acceptable in this context. + + # This duplicates a few lines of code from write_close_frame(). + + self.state = State.CLOSING + if self.debug: + self.logger.debug("= connection is CLOSING") + + # If self.close_rcvd was set, the connection state would be + # CLOSING. Therefore self.close_rcvd isn't set and we don't + # have to set self.close_rcvd_then_sent. + assert self.close_rcvd is None + self.close_sent = close + + self.write_frame_sync(True, OP_CLOSE, close.serialize()) + + # Start close_connection_task if the opening handshake didn't succeed. + if not hasattr(self, "close_connection_task"): + self.close_connection_task = self.loop.create_task(self.close_connection()) + + def abort_pings(self) -> None: + """ + Raise ConnectionClosed in pending keepalive pings. + + They'll never receive a pong once the connection is closed. + + """ + assert self.state is State.CLOSED + exc = self.connection_closed_exc() + + for pong_waiter, _ping_timestamp in self.pings.values(): + pong_waiter.set_exception(exc) + # If the exception is never retrieved, it will be logged when ping + # is garbage-collected. This is confusing for users. + # Given that ping is done (with an exception), canceling it does + # nothing, but it prevents logging the exception. + pong_waiter.cancel() + + # asyncio.Protocol methods + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + """ + Configure write buffer limits. + + The high-water limit is defined by ``self.write_limit``. + + The low-water limit currently defaults to ``self.write_limit // 4`` in + :meth:`~asyncio.WriteTransport.set_write_buffer_limits`, which should + be all right for reasonable use cases of this library. + + This is the earliest point where we can get hold of the transport, + which means it's the best point for configuring it. + + """ + transport = cast(asyncio.Transport, transport) + transport.set_write_buffer_limits(self.write_limit) + self.transport = transport + + # Copied from asyncio.StreamReaderProtocol + self.reader.set_transport(transport) + + def connection_lost(self, exc: Exception | None) -> None: + """ + 7.1.4. The WebSocket Connection is Closed. + + """ + self.state = State.CLOSED + if self.debug: + self.logger.debug("= connection is CLOSED") + + self.abort_pings() + + # If self.connection_lost_waiter isn't pending, that's a bug, because: + # - it's set only here in connection_lost() which is called only once; + # - it must never be canceled. + self.connection_lost_waiter.set_result(None) + + if True: # pragma: no cover + # Copied from asyncio.StreamReaderProtocol + if self.reader is not None: + if exc is None: + self.reader.feed_eof() + else: + self.reader.set_exception(exc) + + # Copied from asyncio.FlowControlMixin + # Wake up the writer if currently paused. + if not self._paused: + return + waiter = self._drain_waiter + if waiter is None: + return + self._drain_waiter = None + if waiter.done(): + return + if exc is None: + waiter.set_result(None) + else: + waiter.set_exception(exc) + + def pause_writing(self) -> None: # pragma: no cover + assert not self._paused + self._paused = True + + def resume_writing(self) -> None: # pragma: no cover + assert self._paused + self._paused = False + + waiter = self._drain_waiter + if waiter is not None: + self._drain_waiter = None + if not waiter.done(): + waiter.set_result(None) + + def data_received(self, data: bytes) -> None: + self.reader.feed_data(data) + + def eof_received(self) -> None: + """ + Close the transport after receiving EOF. + + The WebSocket protocol has its own closing handshake: endpoints close + the TCP or TLS connection after sending and receiving a close frame. + + As a consequence, they never need to write after receiving EOF, so + there's no reason to keep the transport open by returning :obj:`True`. + + Besides, that doesn't work on TLS connections. + + """ + self.reader.feed_eof() + + +# broadcast() is defined in the protocol module even though it's primarily +# used by servers and documented in the server module because it works with +# client connections too and because it's easier to test together with the +# WebSocketCommonProtocol class. + + +def broadcast( + websockets: Iterable[WebSocketCommonProtocol], + message: DataLike, + raise_exceptions: bool = False, +) -> None: + """ + Broadcast a message to several WebSocket connections. + + A string (:class:`str`) is sent as a Text_ frame. A bytestring or bytes-like + object (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) is sent + as a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + :func:`broadcast` pushes the message synchronously to all connections even + if their write buffers are overflowing. There's no backpressure. + + If you broadcast messages faster than a connection can handle them, messages + will pile up in its write buffer until the connection times out. Keep + ``ping_interval`` and ``ping_timeout`` low to prevent excessive memory usage + from slow connections. + + Unlike :meth:`~websockets.legacy.protocol.WebSocketCommonProtocol.send`, + :func:`broadcast` doesn't support sending fragmented messages. Indeed, + fragmentation is useful for sending large messages without buffering them in + memory, while :func:`broadcast` buffers one copy per connection as fast as + possible. + + :func:`broadcast` skips connections that aren't open in order to avoid + errors on connections where the closing handshake is in progress. + + :func:`broadcast` ignores failures to write the message on some connections. + It continues writing to other connections. On Python 3.11 and above, you may + set ``raise_exceptions`` to :obj:`True` to record failures and raise all + exceptions in a :pep:`654` :exc:`ExceptionGroup`. + + While :func:`broadcast` makes more sense for servers, it works identically + with clients, if you have a use case for opening connections to many servers + and broadcasting a message to them. + + Args: + websockets: WebSocket connections to which the message will be sent. + message: Message to send. + raise_exceptions: Whether to raise an exception in case of failures. + + Raises: + TypeError: If ``message`` doesn't have a supported type. + + """ + if not isinstance(message, (str, bytes, bytearray, memoryview)): + raise TypeError("data must be str or bytes-like") + + if raise_exceptions: + if sys.version_info[:2] < (3, 11): # pragma: no cover + raise ValueError("raise_exceptions requires at least Python 3.11") + exceptions = [] + + opcode, data = prepare_data(message) + + for websocket in websockets: + if websocket.state is not State.OPEN: + continue + + if websocket._fragmented_message_waiter is not None: + if raise_exceptions: + exception = RuntimeError("sending a fragmented message") + exceptions.append(exception) + else: + websocket.logger.warning( + "skipped broadcast: sending a fragmented message", + ) + continue + + try: + websocket.write_frame_sync(True, opcode, data) + except Exception as write_exception: + if raise_exceptions: + exception = RuntimeError("failed to write message") + exception.__cause__ = write_exception + exceptions.append(exception) + else: + websocket.logger.warning( + "skipped broadcast: failed to write message: %s", + traceback.format_exception_only(write_exception)[0].strip(), + ) + + if raise_exceptions and exceptions: + raise ExceptionGroup("skipped broadcast", exceptions) + + +# Pretend that broadcast is actually defined in the server module. +broadcast.__module__ = "websockets.legacy.server" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/server.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/server.py new file mode 100644 index 0000000000000000000000000000000000000000..9f5feaca8514b84432d9b05e064012ac0ebee357 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/legacy/server.py @@ -0,0 +1,1191 @@ +from __future__ import annotations + +import asyncio +import email.utils +import functools +import http +import inspect +import logging +import socket +import warnings +from collections.abc import Awaitable, Generator, Iterable, Sequence +from types import TracebackType +from typing import Any, Callable, cast + +from ..asyncio.compatibility import asyncio_timeout +from ..datastructures import Headers, HeadersLike, MultipleValuesError +from ..exceptions import ( + InvalidHandshake, + InvalidHeader, + InvalidMessage, + InvalidOrigin, + InvalidUpgrade, + NegotiationError, +) +from ..extensions import Extension, ServerExtensionFactory +from ..extensions.permessage_deflate import enable_server_permessage_deflate +from ..headers import ( + build_extension, + parse_extension, + parse_subprotocol, + validate_subprotocols, +) +from ..http11 import SERVER +from ..protocol import State +from ..typing import ExtensionHeader, LoggerLike, Origin, StatusLike, Subprotocol +from .exceptions import AbortHandshake +from .handshake import build_response, check_request +from .http import read_request +from .protocol import WebSocketCommonProtocol, broadcast + + +__all__ = [ + "broadcast", + "serve", + "unix_serve", + "WebSocketServerProtocol", + "WebSocketServer", +] + + +HeadersLikeOrCallable = HeadersLike | Callable[[str, Headers], HeadersLike] + +HTTPResponse = tuple[StatusLike, HeadersLike, bytes] + + +class WebSocketServerProtocol(WebSocketCommonProtocol): + """ + WebSocket server connection. + + :class:`WebSocketServerProtocol` provides :meth:`recv` and :meth:`send` + coroutines for receiving and sending messages. + + It supports asynchronous iteration to receive messages:: + + async for message in websocket: + await process(message) + + The iterator exits normally when the connection is closed with close code + 1000 (OK) or 1001 (going away) or without a close code. It raises + a :exc:`~websockets.exceptions.ConnectionClosedError` when the connection + is closed with any other code. + + You may customize the opening handshake in a subclass by + overriding :meth:`process_request` or :meth:`select_subprotocol`. + + Args: + ws_server: WebSocket server that created this connection. + + See :func:`serve` for the documentation of ``ws_handler``, ``logger``, ``origins``, + ``extensions``, ``subprotocols``, ``extra_headers``, and ``server_header``. + + See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the + documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``, + ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``. + + """ + + is_client = False + side = "server" + + def __init__( + self, + # The version that accepts the path in the second argument is deprecated. + ws_handler: ( + Callable[[WebSocketServerProtocol], Awaitable[Any]] + | Callable[[WebSocketServerProtocol, str], Awaitable[Any]] + ), + ws_server: WebSocketServer, + *, + logger: LoggerLike | None = None, + origins: Sequence[Origin | None] | None = None, + extensions: Sequence[ServerExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + extra_headers: HeadersLikeOrCallable | None = None, + server_header: str | None = SERVER, + process_request: ( + Callable[[str, Headers], Awaitable[HTTPResponse | None]] | None + ) = None, + select_subprotocol: ( + Callable[[Sequence[Subprotocol], Sequence[Subprotocol]], Subprotocol] | None + ) = None, + open_timeout: float | None = 10, + **kwargs: Any, + ) -> None: + if logger is None: + logger = logging.getLogger("websockets.server") + super().__init__(logger=logger, **kwargs) + # For backwards compatibility with 6.0 or earlier. + if origins is not None and "" in origins: + warnings.warn("use None instead of '' in origins", DeprecationWarning) + origins = [None if origin == "" else origin for origin in origins] + # For backwards compatibility with 10.0 or earlier. Done here in + # addition to serve to trigger the deprecation warning on direct + # use of WebSocketServerProtocol. + self.ws_handler = remove_path_argument(ws_handler) + self.ws_server = ws_server + self.origins = origins + self.available_extensions = extensions + self.available_subprotocols = subprotocols + self.extra_headers = extra_headers + self.server_header = server_header + self._process_request = process_request + self._select_subprotocol = select_subprotocol + self.open_timeout = open_timeout + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + """ + Register connection and initialize a task to handle it. + + """ + super().connection_made(transport) + # Register the connection with the server before creating the handler + # task. Registering at the beginning of the handler coroutine would + # create a race condition between the creation of the task, which + # schedules its execution, and the moment the handler starts running. + self.ws_server.register(self) + self.handler_task = self.loop.create_task(self.handler()) + + async def handler(self) -> None: + """ + Handle the lifecycle of a WebSocket connection. + + Since this method doesn't have a caller able to handle exceptions, it + attempts to log relevant ones and guarantees that the TCP connection is + closed before exiting. + + """ + try: + try: + async with asyncio_timeout(self.open_timeout): + await self.handshake( + origins=self.origins, + available_extensions=self.available_extensions, + available_subprotocols=self.available_subprotocols, + extra_headers=self.extra_headers, + ) + except asyncio.TimeoutError: # pragma: no cover + raise + except ConnectionError: + raise + except Exception as exc: + if isinstance(exc, AbortHandshake): + status, headers, body = exc.status, exc.headers, exc.body + elif isinstance(exc, InvalidOrigin): + if self.debug: + self.logger.debug("! invalid origin", exc_info=True) + status, headers, body = ( + http.HTTPStatus.FORBIDDEN, + Headers(), + f"Failed to open a WebSocket connection: {exc}.\n".encode(), + ) + elif isinstance(exc, InvalidUpgrade): + if self.debug: + self.logger.debug("! invalid upgrade", exc_info=True) + status, headers, body = ( + http.HTTPStatus.UPGRADE_REQUIRED, + Headers([("Upgrade", "websocket")]), + ( + f"Failed to open a WebSocket connection: {exc}.\n" + f"\n" + f"You cannot access a WebSocket server directly " + f"with a browser. You need a WebSocket client.\n" + ).encode(), + ) + elif isinstance(exc, InvalidHandshake): + if self.debug: + self.logger.debug("! invalid handshake", exc_info=True) + exc_chain = cast(BaseException, exc) + exc_str = f"{exc_chain}" + while exc_chain.__cause__ is not None: + exc_chain = exc_chain.__cause__ + exc_str += f"; {exc_chain}" + status, headers, body = ( + http.HTTPStatus.BAD_REQUEST, + Headers(), + f"Failed to open a WebSocket connection: {exc_str}.\n".encode(), + ) + else: + self.logger.error("opening handshake failed", exc_info=True) + status, headers, body = ( + http.HTTPStatus.INTERNAL_SERVER_ERROR, + Headers(), + ( + b"Failed to open a WebSocket connection.\n" + b"See server log for more information.\n" + ), + ) + + headers.setdefault("Date", email.utils.formatdate(usegmt=True)) + if self.server_header: + headers.setdefault("Server", self.server_header) + + headers.setdefault("Content-Length", str(len(body))) + headers.setdefault("Content-Type", "text/plain") + headers.setdefault("Connection", "close") + + self.write_http_response(status, headers, body) + self.logger.info( + "connection rejected (%d %s)", status.value, status.phrase + ) + await self.close_transport() + return + + try: + await self.ws_handler(self) + except Exception: + self.logger.error("connection handler failed", exc_info=True) + if not self.closed: + self.fail_connection(1011) + raise + + try: + await self.close() + except ConnectionError: + raise + except Exception: + self.logger.error("closing handshake failed", exc_info=True) + raise + + except Exception: + # Last-ditch attempt to avoid leaking connections on errors. + try: + self.transport.close() + except Exception: # pragma: no cover + pass + + finally: + # Unregister the connection with the server when the handler task + # terminates. Registration is tied to the lifecycle of the handler + # task because the server waits for tasks attached to registered + # connections before terminating. + self.ws_server.unregister(self) + self.logger.info("connection closed") + + async def read_http_request(self) -> tuple[str, Headers]: + """ + Read request line and headers from the HTTP request. + + If the request contains a body, it may be read from ``self.reader`` + after this coroutine returns. + + Raises: + InvalidMessage: If the HTTP message is malformed or isn't an + HTTP/1.1 GET request. + + """ + try: + path, headers = await read_request(self.reader) + except asyncio.CancelledError: # pragma: no cover + raise + except Exception as exc: + raise InvalidMessage("did not receive a valid HTTP request") from exc + + if self.debug: + self.logger.debug("< GET %s HTTP/1.1", path) + for key, value in headers.raw_items(): + self.logger.debug("< %s: %s", key, value) + + self.path = path + self.request_headers = headers + + return path, headers + + def write_http_response( + self, status: http.HTTPStatus, headers: Headers, body: bytes | None = None + ) -> None: + """ + Write status line and headers to the HTTP response. + + This coroutine is also able to write a response body. + + """ + self.response_headers = headers + + if self.debug: + self.logger.debug("> HTTP/1.1 %d %s", status.value, status.phrase) + for key, value in headers.raw_items(): + self.logger.debug("> %s: %s", key, value) + if body is not None: + self.logger.debug("> [body] (%d bytes)", len(body)) + + # Since the status line and headers only contain ASCII characters, + # we can keep this simple. + response = f"HTTP/1.1 {status.value} {status.phrase}\r\n" + response += str(headers) + + self.transport.write(response.encode()) + + if body is not None: + self.transport.write(body) + + async def process_request( + self, path: str, request_headers: Headers + ) -> HTTPResponse | None: + """ + Intercept the HTTP request and return an HTTP response if appropriate. + + You may override this method in a :class:`WebSocketServerProtocol` + subclass, for example: + + * to return an HTTP 200 OK response on a given path; then a load + balancer can use this path for a health check; + * to authenticate the request and return an HTTP 401 Unauthorized or an + HTTP 403 Forbidden when authentication fails. + + You may also override this method with the ``process_request`` + argument of :func:`serve` and :class:`WebSocketServerProtocol`. This + is equivalent, except ``process_request`` won't have access to the + protocol instance, so it can't store information for later use. + + :meth:`process_request` is expected to complete quickly. If it may run + for a long time, then it should await :meth:`wait_closed` and exit if + :meth:`wait_closed` completes, or else it could prevent the server + from shutting down. + + Args: + path: Request path, including optional query string. + request_headers: Request headers. + + Returns: + tuple[StatusLike, HeadersLike, bytes] | None: :obj:`None` to + continue the WebSocket handshake normally. + + An HTTP response, represented by a 3-uple of the response status, + headers, and body, to abort the WebSocket handshake and return + that HTTP response instead. + + """ + if self._process_request is not None: + response = self._process_request(path, request_headers) + if isinstance(response, Awaitable): + return await response + else: + # For backwards compatibility with 7.0. + warnings.warn( + "declare process_request as a coroutine", DeprecationWarning + ) + return response + return None + + @staticmethod + def process_origin( + headers: Headers, origins: Sequence[Origin | None] | None = None + ) -> Origin | None: + """ + Handle the Origin HTTP request header. + + Args: + headers: Request headers. + origins: Optional list of acceptable origins. + + Raises: + InvalidOrigin: If the origin isn't acceptable. + + """ + # "The user agent MUST NOT include more than one Origin header field" + # per https://datatracker.ietf.org/doc/html/rfc6454#section-7.3. + try: + origin = headers.get("Origin") + except MultipleValuesError as exc: + raise InvalidHeader("Origin", "multiple values") from exc + if origin is not None: + origin = cast(Origin, origin) + if origins is not None: + if origin not in origins: + raise InvalidOrigin(origin) + return origin + + @staticmethod + def process_extensions( + headers: Headers, + available_extensions: Sequence[ServerExtensionFactory] | None, + ) -> tuple[str | None, list[Extension]]: + """ + Handle the Sec-WebSocket-Extensions HTTP request header. + + Accept or reject each extension proposed in the client request. + Negotiate parameters for accepted extensions. + + Return the Sec-WebSocket-Extensions HTTP response header and the list + of accepted extensions. + + :rfc:`6455` leaves the rules up to the specification of each + :extension. + + To provide this level of flexibility, for each extension proposed by + the client, we check for a match with each extension available in the + server configuration. If no match is found, the extension is ignored. + + If several variants of the same extension are proposed by the client, + it may be accepted several times, which won't make sense in general. + Extensions must implement their own requirements. For this purpose, + the list of previously accepted extensions is provided. + + This process doesn't allow the server to reorder extensions. It can + only select a subset of the extensions proposed by the client. + + Other requirements, for example related to mandatory extensions or the + order of extensions, may be implemented by overriding this method. + + Args: + headers: Request headers. + extensions: Optional list of supported extensions. + + Raises: + InvalidHandshake: To abort the handshake with an HTTP 400 error. + + """ + response_header_value: str | None = None + + extension_headers: list[ExtensionHeader] = [] + accepted_extensions: list[Extension] = [] + + header_values = headers.get_all("Sec-WebSocket-Extensions") + + if header_values and available_extensions: + parsed_header_values: list[ExtensionHeader] = sum( + [parse_extension(header_value) for header_value in header_values], [] + ) + + for name, request_params in parsed_header_values: + for ext_factory in available_extensions: + # Skip non-matching extensions based on their name. + if ext_factory.name != name: + continue + + # Skip non-matching extensions based on their params. + try: + response_params, extension = ext_factory.process_request_params( + request_params, accepted_extensions + ) + except NegotiationError: + continue + + # Add matching extension to the final list. + extension_headers.append((name, response_params)) + accepted_extensions.append(extension) + + # Break out of the loop once we have a match. + break + + # If we didn't break from the loop, no extension in our list + # matched what the client sent. The extension is declined. + + # Serialize extension header. + if extension_headers: + response_header_value = build_extension(extension_headers) + + return response_header_value, accepted_extensions + + # Not @staticmethod because it calls self.select_subprotocol() + def process_subprotocol( + self, headers: Headers, available_subprotocols: Sequence[Subprotocol] | None + ) -> Subprotocol | None: + """ + Handle the Sec-WebSocket-Protocol HTTP request header. + + Return Sec-WebSocket-Protocol HTTP response header, which is the same + as the selected subprotocol. + + Args: + headers: Request headers. + available_subprotocols: Optional list of supported subprotocols. + + Raises: + InvalidHandshake: To abort the handshake with an HTTP 400 error. + + """ + subprotocol: Subprotocol | None = None + + header_values = headers.get_all("Sec-WebSocket-Protocol") + + if header_values and available_subprotocols: + parsed_header_values: list[Subprotocol] = sum( + [parse_subprotocol(header_value) for header_value in header_values], [] + ) + + subprotocol = self.select_subprotocol( + parsed_header_values, available_subprotocols + ) + + return subprotocol + + def select_subprotocol( + self, + client_subprotocols: Sequence[Subprotocol], + server_subprotocols: Sequence[Subprotocol], + ) -> Subprotocol | None: + """ + Pick a subprotocol among those supported by the client and the server. + + If several subprotocols are available, select the preferred subprotocol + by giving equal weight to the preferences of the client and the server. + + If no subprotocol is available, proceed without a subprotocol. + + You may provide a ``select_subprotocol`` argument to :func:`serve` or + :class:`WebSocketServerProtocol` to override this logic. For example, + you could reject the handshake if the client doesn't support a + particular subprotocol, rather than accept the handshake without that + subprotocol. + + Args: + client_subprotocols: List of subprotocols offered by the client. + server_subprotocols: List of subprotocols available on the server. + + Returns: + Selected subprotocol, if a common subprotocol was found. + + :obj:`None` to continue without a subprotocol. + + """ + if self._select_subprotocol is not None: + return self._select_subprotocol(client_subprotocols, server_subprotocols) + + subprotocols = set(client_subprotocols) & set(server_subprotocols) + if not subprotocols: + return None + return sorted( + subprotocols, + key=lambda p: client_subprotocols.index(p) + server_subprotocols.index(p), + )[0] + + async def handshake( + self, + origins: Sequence[Origin | None] | None = None, + available_extensions: Sequence[ServerExtensionFactory] | None = None, + available_subprotocols: Sequence[Subprotocol] | None = None, + extra_headers: HeadersLikeOrCallable | None = None, + ) -> str: + """ + Perform the server side of the opening handshake. + + Args: + origins: List of acceptable values of the Origin HTTP header; + include :obj:`None` if the lack of an origin is acceptable. + extensions: List of supported extensions, in order in which they + should be tried. + subprotocols: List of supported subprotocols, in order of + decreasing preference. + extra_headers: Arbitrary HTTP headers to add to the response when + the handshake succeeds. + + Returns: + path of the URI of the request. + + Raises: + InvalidHandshake: If the handshake fails. + + """ + path, request_headers = await self.read_http_request() + + # Hook for customizing request handling, for example checking + # authentication or treating some paths as plain HTTP endpoints. + early_response_awaitable = self.process_request(path, request_headers) + if isinstance(early_response_awaitable, Awaitable): + early_response = await early_response_awaitable + else: + # For backwards compatibility with 7.0. + warnings.warn("declare process_request as a coroutine", DeprecationWarning) + early_response = early_response_awaitable + + # The connection may drop while process_request is running. + if self.state is State.CLOSED: + # This subclass of ConnectionError is silently ignored in handler(). + raise BrokenPipeError("connection closed during opening handshake") + + # Change the response to a 503 error if the server is shutting down. + if not self.ws_server.is_serving(): + early_response = ( + http.HTTPStatus.SERVICE_UNAVAILABLE, + [], + b"Server is shutting down.\n", + ) + + if early_response is not None: + raise AbortHandshake(*early_response) + + key = check_request(request_headers) + + self.origin = self.process_origin(request_headers, origins) + + extensions_header, self.extensions = self.process_extensions( + request_headers, available_extensions + ) + + protocol_header = self.subprotocol = self.process_subprotocol( + request_headers, available_subprotocols + ) + + response_headers = Headers() + + build_response(response_headers, key) + + if extensions_header is not None: + response_headers["Sec-WebSocket-Extensions"] = extensions_header + + if protocol_header is not None: + response_headers["Sec-WebSocket-Protocol"] = protocol_header + + if callable(extra_headers): + extra_headers = extra_headers(path, self.request_headers) + if extra_headers is not None: + response_headers.update(extra_headers) + + response_headers.setdefault("Date", email.utils.formatdate(usegmt=True)) + if self.server_header is not None: + response_headers.setdefault("Server", self.server_header) + + self.write_http_response(http.HTTPStatus.SWITCHING_PROTOCOLS, response_headers) + + self.logger.info("connection open") + + self.connection_open() + + return path + + +class WebSocketServer: + """ + WebSocket server returned by :func:`serve`. + + This class mirrors the API of :class:`~asyncio.Server`. + + It keeps track of WebSocket connections in order to close them properly + when shutting down. + + Args: + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.server")``. + See the :doc:`logging guide <../../topics/logging>` for details. + + """ + + def __init__(self, logger: LoggerLike | None = None) -> None: + if logger is None: + logger = logging.getLogger("websockets.server") + self.logger = logger + + # Keep track of active connections. + self.websockets: set[WebSocketServerProtocol] = set() + + # Task responsible for closing the server and terminating connections. + self.close_task: asyncio.Task[None] | None = None + + # Completed when the server is closed and connections are terminated. + self.closed_waiter: asyncio.Future[None] + + def wrap(self, server: asyncio.base_events.Server) -> None: + """ + Attach to a given :class:`~asyncio.Server`. + + Since :meth:`~asyncio.loop.create_server` doesn't support injecting a + custom ``Server`` class, the easiest solution that doesn't rely on + private :mod:`asyncio` APIs is to: + + - instantiate a :class:`WebSocketServer` + - give the protocol factory a reference to that instance + - call :meth:`~asyncio.loop.create_server` with the factory + - attach the resulting :class:`~asyncio.Server` with this method + + """ + self.server = server + for sock in server.sockets: + if sock.family == socket.AF_INET: + name = "%s:%d" % sock.getsockname() + elif sock.family == socket.AF_INET6: + name = "[%s]:%d" % sock.getsockname()[:2] + elif sock.family == socket.AF_UNIX: + name = sock.getsockname() + # In the unlikely event that someone runs websockets over a + # protocol other than IP or Unix sockets, avoid crashing. + else: # pragma: no cover + name = str(sock.getsockname()) + self.logger.info("server listening on %s", name) + + # Initialized here because we need a reference to the event loop. + # This could be moved back to __init__ now that Python < 3.10 isn't + # supported anymore, but I'm not taking that risk in legacy code. + self.closed_waiter = server.get_loop().create_future() + + def register(self, protocol: WebSocketServerProtocol) -> None: + """ + Register a connection with this server. + + """ + self.websockets.add(protocol) + + def unregister(self, protocol: WebSocketServerProtocol) -> None: + """ + Unregister a connection with this server. + + """ + self.websockets.remove(protocol) + + def close(self, close_connections: bool = True) -> None: + """ + Close the server. + + * Close the underlying :class:`~asyncio.Server`. + * When ``close_connections`` is :obj:`True`, which is the default, + close existing connections. Specifically: + + * Reject opening WebSocket connections with an HTTP 503 (service + unavailable) error. This happens when the server accepted the TCP + connection but didn't complete the opening handshake before closing. + * Close open WebSocket connections with close code 1001 (going away). + + * Wait until all connection handlers terminate. + + :meth:`close` is idempotent. + + """ + if self.close_task is None: + self.close_task = self.get_loop().create_task( + self._close(close_connections) + ) + + async def _close(self, close_connections: bool) -> None: + """ + Implementation of :meth:`close`. + + This calls :meth:`~asyncio.Server.close` on the underlying + :class:`~asyncio.Server` object to stop accepting new connections and + then closes open connections with close code 1001. + + """ + self.logger.info("server closing") + + # Stop accepting new connections. + self.server.close() + + # Wait until all accepted connections reach connection_made() and call + # register(). See https://github.com/python/cpython/issues/79033 for + # details. This workaround can be removed when dropping Python < 3.11. + await asyncio.sleep(0) + + if close_connections: + # Close OPEN connections with close code 1001. After server.close(), + # handshake() closes OPENING connections with an HTTP 503 error. + close_tasks = [ + asyncio.create_task(websocket.close(1001)) + for websocket in self.websockets + if websocket.state is not State.CONNECTING + ] + # asyncio.wait doesn't accept an empty first argument. + if close_tasks: + await asyncio.wait(close_tasks) + + # Wait until all TCP connections are closed. + await self.server.wait_closed() + + # Wait until all connection handlers terminate. + # asyncio.wait doesn't accept an empty first argument. + if self.websockets: + await asyncio.wait( + [websocket.handler_task for websocket in self.websockets] + ) + + # Tell wait_closed() to return. + self.closed_waiter.set_result(None) + + self.logger.info("server closed") + + async def wait_closed(self) -> None: + """ + Wait until the server is closed. + + When :meth:`wait_closed` returns, all TCP connections are closed and + all connection handlers have returned. + + To ensure a fast shutdown, a connection handler should always be + awaiting at least one of: + + * :meth:`~WebSocketServerProtocol.recv`: when the connection is closed, + it raises :exc:`~websockets.exceptions.ConnectionClosedOK`; + * :meth:`~WebSocketServerProtocol.wait_closed`: when the connection is + closed, it returns. + + Then the connection handler is immediately notified of the shutdown; + it can clean up and exit. + + """ + await asyncio.shield(self.closed_waiter) + + def get_loop(self) -> asyncio.AbstractEventLoop: + """ + See :meth:`asyncio.Server.get_loop`. + + """ + return self.server.get_loop() + + def is_serving(self) -> bool: + """ + See :meth:`asyncio.Server.is_serving`. + + """ + return self.server.is_serving() + + async def start_serving(self) -> None: # pragma: no cover + """ + See :meth:`asyncio.Server.start_serving`. + + Typical use:: + + server = await serve(..., start_serving=False) + # perform additional setup here... + # ... then start the server + await server.start_serving() + + """ + await self.server.start_serving() + + async def serve_forever(self) -> None: # pragma: no cover + """ + See :meth:`asyncio.Server.serve_forever`. + + Typical use:: + + server = await serve(...) + # this coroutine doesn't return + # canceling it stops the server + await server.serve_forever() + + This is an alternative to using :func:`serve` as an asynchronous context + manager. Shutdown is triggered by canceling :meth:`serve_forever` + instead of exiting a :func:`serve` context. + + """ + await self.server.serve_forever() + + @property + def sockets(self) -> Iterable[socket.socket]: + """ + See :attr:`asyncio.Server.sockets`. + + """ + return self.server.sockets + + async def __aenter__(self) -> WebSocketServer: # pragma: no cover + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: # pragma: no cover + self.close() + await self.wait_closed() + + +class Serve: + """ + Start a WebSocket server listening on ``host`` and ``port``. + + Whenever a client connects, the server creates a + :class:`WebSocketServerProtocol`, performs the opening handshake, and + delegates to the connection handler, ``ws_handler``. + + The handler receives the :class:`WebSocketServerProtocol` and uses it to + send and receive messages. + + Once the handler completes, either normally or with an exception, the + server performs the closing handshake and closes the connection. + + Awaiting :func:`serve` yields a :class:`WebSocketServer`. This object + provides a :meth:`~WebSocketServer.close` method to shut down the server:: + + # set this future to exit the server + stop = asyncio.get_running_loop().create_future() + + server = await serve(...) + await stop + server.close() + await server.wait_closed() + + :func:`serve` can be used as an asynchronous context manager. Then, the + server is shut down automatically when exiting the context:: + + # set this future to exit the server + stop = asyncio.get_running_loop().create_future() + + async with serve(...): + await stop + + Args: + ws_handler: Connection handler. It receives the WebSocket connection, + which is a :class:`WebSocketServerProtocol`, in argument. + host: Network interfaces the server binds to. + See :meth:`~asyncio.loop.create_server` for details. + port: TCP port the server listens on. + See :meth:`~asyncio.loop.create_server` for details. + create_protocol: Factory for the :class:`asyncio.Protocol` managing + the connection. It defaults to :class:`WebSocketServerProtocol`. + Set it to a wrapper or a subclass to customize connection handling. + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.server")``. + See the :doc:`logging guide <../../topics/logging>` for details. + compression: The "permessage-deflate" extension is enabled by default. + Set ``compression`` to :obj:`None` to disable it. See the + :doc:`compression guide <../../topics/compression>` for details. + origins: Acceptable values of the ``Origin`` header, for defending + against Cross-Site WebSocket Hijacking attacks. Include :obj:`None` + in the list if the lack of an origin is acceptable. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + extra_headers (HeadersLike | Callable[[str, Headers] | HeadersLike]): + Arbitrary HTTP headers to add to the response. This can be + a :data:`~websockets.datastructures.HeadersLike` or a callable + taking the request path and headers in arguments and returning + a :data:`~websockets.datastructures.HeadersLike`. + server_header: Value of the ``Server`` response header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. + Setting it to :obj:`None` removes the header. + process_request (Callable[[str, Headers], \ + Awaitable[tuple[StatusLike, HeadersLike, bytes] | None]] | None): + Intercept HTTP request before the opening handshake. + See :meth:`~WebSocketServerProtocol.process_request` for details. + select_subprotocol: Select a subprotocol supported by the client. + See :meth:`~WebSocketServerProtocol.select_subprotocol` for details. + open_timeout: Timeout for opening connections in seconds. + :obj:`None` disables the timeout. + + See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the + documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``, + ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``. + + Any other keyword arguments are passed the event loop's + :meth:`~asyncio.loop.create_server` method. + + For example: + + * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enable TLS. + + * You can set ``sock`` to a :obj:`~socket.socket` that you created + outside of websockets. + + Returns: + WebSocket server. + + """ + + def __init__( + self, + # The version that accepts the path in the second argument is deprecated. + ws_handler: ( + Callable[[WebSocketServerProtocol], Awaitable[Any]] + | Callable[[WebSocketServerProtocol, str], Awaitable[Any]] + ), + host: str | Sequence[str] | None = None, + port: int | None = None, + *, + create_protocol: Callable[..., WebSocketServerProtocol] | None = None, + logger: LoggerLike | None = None, + compression: str | None = "deflate", + origins: Sequence[Origin | None] | None = None, + extensions: Sequence[ServerExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + extra_headers: HeadersLikeOrCallable | None = None, + server_header: str | None = SERVER, + process_request: ( + Callable[[str, Headers], Awaitable[HTTPResponse | None]] | None + ) = None, + select_subprotocol: ( + Callable[[Sequence[Subprotocol], Sequence[Subprotocol]], Subprotocol] | None + ) = None, + open_timeout: float | None = 10, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = None, + max_size: int | None = 2**20, + max_queue: int | None = 2**5, + read_limit: int = 2**16, + write_limit: int = 2**16, + **kwargs: Any, + ) -> None: + # Backwards compatibility: close_timeout used to be called timeout. + timeout: float | None = kwargs.pop("timeout", None) + if timeout is None: + timeout = 10 + else: + warnings.warn("rename timeout to close_timeout", DeprecationWarning) + # If both are specified, timeout is ignored. + if close_timeout is None: + close_timeout = timeout + + # Backwards compatibility: create_protocol used to be called klass. + klass: type[WebSocketServerProtocol] | None = kwargs.pop("klass", None) + if klass is None: + klass = WebSocketServerProtocol + else: + warnings.warn("rename klass to create_protocol", DeprecationWarning) + # If both are specified, klass is ignored. + if create_protocol is None: + create_protocol = klass + + # Backwards compatibility: recv() used to return None on closed connections + legacy_recv: bool = kwargs.pop("legacy_recv", False) + + # Backwards compatibility: the loop parameter used to be supported. + _loop: asyncio.AbstractEventLoop | None = kwargs.pop("loop", None) + if _loop is None: + loop = asyncio.get_event_loop() + else: + loop = _loop + warnings.warn("remove loop argument", DeprecationWarning) + + ws_server = WebSocketServer(logger=logger) + + secure = kwargs.get("ssl") is not None + + if compression == "deflate": + extensions = enable_server_permessage_deflate(extensions) + elif compression is not None: + raise ValueError(f"unsupported compression: {compression}") + + if subprotocols is not None: + validate_subprotocols(subprotocols) + + # Help mypy and avoid this error: "type[WebSocketServerProtocol] | + # Callable[..., WebSocketServerProtocol]" not callable [misc] + create_protocol = cast(Callable[..., WebSocketServerProtocol], create_protocol) + factory = functools.partial( + create_protocol, + # For backwards compatibility with 10.0 or earlier. Done here in + # addition to WebSocketServerProtocol to trigger the deprecation + # warning once per serve() call rather than once per connection. + remove_path_argument(ws_handler), + ws_server, + host=host, + port=port, + secure=secure, + open_timeout=open_timeout, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_size=max_size, + max_queue=max_queue, + read_limit=read_limit, + write_limit=write_limit, + loop=_loop, + legacy_recv=legacy_recv, + origins=origins, + extensions=extensions, + subprotocols=subprotocols, + extra_headers=extra_headers, + server_header=server_header, + process_request=process_request, + select_subprotocol=select_subprotocol, + logger=logger, + ) + + if kwargs.pop("unix", False): + path: str | None = kwargs.pop("path", None) + # unix_serve(path) must not specify host and port parameters. + assert host is None and port is None + create_server = functools.partial( + loop.create_unix_server, factory, path, **kwargs + ) + else: + create_server = functools.partial( + loop.create_server, factory, host, port, **kwargs + ) + + # This is a coroutine function. + self._create_server = create_server + self.ws_server = ws_server + + # async with serve(...) + + async def __aenter__(self) -> WebSocketServer: + return await self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + self.ws_server.close() + await self.ws_server.wait_closed() + + # await serve(...) + + def __await__(self) -> Generator[Any, None, WebSocketServer]: + # Create a suitable iterator by calling __await__ on a coroutine. + return self.__await_impl__().__await__() + + async def __await_impl__(self) -> WebSocketServer: + server = await self._create_server() + self.ws_server.wrap(server) + return self.ws_server + + # yield from serve(...) - remove when dropping Python < 3.11 + + __iter__ = __await__ + + +serve = Serve + + +def unix_serve( + # The version that accepts the path in the second argument is deprecated. + ws_handler: ( + Callable[[WebSocketServerProtocol], Awaitable[Any]] + | Callable[[WebSocketServerProtocol, str], Awaitable[Any]] + ), + path: str | None = None, + **kwargs: Any, +) -> Serve: + """ + Start a WebSocket server listening on a Unix socket. + + This function is identical to :func:`serve`, except the ``host`` and + ``port`` arguments are replaced by ``path``. It is only available on Unix. + + Unrecognized keyword arguments are passed the event loop's + :meth:`~asyncio.loop.create_unix_server` method. + + It's useful for deploying a server behind a reverse proxy such as nginx. + + Args: + path: File system path to the Unix socket. + + """ + return serve(ws_handler, path=path, unix=True, **kwargs) + + +def remove_path_argument( + ws_handler: ( + Callable[[WebSocketServerProtocol], Awaitable[Any]] + | Callable[[WebSocketServerProtocol, str], Awaitable[Any]] + ), +) -> Callable[[WebSocketServerProtocol], Awaitable[Any]]: + try: + inspect.signature(ws_handler).bind(None) + except TypeError: + try: + inspect.signature(ws_handler).bind(None, "") + except TypeError: # pragma: no cover + # ws_handler accepts neither one nor two arguments; leave it alone. + pass + else: + # ws_handler accepts two arguments; activate backwards compatibility. + warnings.warn("remove second argument of ws_handler", DeprecationWarning) + + async def _ws_handler(websocket: WebSocketServerProtocol) -> Any: + return await cast( + Callable[[WebSocketServerProtocol, str], Awaitable[Any]], + ws_handler, + )(websocket, websocket.path) + + return _ws_handler + + return cast( + Callable[[WebSocketServerProtocol], Awaitable[Any]], + ws_handler, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/protocol.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..ed47272c8d5c4635664ba49d344ce07cdb8d0096 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/protocol.py @@ -0,0 +1,768 @@ +from __future__ import annotations + +import enum +import logging +import uuid +from collections.abc import Generator + +from .exceptions import ( + ConnectionClosed, + ConnectionClosedError, + ConnectionClosedOK, + InvalidState, + PayloadTooBig, + ProtocolError, +) +from .extensions import Extension +from .frames import ( + OK_CLOSE_CODES, + OP_BINARY, + OP_CLOSE, + OP_CONT, + OP_PING, + OP_PONG, + OP_TEXT, + Close, + CloseCode, + Frame, +) +from .http11 import Request, Response +from .streams import StreamReader +from .typing import BytesLike, LoggerLike, Origin, Subprotocol + + +__all__ = [ + "Protocol", + "Side", + "State", + "SEND_EOF", +] + +Event = Request | Response | Frame +"""Events that :meth:`~Protocol.events_received` may return.""" + + +class Side(enum.IntEnum): + """A WebSocket connection is either a server or a client.""" + + SERVER, CLIENT = range(2) + + +SERVER = Side.SERVER +CLIENT = Side.CLIENT + + +class State(enum.IntEnum): + """A WebSocket connection is in one of these four states.""" + + CONNECTING, OPEN, CLOSING, CLOSED = range(4) + + +CONNECTING = State.CONNECTING +OPEN = State.OPEN +CLOSING = State.CLOSING +CLOSED = State.CLOSED + + +SEND_EOF = b"" +"""Sentinel signaling that the TCP connection must be half-closed.""" + + +class Protocol: + """ + Sans-I/O implementation of a WebSocket connection. + + Args: + side: :attr:`~Side.CLIENT` or :attr:`~Side.SERVER`. + state: Initial state of the WebSocket connection. + max_size: Maximum size of incoming messages in bytes. + :obj:`None` disables the limit. You may pass a ``(max_message_size, + max_fragment_size)`` tuple to set different limits for messages and + fragments when you expect long messages sent in short fragments. + logger: Logger for this connection; depending on ``side``, + defaults to ``logging.getLogger("websockets.client")`` + or ``logging.getLogger("websockets.server")``; + see the :doc:`logging guide <../../topics/logging>` for details. + + """ + + def __init__( + self, + side: Side, + *, + state: State = OPEN, + max_size: tuple[int | None, int | None] | int | None = 2**20, + logger: LoggerLike | None = None, + ) -> None: + # Unique identifier. For logs. + self.id: uuid.UUID = uuid.uuid4() + """Unique identifier of the connection. Useful in logs.""" + + # Logger or LoggerAdapter for this connection. + if logger is None: + logger = logging.getLogger(f"websockets.{side.name.lower()}") + self.logger: LoggerLike = logger + """Logger for this connection.""" + + # Track if DEBUG is enabled. Shortcut logging calls if it isn't. + self.debug = logger.isEnabledFor(logging.DEBUG) + + # Connection side. CLIENT or SERVER. + self.side = side + + # Connection state. Initially OPEN because subclasses handle CONNECTING. + self.state = state + + # Maximum size of incoming messages in bytes. + if isinstance(max_size, int) or max_size is None: + self.max_message_size, self.max_fragment_size = max_size, None + else: + self.max_message_size, self.max_fragment_size = max_size + + # Current size of incoming message in bytes. Only set while reading a + # fragmented message i.e. a data frames with the FIN bit not set. + self.current_size: int | None = None + + # True while sending a fragmented message i.e. a data frames with the + # FIN bit not set. + self.expect_continuation_frame = False + + # WebSocket protocol parameters. + self.origin: Origin | None = None + self.extensions: list[Extension] = [] + self.subprotocol: Subprotocol | None = None + + # Close code and reason, set when a close frame is sent or received. + self.close_rcvd: Close | None = None + self.close_sent: Close | None = None + self.close_rcvd_then_sent: bool | None = None + + # Track if an exception happened during the handshake. + self.handshake_exc: Exception | None = None + """ + Exception to raise if the opening handshake failed. + + :obj:`None` if the opening handshake succeeded. + + """ + + # Track if send_eof() was called. + self.eof_sent = False + + # Parser state. + self.reader = StreamReader() + self.events: list[Event] = [] + self.writes: list[bytes] = [] + self.parser = self.parse() + next(self.parser) # start coroutine + self.parser_exc: Exception | None = None + + @property + def state(self) -> State: + """ + State of the WebSocket connection. + + Defined in 4.1_, 4.2_, 7.1.3_, and 7.1.4_ of :rfc:`6455`. + + .. _4.1: https://datatracker.ietf.org/doc/html/rfc6455#section-4.1 + .. _4.2: https://datatracker.ietf.org/doc/html/rfc6455#section-4.2 + .. _7.1.3: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.3 + .. _7.1.4: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4 + + """ + return self._state + + @state.setter + def state(self, state: State) -> None: + if self.debug: + self.logger.debug("= connection is %s", state.name) + self._state = state + + @property + def close_code(self) -> int | None: + """ + WebSocket close code received from the remote endpoint. + + Defined in 7.1.5_ of :rfc:`6455`. + + .. _7.1.5: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 + + :obj:`None` if the connection isn't closed yet. + + """ + if self.state is not CLOSED: + return None + elif self.close_rcvd is None: + return CloseCode.ABNORMAL_CLOSURE + else: + return self.close_rcvd.code + + @property + def close_reason(self) -> str | None: + """ + WebSocket close reason received from the remote endpoint. + + Defined in 7.1.6_ of :rfc:`6455`. + + .. _7.1.6: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 + + :obj:`None` if the connection isn't closed yet. + + """ + if self.state is not CLOSED: + return None + elif self.close_rcvd is None: + return "" + else: + return self.close_rcvd.reason + + @property + def close_exc(self) -> ConnectionClosed: + """ + Exception to raise when trying to interact with a closed connection. + + Don't raise this exception while the connection :attr:`state` + is :attr:`~websockets.protocol.State.CLOSING`; wait until + it's :attr:`~websockets.protocol.State.CLOSED`. + + Indeed, the exception includes the close code and reason, which are + known only once the connection is closed. + + Raises: + AssertionError: If the connection isn't closed yet. + + """ + assert self.state is CLOSED, "connection isn't closed yet" + exc_type: type[ConnectionClosed] + if ( + self.close_rcvd is not None + and self.close_sent is not None + and self.close_rcvd.code in OK_CLOSE_CODES + and self.close_sent.code in OK_CLOSE_CODES + ): + exc_type = ConnectionClosedOK + else: + exc_type = ConnectionClosedError + exc: ConnectionClosed = exc_type( + self.close_rcvd, + self.close_sent, + self.close_rcvd_then_sent, + ) + # Chain to the exception raised in the parser, if any. + exc.__cause__ = self.parser_exc + return exc + + # Public methods for receiving data. + + def receive_data(self, data: bytes | bytearray) -> None: + """ + Receive data from the network. + + After calling this method: + + - You must call :meth:`data_to_send` and send this data to the network. + - You should call :meth:`events_received` and process resulting events. + + Raises: + EOFError: If :meth:`receive_eof` was called earlier. + + """ + self.reader.feed_data(data) + next(self.parser) + + def receive_eof(self) -> None: + """ + Receive the end of the data stream from the network. + + After calling this method: + + - You must call :meth:`data_to_send` and send this data to the network; + it will return ``[b""]``, signaling the end of the stream, or ``[]``. + - You aren't expected to call :meth:`events_received`; it won't return + any new events. + + :meth:`receive_eof` is idempotent. + + """ + if self.reader.eof: + return + self.reader.feed_eof() + next(self.parser) + + # Public methods for sending events. + + def send_continuation(self, data: BytesLike, fin: bool) -> None: + """ + Send a `Continuation frame`_. + + .. _Continuation frame: + https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + Parameters: + data: payload containing the same kind of data + as the initial frame. + fin: FIN bit; set it to :obj:`True` if this is the last frame + of a fragmented message and to :obj:`False` otherwise. + + Raises: + ProtocolError: If a fragmented message isn't in progress. + + """ + if not self.expect_continuation_frame: + raise ProtocolError("unexpected continuation frame") + if self._state is not OPEN: + raise InvalidState(f"connection is {self.state.name.lower()}") + self.expect_continuation_frame = not fin + self.send_frame(Frame(OP_CONT, data, fin)) + + def send_text(self, data: BytesLike, fin: bool = True) -> None: + """ + Send a `Text frame`_. + + .. _Text frame: + https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + Parameters: + data: payload containing text encoded with UTF-8. + fin: FIN bit; set it to :obj:`False` if this is the first frame of + a fragmented message. + + Raises: + ProtocolError: If a fragmented message is in progress. + + """ + if self.expect_continuation_frame: + raise ProtocolError("expected a continuation frame") + if self._state is not OPEN: + raise InvalidState(f"connection is {self.state.name.lower()}") + self.expect_continuation_frame = not fin + self.send_frame(Frame(OP_TEXT, data, fin)) + + def send_binary(self, data: BytesLike, fin: bool = True) -> None: + """ + Send a `Binary frame`_. + + .. _Binary frame: + https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + Parameters: + data: payload containing arbitrary binary data. + fin: FIN bit; set it to :obj:`False` if this is the first frame of + a fragmented message. + + Raises: + ProtocolError: If a fragmented message is in progress. + + """ + if self.expect_continuation_frame: + raise ProtocolError("expected a continuation frame") + if self._state is not OPEN: + raise InvalidState(f"connection is {self.state.name.lower()}") + self.expect_continuation_frame = not fin + self.send_frame(Frame(OP_BINARY, data, fin)) + + def send_close(self, code: CloseCode | int | None = None, reason: str = "") -> None: + """ + Send a `Close frame`_. + + .. _Close frame: + https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.1 + + Parameters: + code: close code. + reason: close reason. + + Raises: + ProtocolError: If the code isn't valid or if a reason is provided + without a code. + + """ + # While RFC 6455 doesn't rule out sending more than one close Frame, + # websockets is conservative in what it sends and doesn't allow that. + if self._state is not OPEN: + raise InvalidState(f"connection is {self.state.name.lower()}") + if code is None: + if reason != "": + raise ProtocolError("cannot send a reason without a code") + close = Close(CloseCode.NO_STATUS_RCVD, "") + data = b"" + else: + close = Close(code, reason) + data = close.serialize() + # 7.1.3. The WebSocket Closing Handshake is Started + self.send_frame(Frame(OP_CLOSE, data)) + # Since the state is OPEN, no close frame was received yet. + # As a consequence, self.close_rcvd_then_sent remains None. + assert self.close_rcvd is None + self.close_sent = close + self.state = CLOSING + + def send_ping(self, data: BytesLike) -> None: + """ + Send a `Ping frame`_. + + .. _Ping frame: + https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2 + + Parameters: + data: payload containing arbitrary binary data. + + """ + # RFC 6455 allows control frames after starting the closing handshake. + if self._state is not OPEN and self._state is not CLOSING: + raise InvalidState(f"connection is {self.state.name.lower()}") + self.send_frame(Frame(OP_PING, data)) + + def send_pong(self, data: BytesLike) -> None: + """ + Send a `Pong frame`_. + + .. _Pong frame: + https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3 + + Parameters: + data: payload containing arbitrary binary data. + + """ + # RFC 6455 allows control frames after starting the closing handshake. + if self._state is not OPEN and self._state is not CLOSING: + raise InvalidState(f"connection is {self.state.name.lower()}") + self.send_frame(Frame(OP_PONG, data)) + + def fail(self, code: CloseCode | int, reason: str = "") -> None: + """ + `Fail the WebSocket connection`_. + + .. _Fail the WebSocket connection: + https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.7 + + Parameters: + code: close code + reason: close reason + + Raises: + ProtocolError: If the code isn't valid. + """ + # 7.1.7. Fail the WebSocket Connection + + # Send a close frame when the state is OPEN (a close frame was already + # sent if it's CLOSING), except when failing the connection because + # of an error reading from or writing to the network. + if self.state is OPEN: + if code != CloseCode.ABNORMAL_CLOSURE: + close = Close(code, reason) + data = close.serialize() + self.send_frame(Frame(OP_CLOSE, data)) + self.close_sent = close + # If recv_messages() raised an exception upon receiving a close + # frame but before echoing it, then close_rcvd is not None even + # though the state is OPEN. This happens when the connection is + # closed while receiving a fragmented message. + if self.close_rcvd is not None: + self.close_rcvd_then_sent = True + self.state = CLOSING + + # When failing the connection, a server closes the TCP connection + # without waiting for the client to complete the handshake, while a + # client waits for the server to close the TCP connection, possibly + # after sending a close frame that the client will ignore. + if self.side is SERVER and not self.eof_sent: + self.send_eof() + + # 7.1.7. Fail the WebSocket Connection "An endpoint MUST NOT continue + # to attempt to process data(including a responding Close frame) from + # the remote endpoint after being instructed to _Fail the WebSocket + # Connection_." + self.parser = self.discard() + next(self.parser) # start coroutine + + # Public method for getting incoming events after receiving data. + + def events_received(self) -> list[Event]: + """ + Fetch events generated from data received from the network. + + Call this method immediately after any of the ``receive_*()`` methods. + + Process resulting events, likely by passing them to the application. + + Returns: + Events read from the connection. + """ + events, self.events = self.events, [] + return events + + # Public method for getting outgoing data after receiving data or sending events. + + def data_to_send(self) -> list[bytes]: + """ + Obtain data to send to the network. + + Call this method immediately after any of the ``receive_*()``, + ``send_*()``, or :meth:`fail` methods. + + Write resulting data to the connection. + + The empty bytestring :data:`~websockets.protocol.SEND_EOF` signals + the end of the data stream. When you receive it, half-close the TCP + connection. + + Returns: + Data to write to the connection. + + """ + writes, self.writes = self.writes, [] + return writes + + def close_expected(self) -> bool: + """ + Tell if the TCP connection is expected to close soon. + + Call this method immediately after any of the ``receive_*()``, + ``send_close()``, or :meth:`fail` methods. + + If it returns :obj:`True`, schedule closing the TCP connection after a + short timeout if the other side hasn't already closed it. + + Returns: + Whether the TCP connection is expected to close soon. + + """ + # During the opening handshake, when our state is CONNECTING, we expect + # a TCP close if and only if the hansdake fails. When it does, we start + # the TCP closing handshake by sending EOF with send_eof(). + + # Once the opening handshake completes successfully, we expect a TCP + # close if and only if we sent a close frame, meaning that our state + # progressed to CLOSING: + + # * Normal closure: once we send a close frame, we expect a TCP close: + # server waits for client to complete the TCP closing handshake; + # client waits for server to initiate the TCP closing handshake. + + # * Abnormal closure: we always send a close frame and the same logic + # applies, except on EOFError where we don't send a close frame + # because we already received the TCP close, so we don't expect it. + + # If our state is CLOSED, we already received a TCP close so we don't + # expect it anymore. + + # Micro-optimization: put the most common case first + if self.state is OPEN: + return False + if self.state is CLOSING: + return True + if self.state is CLOSED: + return False + assert self.state is CONNECTING + return self.eof_sent + + # Private methods for receiving data. + + def parse(self) -> Generator[None]: + """ + Parse incoming data into frames. + + :meth:`receive_data` and :meth:`receive_eof` run this generator + coroutine until it needs more data or reaches EOF. + + :meth:`parse` never raises an exception. Instead, it sets the + :attr:`parser_exc` and yields control. + + """ + try: + while True: + if (yield from self.reader.at_eof()): + if self.debug: + self.logger.debug("< EOF") + # If the WebSocket connection is closed cleanly, with a + # closing handhshake, recv_frame() substitutes parse() + # with discard(). This branch is reached only when the + # connection isn't closed cleanly. + raise EOFError("unexpected end of stream") + + max_size = None + + if self.max_message_size is not None: + if self.current_size is None: + max_size = self.max_message_size + else: + max_size = self.max_message_size - self.current_size + + if self.max_fragment_size is not None: + if max_size is None: + max_size = self.max_fragment_size + else: + max_size = min(max_size, self.max_fragment_size) + + # During a normal closure, execution ends here on the next + # iteration of the loop after receiving a close frame. At + # this point, recv_frame() replaced parse() by discard(). + frame = yield from Frame.parse( + self.reader.read_exact, + mask=self.side is SERVER, + max_size=max_size, + extensions=self.extensions, + ) + + if self.debug: + self.logger.debug("< %s", frame) + + self.recv_frame(frame) + + except ProtocolError as exc: + self.fail(CloseCode.PROTOCOL_ERROR, str(exc)) + self.parser_exc = exc + + except EOFError as exc: + self.fail(CloseCode.ABNORMAL_CLOSURE, str(exc)) + self.parser_exc = exc + + except UnicodeDecodeError as exc: + self.fail(CloseCode.INVALID_DATA, f"{exc.reason} at position {exc.start}") + self.parser_exc = exc + + except PayloadTooBig as exc: + exc.set_current_size(self.current_size) + self.fail(CloseCode.MESSAGE_TOO_BIG, str(exc)) + self.parser_exc = exc + + except Exception as exc: + self.logger.error("parser failed", exc_info=True) + # Don't include exception details, which may be security-sensitive. + self.fail(CloseCode.INTERNAL_ERROR) + self.parser_exc = exc + + # During an abnormal closure, execution ends here after catching an + # exception. At this point, fail() replaced parse() by discard(). + yield + raise AssertionError("parse() shouldn't step after error") + + def discard(self) -> Generator[None]: + """ + Discard incoming data. + + This coroutine replaces :meth:`parse`: + + - after receiving a close frame, during a normal closure (1.4); + - after sending a close frame, during an abnormal closure (7.1.7). + + """ + # After the opening handshake completes, the server closes the TCP + # connection in the same circumstances where discard() replaces parse(). + # The client closes it when it receives EOF from the server or times + # out. (The latter case cannot be handled in this Sans-I/O layer.) + assert (self.side is SERVER or self.state is CONNECTING) == (self.eof_sent) + while not (yield from self.reader.at_eof()): + self.reader.discard() + if self.debug: + self.logger.debug("< EOF") + # A server closes the TCP connection immediately, while a client + # waits for the server to close the TCP connection. + if self.side is CLIENT and self.state is not CONNECTING: + self.send_eof() + self.state = CLOSED + # If discard() completes normally, execution ends here. + yield + # Once the reader reaches EOF, its feed_data/eof() methods raise an + # error, so our receive_data/eof() methods don't step the generator. + raise AssertionError("discard() shouldn't step after EOF") + + def recv_frame(self, frame: Frame) -> None: + """ + Process an incoming frame. + + """ + if frame.opcode is OP_TEXT or frame.opcode is OP_BINARY: + if self.current_size is not None: + raise ProtocolError("expected a continuation frame") + if not frame.fin: + self.current_size = len(frame.data) + + elif frame.opcode is OP_CONT: + if self.current_size is None: + raise ProtocolError("unexpected continuation frame") + if frame.fin: + self.current_size = None + else: + self.current_size += len(frame.data) + + elif frame.opcode is OP_PING: + # 5.5.2. Ping: "Upon receipt of a Ping frame, an endpoint MUST + # send a Pong frame in response" + pong_frame = Frame(OP_PONG, frame.data) + self.send_frame(pong_frame) + + elif frame.opcode is OP_PONG: + # 5.5.3 Pong: "A response to an unsolicited Pong frame is not + # expected." + pass + + elif frame.opcode is OP_CLOSE: + # 7.1.5. The WebSocket Connection Close Code + # 7.1.6. The WebSocket Connection Close Reason + self.close_rcvd = Close.parse(frame.data) + if self.state is CLOSING: + assert self.close_sent is not None + self.close_rcvd_then_sent = False + + if self.current_size is not None: + raise ProtocolError("incomplete fragmented message") + + # 5.5.1 Close: "If an endpoint receives a Close frame and did + # not previously send a Close frame, the endpoint MUST send a + # Close frame in response. (When sending a Close frame in + # response, the endpoint typically echos the status code it + # received.)" + + if self.state is OPEN: + # Echo the original data instead of re-serializing it with + # Close.serialize() because that fails when the close frame + # is empty and Close.parse() synthesizes a 1005 close code. + # The rest is identical to send_close(). + self.send_frame(Frame(OP_CLOSE, frame.data)) + self.close_sent = self.close_rcvd + self.close_rcvd_then_sent = True + self.state = CLOSING + + # 7.1.2. Start the WebSocket Closing Handshake: "Once an + # endpoint has both sent and received a Close control frame, + # that endpoint SHOULD _Close the WebSocket Connection_" + + # A server closes the TCP connection immediately, while a client + # waits for the server to close the TCP connection. + if self.side is SERVER: + self.send_eof() + + # 1.4. Closing Handshake: "after receiving a control frame + # indicating the connection should be closed, a peer discards + # any further data received." + # RFC 6455 allows reading Ping and Pong frames after a Close frame. + # However, that doesn't seem useful; websockets doesn't support it. + self.parser = self.discard() + next(self.parser) # start coroutine + + else: + # This can't happen because Frame.parse() validates opcodes. + raise AssertionError(f"unexpected opcode: {frame.opcode:02x}") + + self.events.append(frame) + + # Private methods for sending events. + + def send_frame(self, frame: Frame) -> None: + if self.debug: + self.logger.debug("> %s", frame) + self.writes.append( + frame.serialize( + mask=self.side is CLIENT, + extensions=self.extensions, + ) + ) + + def send_eof(self) -> None: + assert not self.eof_sent + self.eof_sent = True + if self.debug: + self.logger.debug("> EOF") + self.writes.append(SEND_EOF) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/proxy.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..c3a735d50cff52574abc5dd0ae3d77ad3936ff11 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/proxy.py @@ -0,0 +1,150 @@ +from __future__ import annotations + +import dataclasses +import urllib.parse +import urllib.request + +from .datastructures import Headers +from .exceptions import InvalidProxy +from .headers import build_authorization_basic, build_host +from .http11 import USER_AGENT +from .uri import DELIMS, WebSocketURI + + +__all__ = ["get_proxy", "parse_proxy", "Proxy"] + + +@dataclasses.dataclass +class Proxy: + """ + Proxy address. + + Attributes: + scheme: ``"socks5h"``, ``"socks5"``, ``"socks4a"``, ``"socks4"``, + ``"https"``, or ``"http"``. + host: Normalized to lower case. + port: Always set even if it's the default. + username: Available when the proxy address contains `User Information`_. + password: Available when the proxy address contains `User Information`_. + + .. _User Information: https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.1 + + """ + + scheme: str + host: str + port: int + username: str | None = None + password: str | None = None + + @property + def user_info(self) -> tuple[str, str] | None: + if self.username is None: + return None + assert self.password is not None + return (self.username, self.password) + + +def parse_proxy(proxy: str) -> Proxy: + """ + Parse and validate a proxy. + + Args: + proxy: proxy. + + Returns: + Parsed proxy. + + Raises: + InvalidProxy: If ``proxy`` isn't a valid proxy. + + """ + parsed = urllib.parse.urlparse(proxy) + if parsed.scheme not in ["socks5h", "socks5", "socks4a", "socks4", "https", "http"]: + raise InvalidProxy(proxy, f"scheme {parsed.scheme} isn't supported") + if parsed.hostname is None: + raise InvalidProxy(proxy, "hostname isn't provided") + if parsed.path not in ["", "/"]: + raise InvalidProxy(proxy, "path is meaningless") + if parsed.query != "": + raise InvalidProxy(proxy, "query is meaningless") + if parsed.fragment != "": + raise InvalidProxy(proxy, "fragment is meaningless") + + scheme = parsed.scheme + host = parsed.hostname + port = parsed.port or (443 if parsed.scheme == "https" else 80) + username = parsed.username + password = parsed.password + # urllib.parse.urlparse accepts URLs with a username but without a + # password. This doesn't make sense for HTTP Basic Auth credentials. + if username is not None and password is None: + raise InvalidProxy(proxy, "username provided without password") + + try: + proxy.encode("ascii") + except UnicodeEncodeError: + # Input contains non-ASCII characters. + # It must be an IRI. Convert it to a URI. + host = host.encode("idna").decode() + if username is not None: + assert password is not None + username = urllib.parse.quote(username, safe=DELIMS) + password = urllib.parse.quote(password, safe=DELIMS) + + return Proxy(scheme, host, port, username, password) + + +def get_proxy(uri: WebSocketURI) -> str | None: + """ + Return the proxy to use for connecting to the given WebSocket URI, if any. + + """ + if urllib.request.proxy_bypass(f"{uri.host}:{uri.port}"): + return None + + # According to the _Proxy Usage_ section of RFC 6455, use a SOCKS5 proxy if + # available, else favor the proxy for HTTPS connections over the proxy for + # HTTP connections. + + # The priority of a proxy for WebSocket connections is unspecified. We give + # it the highest priority. This makes it easy to configure a specific proxy + # for websockets. + + # getproxies() may return SOCKS proxies as {"socks": "http://host:port"} or + # as {"https": "socks5h://host:port"} depending on whether they're declared + # in the operating system or in environment variables. + + proxies = urllib.request.getproxies() + if uri.secure: + schemes = ["wss", "socks", "https"] + else: + schemes = ["ws", "socks", "https", "http"] + + for scheme in schemes: + proxy = proxies.get(scheme) + if proxy is not None: + if scheme == "socks" and proxy.startswith("http://"): + proxy = "socks5h://" + proxy[7:] + return proxy + else: + return None + + +def prepare_connect_request( + proxy: Proxy, + ws_uri: WebSocketURI, + user_agent_header: str | None = USER_AGENT, +) -> bytes: + host = build_host(ws_uri.host, ws_uri.port, ws_uri.secure, always_include_port=True) + headers = Headers() + headers["Host"] = build_host(ws_uri.host, ws_uri.port, ws_uri.secure) + if user_agent_header is not None: + headers["User-Agent"] = user_agent_header + if proxy.username is not None: + assert proxy.password is not None # enforced by parse_proxy() + headers["Proxy-Authorization"] = build_authorization_basic( + proxy.username, proxy.password + ) + # We cannot use the Request class because it supports only GET requests. + return f"CONNECT {host} HTTP/1.1\r\n".encode() + headers.serialize() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/py.typed b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/server.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/server.py new file mode 100644 index 0000000000000000000000000000000000000000..c4ff6cf70008ab2a01b9a6cbb739b799d414582c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/server.py @@ -0,0 +1,589 @@ +from __future__ import annotations + +import base64 +import binascii +import email.utils +import http +import re +import warnings +from collections.abc import Generator, Sequence +from typing import Any, Callable, cast + +from .datastructures import Headers, MultipleValuesError +from .exceptions import ( + InvalidHandshake, + InvalidHeader, + InvalidHeaderValue, + InvalidMessage, + InvalidOrigin, + InvalidUpgrade, + NegotiationError, +) +from .extensions import Extension, ServerExtensionFactory +from .headers import ( + build_extension, + parse_connection, + parse_extension, + parse_subprotocol, + parse_upgrade, +) +from .http11 import Request, Response +from .imports import lazy_import +from .protocol import CONNECTING, OPEN, SERVER, Protocol, State +from .typing import ( + ConnectionOption, + ExtensionHeader, + LoggerLike, + Origin, + StatusLike, + Subprotocol, + UpgradeProtocol, +) +from .utils import accept_key + + +__all__ = ["ServerProtocol"] + + +class ServerProtocol(Protocol): + """ + Sans-I/O implementation of a WebSocket server connection. + + Args: + origins: Acceptable values of the ``Origin`` header. Values can be + :class:`str` to test for an exact match or regular expressions + compiled by :func:`re.compile` to test against a pattern. Include + :obj:`None` in the list if the lack of an origin is acceptable. + This is useful for defending against Cross-Site WebSocket + Hijacking attacks. + extensions: List of supported extensions, in order in which they + should be tried. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + select_subprotocol: Callback for selecting a subprotocol among + those supported by the client and the server. It has the same + signature as the :meth:`select_subprotocol` method, including a + :class:`ServerProtocol` instance as first argument. + state: Initial state of the WebSocket connection. + max_size: Maximum size of incoming messages in bytes. + :obj:`None` disables the limit. You may pass a ``(max_message_size, + max_fragment_size)`` tuple to set different limits for messages and + fragments when you expect long messages sent in short fragments. + logger: Logger for this connection; + defaults to ``logging.getLogger("websockets.server")``; + see the :doc:`logging guide <../../topics/logging>` for details. + + """ + + def __init__( + self, + *, + origins: Sequence[Origin | re.Pattern[str] | None] | None = None, + extensions: Sequence[ServerExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + select_subprotocol: ( + Callable[ + [ServerProtocol, Sequence[Subprotocol]], + Subprotocol | None, + ] + | None + ) = None, + state: State = CONNECTING, + max_size: int | None | tuple[int | None, int | None] = 2**20, + logger: LoggerLike | None = None, + ) -> None: + super().__init__( + side=SERVER, + state=state, + max_size=max_size, + logger=logger, + ) + self.origins = origins + self.available_extensions = extensions + self.available_subprotocols = subprotocols + if select_subprotocol is not None: + # Bind select_subprotocol then shadow self.select_subprotocol. + # Use setattr to work around https://github.com/python/mypy/issues/2427. + setattr( + self, + "select_subprotocol", + select_subprotocol.__get__(self, self.__class__), + ) + + def accept(self, request: Request) -> Response: + """ + Create a handshake response to accept the connection. + + If the handshake request is valid and the handshake successful, + :meth:`accept` returns an HTTP response with status code 101. + + Else, it returns an HTTP response with another status code. This rejects + the connection, like :meth:`reject` would. + + You must send the handshake response with :meth:`send_response`. + + You may modify the response before sending it, typically by adding HTTP + headers. + + Args: + request: WebSocket handshake request received from the client. + + Returns: + WebSocket handshake response or HTTP response to send to the client. + + """ + try: + ( + accept_header, + extensions_header, + protocol_header, + ) = self.process_request(request) + except InvalidOrigin as exc: + request._exception = exc + self.handshake_exc = exc + if self.debug: + self.logger.debug("! invalid origin", exc_info=True) + return self.reject( + http.HTTPStatus.FORBIDDEN, + f"Failed to open a WebSocket connection: {exc}.\n", + ) + except InvalidUpgrade as exc: + request._exception = exc + self.handshake_exc = exc + if self.debug: + self.logger.debug("! invalid upgrade", exc_info=True) + response = self.reject( + http.HTTPStatus.UPGRADE_REQUIRED, + ( + f"Failed to open a WebSocket connection: {exc}.\n" + f"\n" + f"You cannot access a WebSocket server directly " + f"with a browser. You need a WebSocket client.\n" + ), + ) + response.headers["Upgrade"] = "websocket" + return response + except InvalidHandshake as exc: + request._exception = exc + self.handshake_exc = exc + if self.debug: + self.logger.debug("! invalid handshake", exc_info=True) + exc_chain = cast(BaseException, exc) + exc_str = f"{exc_chain}" + while exc_chain.__cause__ is not None: + exc_chain = exc_chain.__cause__ + exc_str += f"; {exc_chain}" + return self.reject( + http.HTTPStatus.BAD_REQUEST, + f"Failed to open a WebSocket connection: {exc_str}.\n", + ) + except Exception as exc: + # Handle exceptions raised by user-provided select_subprotocol and + # unexpected errors. + request._exception = exc + self.handshake_exc = exc + self.logger.error("opening handshake failed", exc_info=True) + return self.reject( + http.HTTPStatus.INTERNAL_SERVER_ERROR, + ( + "Failed to open a WebSocket connection.\n" + "See server log for more information.\n" + ), + ) + + headers = Headers() + headers["Date"] = email.utils.formatdate(usegmt=True) + headers["Upgrade"] = "websocket" + headers["Connection"] = "Upgrade" + headers["Sec-WebSocket-Accept"] = accept_header + if extensions_header is not None: + headers["Sec-WebSocket-Extensions"] = extensions_header + if protocol_header is not None: + headers["Sec-WebSocket-Protocol"] = protocol_header + return Response(101, "Switching Protocols", headers) + + def process_request( + self, + request: Request, + ) -> tuple[str, str | None, str | None]: + """ + Check a handshake request and negotiate extensions and subprotocol. + + This function doesn't verify that the request is an HTTP/1.1 or higher + GET request and doesn't check the ``Host`` header. These controls are + usually performed earlier in the HTTP request handling code. They're + the responsibility of the caller. + + Args: + request: WebSocket handshake request received from the client. + + Returns: + ``Sec-WebSocket-Accept``, ``Sec-WebSocket-Extensions``, and + ``Sec-WebSocket-Protocol`` headers for the handshake response. + + Raises: + InvalidHandshake: If the handshake request is invalid; + then the server must return 400 Bad Request error. + + """ + headers = request.headers + + connection: list[ConnectionOption] = sum( + [parse_connection(value) for value in headers.get_all("Connection")], [] + ) + if not any(value.lower() == "upgrade" for value in connection): + raise InvalidUpgrade( + "Connection", ", ".join(connection) if connection else None + ) + + upgrade: list[UpgradeProtocol] = sum( + [parse_upgrade(value) for value in headers.get_all("Upgrade")], [] + ) + # For compatibility with non-strict implementations, ignore case when + # checking the Upgrade header. The RFC always uses "websocket", except + # in section 11.2. (IANA registration) where it uses "WebSocket". + if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"): + raise InvalidUpgrade("Upgrade", ", ".join(upgrade) if upgrade else None) + + try: + key = headers["Sec-WebSocket-Key"] + except KeyError: + raise InvalidHeader("Sec-WebSocket-Key") from None + except MultipleValuesError: + raise InvalidHeader("Sec-WebSocket-Key", "multiple values") from None + try: + raw_key = base64.b64decode(key.encode(), validate=True) + except binascii.Error as exc: + raise InvalidHeaderValue("Sec-WebSocket-Key", key) from exc + if len(raw_key) != 16: + raise InvalidHeaderValue("Sec-WebSocket-Key", key) + accept_header = accept_key(key) + + try: + version = headers["Sec-WebSocket-Version"] + except KeyError: + raise InvalidHeader("Sec-WebSocket-Version") from None + except MultipleValuesError: + raise InvalidHeader("Sec-WebSocket-Version", "multiple values") from None + if version != "13": + raise InvalidHeaderValue("Sec-WebSocket-Version", version) + + self.origin = self.process_origin(headers) + extensions_header, self.extensions = self.process_extensions(headers) + protocol_header = self.subprotocol = self.process_subprotocol(headers) + + return (accept_header, extensions_header, protocol_header) + + def process_origin(self, headers: Headers) -> Origin | None: + """ + Handle the Origin HTTP request header. + + Args: + headers: WebSocket handshake request headers. + + Returns: + origin, if it is acceptable. + + Raises: + InvalidHandshake: If the Origin header is invalid. + InvalidOrigin: If the origin isn't acceptable. + + """ + # "The user agent MUST NOT include more than one Origin header field" + # per https://datatracker.ietf.org/doc/html/rfc6454#section-7.3. + try: + origin = headers.get("Origin") + except MultipleValuesError: + raise InvalidHeader("Origin", "multiple values") from None + if origin is not None: + origin = cast(Origin, origin) + if self.origins is not None: + for origin_or_regex in self.origins: + if origin_or_regex == origin or ( + isinstance(origin_or_regex, re.Pattern) + and origin is not None + and origin_or_regex.fullmatch(origin) is not None + ): + break + else: + raise InvalidOrigin(origin) + return origin + + def process_extensions( + self, + headers: Headers, + ) -> tuple[str | None, list[Extension]]: + """ + Handle the Sec-WebSocket-Extensions HTTP request header. + + Accept or reject each extension proposed in the client request. + Negotiate parameters for accepted extensions. + + Per :rfc:`6455`, negotiation rules are defined by the specification of + each extension. + + To provide this level of flexibility, for each extension proposed by + the client, we check for a match with each extension available in the + server configuration. If no match is found, the extension is ignored. + + If several variants of the same extension are proposed by the client, + it may be accepted several times, which won't make sense in general. + Extensions must implement their own requirements. For this purpose, + the list of previously accepted extensions is provided. + + This process doesn't allow the server to reorder extensions. It can + only select a subset of the extensions proposed by the client. + + Other requirements, for example related to mandatory extensions or the + order of extensions, may be implemented by overriding this method. + + Args: + headers: WebSocket handshake request headers. + + Returns: + ``Sec-WebSocket-Extensions`` HTTP response header and list of + accepted extensions. + + Raises: + InvalidHandshake: If the Sec-WebSocket-Extensions header is invalid. + + """ + response_header_value: str | None = None + + extension_headers: list[ExtensionHeader] = [] + accepted_extensions: list[Extension] = [] + + header_values = headers.get_all("Sec-WebSocket-Extensions") + + if header_values and self.available_extensions: + parsed_header_values: list[ExtensionHeader] = sum( + [parse_extension(header_value) for header_value in header_values], [] + ) + + for name, request_params in parsed_header_values: + for ext_factory in self.available_extensions: + # Skip non-matching extensions based on their name. + if ext_factory.name != name: + continue + + # Skip non-matching extensions based on their params. + try: + response_params, extension = ext_factory.process_request_params( + request_params, accepted_extensions + ) + except NegotiationError: + continue + + # Add matching extension to the final list. + extension_headers.append((name, response_params)) + accepted_extensions.append(extension) + + # Break out of the loop once we have a match. + break + + # If we didn't break from the loop, no extension in our list + # matched what the client sent. The extension is declined. + + # Serialize extension header. + if extension_headers: + response_header_value = build_extension(extension_headers) + + return response_header_value, accepted_extensions + + def process_subprotocol(self, headers: Headers) -> Subprotocol | None: + """ + Handle the Sec-WebSocket-Protocol HTTP request header. + + Args: + headers: WebSocket handshake request headers. + + Returns: + Subprotocol, if one was selected; this is also the value of the + ``Sec-WebSocket-Protocol`` response header. + + Raises: + InvalidHandshake: If the Sec-WebSocket-Subprotocol header is invalid. + + """ + subprotocols: Sequence[Subprotocol] = sum( + [ + parse_subprotocol(header_value) + for header_value in headers.get_all("Sec-WebSocket-Protocol") + ], + [], + ) + return self.select_subprotocol(subprotocols) + + def select_subprotocol( + self, + subprotocols: Sequence[Subprotocol], + ) -> Subprotocol | None: + """ + Pick a subprotocol among those offered by the client. + + If several subprotocols are supported by both the client and the server, + pick the first one in the list declared the server. + + If the server doesn't support any subprotocols, continue without a + subprotocol, regardless of what the client offers. + + If the server supports at least one subprotocol and the client doesn't + offer any, abort the handshake with an HTTP 400 error. + + You provide a ``select_subprotocol`` argument to :class:`ServerProtocol` + to override this logic. For example, you could accept the connection + even if client doesn't offer a subprotocol, rather than reject it. + + Here's how to negotiate the ``chat`` subprotocol if the client supports + it and continue without a subprotocol otherwise:: + + def select_subprotocol(protocol, subprotocols): + if "chat" in subprotocols: + return "chat" + + Args: + subprotocols: List of subprotocols offered by the client. + + Returns: + Selected subprotocol, if a common subprotocol was found. + + :obj:`None` to continue without a subprotocol. + + Raises: + NegotiationError: Custom implementations may raise this exception + to abort the handshake with an HTTP 400 error. + + """ + # Server doesn't offer any subprotocols. + if not self.available_subprotocols: # None or empty list + return None + + # Server offers at least one subprotocol but client doesn't offer any. + if not subprotocols: + raise NegotiationError("missing subprotocol") + + # Server and client both offer subprotocols. Look for a shared one. + proposed_subprotocols = set(subprotocols) + for subprotocol in self.available_subprotocols: + if subprotocol in proposed_subprotocols: + return subprotocol + + # No common subprotocol was found. + raise NegotiationError( + "invalid subprotocol; expected one of " + + ", ".join(self.available_subprotocols) + ) + + def reject(self, status: StatusLike, text: str) -> Response: + """ + Create a handshake response to reject the connection. + + A short plain text response is the best fallback when failing to + establish a WebSocket connection. + + You must send the handshake response with :meth:`send_response`. + + You may modify the response before sending it, for example by changing + HTTP headers. + + Args: + status: HTTP status code. + text: HTTP response body; it will be encoded to UTF-8. + + Returns: + HTTP response to send to the client. + + """ + # If status is an int instead of an HTTPStatus, fix it automatically. + status = http.HTTPStatus(status) + body = text.encode() + headers = Headers( + [ + ("Date", email.utils.formatdate(usegmt=True)), + ("Connection", "close"), + ("Content-Length", str(len(body))), + ("Content-Type", "text/plain; charset=utf-8"), + ] + ) + return Response(status.value, status.phrase, headers, body) + + def send_response(self, response: Response) -> None: + """ + Send a handshake response to the client. + + Args: + response: WebSocket handshake response event to send. + + """ + if self.debug: + code, phrase = response.status_code, response.reason_phrase + self.logger.debug("> HTTP/1.1 %d %s", code, phrase) + for key, value in response.headers.raw_items(): + self.logger.debug("> %s: %s", key, value) + if response.body: + self.logger.debug("> [body] (%d bytes)", len(response.body)) + + self.writes.append(response.serialize()) + + if response.status_code == 101: + assert self.state is CONNECTING + self.state = OPEN + self.logger.info("connection open") + + else: + self.logger.info( + "connection rejected (%d %s)", + response.status_code, + response.reason_phrase, + ) + + self.send_eof() + self.parser = self.discard() + next(self.parser) # start coroutine + + def parse(self) -> Generator[None]: + if self.state is CONNECTING: + try: + request = yield from Request.parse( + self.reader.read_line, + ) + except Exception as exc: + self.handshake_exc = InvalidMessage( + "did not receive a valid HTTP request" + ) + self.handshake_exc.__cause__ = exc + self.send_eof() + self.parser = self.discard() + next(self.parser) # start coroutine + yield + + if self.debug: + self.logger.debug("< GET %s HTTP/1.1", request.path) + for key, value in request.headers.raw_items(): + self.logger.debug("< %s: %s", key, value) + + self.events.append(request) + + yield from super().parse() + + +class ServerConnection(ServerProtocol): + def __init__(self, *args: Any, **kwargs: Any) -> None: + warnings.warn( # deprecated in 11.0 - 2023-04-02 + "ServerConnection was renamed to ServerProtocol", + DeprecationWarning, + ) + super().__init__(*args, **kwargs) + + +lazy_import( + globals(), + deprecated_aliases={ + # deprecated in 14.0 - 2024-11-09 + "WebSocketServer": ".legacy.server", + "WebSocketServerProtocol": ".legacy.server", + "broadcast": ".legacy.server", + "serve": ".legacy.server", + "unix_serve": ".legacy.server", + }, +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/speedups.c b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/speedups.c new file mode 100644 index 0000000000000000000000000000000000000000..5c0235abef1ebb0ccbb0e26d9d5d7100e4f16031 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/speedups.c @@ -0,0 +1,229 @@ +/* C implementation of performance sensitive functions. */ + +#define PY_SSIZE_T_CLEAN +#include +#include /* uint8_t, uint32_t, uint64_t */ + +#if __ARM_NEON +#include +#elif __SSE2__ +#include +#endif + +static const Py_ssize_t MASK_LEN = 4; + +/* Similar to PyBytes_AsStringAndSize, but accepts more types */ + +static int +_PyBytesLike_AsStringAndSize(PyObject *obj, PyObject **tmp, char **buffer, Py_ssize_t *length) +{ + // This supports bytes, bytearrays, and memoryview objects, + // which are common data structures for handling byte streams. + // If *tmp isn't NULL, the caller gets a new reference. + if (PyBytes_Check(obj)) + { + *tmp = NULL; + *buffer = PyBytes_AS_STRING(obj); + *length = PyBytes_GET_SIZE(obj); + } + else if (PyByteArray_Check(obj)) + { + *tmp = NULL; + *buffer = PyByteArray_AS_STRING(obj); + *length = PyByteArray_GET_SIZE(obj); + } + else if (PyMemoryView_Check(obj)) + { + *tmp = PyMemoryView_GetContiguous(obj, PyBUF_READ, 'C'); + if (*tmp == NULL) + { + return -1; + } + Py_buffer *mv_buf; + mv_buf = PyMemoryView_GET_BUFFER(*tmp); + *buffer = mv_buf->buf; + *length = mv_buf->len; + } + else + { + PyErr_Format( + PyExc_TypeError, + "expected a bytes-like object, %.200s found", + Py_TYPE(obj)->tp_name); + return -1; + } + + return 0; +} + +/* C implementation of websockets.utils.apply_mask */ + +static PyObject * +apply_mask(PyObject *self, PyObject *args, PyObject *kwds) +{ + + // In order to support various bytes-like types, accept any Python object. + + static char *kwlist[] = {"data", "mask", NULL}; + PyObject *input_obj; + PyObject *mask_obj; + + // A pointer to a char * + length will be extracted from the data and mask + // arguments, possibly via a Py_buffer. + + PyObject *input_tmp = NULL; + char *input; + Py_ssize_t input_len; + PyObject *mask_tmp = NULL; + char *mask; + Py_ssize_t mask_len; + + // Initialize a PyBytesObject then get a pointer to the underlying char * + // in order to avoid an extra memory copy in PyBytes_FromStringAndSize. + + PyObject *result = NULL; + char *output; + + // Other variables. + + Py_ssize_t i = 0; + + // Parse inputs. + + if (!PyArg_ParseTupleAndKeywords( + args, kwds, "OO", kwlist, &input_obj, &mask_obj)) + { + goto exit; + } + + if (_PyBytesLike_AsStringAndSize(input_obj, &input_tmp, &input, &input_len) == -1) + { + goto exit; + } + + if (_PyBytesLike_AsStringAndSize(mask_obj, &mask_tmp, &mask, &mask_len) == -1) + { + goto exit; + } + + if (mask_len != MASK_LEN) + { + PyErr_SetString(PyExc_ValueError, "mask must contain 4 bytes"); + goto exit; + } + + // Create output. + + result = PyBytes_FromStringAndSize(NULL, input_len); + if (result == NULL) + { + goto exit; + } + + // Since we just created result, we don't need error checks. + output = PyBytes_AS_STRING(result); + + // Perform the masking operation. + + // Apparently GCC cannot figure out the following optimizations by itself. + + // We need a new scope for MSVC 2010 (non C99 friendly) + { +#if __ARM_NEON + + // With NEON support, XOR by blocks of 16 bytes = 128 bits. + + Py_ssize_t input_len_128 = input_len & ~15; + uint8x16_t mask_128 = vreinterpretq_u8_u32(vdupq_n_u32(*(uint32_t *)mask)); + + for (; i < input_len_128; i += 16) + { + uint8x16_t in_128 = vld1q_u8((uint8_t *)(input + i)); + uint8x16_t out_128 = veorq_u8(in_128, mask_128); + vst1q_u8((uint8_t *)(output + i), out_128); + } + +#elif __SSE2__ + + // With SSE2 support, XOR by blocks of 16 bytes = 128 bits. + + // Since we cannot control the 16-bytes alignment of input and output + // buffers, we rely on loadu/storeu rather than load/store. + + Py_ssize_t input_len_128 = input_len & ~15; + __m128i mask_128 = _mm_set1_epi32(*(uint32_t *)mask); + + for (; i < input_len_128; i += 16) + { + __m128i in_128 = _mm_loadu_si128((__m128i *)(input + i)); + __m128i out_128 = _mm_xor_si128(in_128, mask_128); + _mm_storeu_si128((__m128i *)(output + i), out_128); + } + +#else + + // Without SSE2 support, XOR by blocks of 8 bytes = 64 bits. + + // We assume the memory allocator aligns everything on 8 bytes boundaries. + + Py_ssize_t input_len_64 = input_len & ~7; + uint32_t mask_32 = *(uint32_t *)mask; + uint64_t mask_64 = ((uint64_t)mask_32 << 32) | (uint64_t)mask_32; + + for (; i < input_len_64; i += 8) + { + *(uint64_t *)(output + i) = *(uint64_t *)(input + i) ^ mask_64; + } + +#endif + } + + // XOR the remainder of the input byte by byte. + + for (; i < input_len; i++) + { + output[i] = input[i] ^ mask[i & (MASK_LEN - 1)]; + } + +exit: + Py_XDECREF(input_tmp); + Py_XDECREF(mask_tmp); + return result; + +} + +static PyMethodDef speedups_methods[] = { + { + "apply_mask", + (PyCFunction)apply_mask, + METH_VARARGS | METH_KEYWORDS, + "Apply masking to the data of a WebSocket message.", + }, + {NULL, NULL, 0, NULL}, /* Sentinel */ +}; + +static struct PyModuleDef speedups_module = { + PyModuleDef_HEAD_INIT, + "websocket.speedups", /* m_name */ + "C implementation of performance sensitive functions.", + /* m_doc */ + -1, /* m_size */ + speedups_methods, /* m_methods */ + NULL, + NULL, + NULL, + NULL +}; + +PyMODINIT_FUNC +PyInit_speedups(void) +{ + PyObject *m = PyModule_Create(&speedups_module); + if (m == NULL) { + return NULL; + } +#ifdef Py_GIL_DISABLED + PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED); +#endif + return m; +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/speedups.cp311-win_amd64.pyd b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/speedups.cp311-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..0a476e85fc0cc6fcf731ccd948c2fd5b13be48c1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/speedups.cp311-win_amd64.pyd differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/speedups.pyi b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/speedups.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2aa58e8e92c4cc66c30d423051e6dc55b0b86d0b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/speedups.pyi @@ -0,0 +1,3 @@ +from .typing import BytesLike + +def apply_mask(data: BytesLike, mask: bytes | bytearray) -> bytes: ... diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/streams.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/streams.py new file mode 100644 index 0000000000000000000000000000000000000000..35634fc5b47b702322d73aabfe083c6817203674 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/streams.py @@ -0,0 +1,151 @@ +from __future__ import annotations + +from collections.abc import Generator + + +class StreamReader: + """ + Generator-based stream reader. + + This class doesn't support concurrent calls to :meth:`read_line`, + :meth:`read_exact`, or :meth:`read_to_eof`. Make sure calls are + serialized. + + """ + + def __init__(self) -> None: + self.buffer = bytearray() + self.eof = False + + def read_line(self, m: int) -> Generator[None, None, bytearray]: + """ + Read a LF-terminated line from the stream. + + This is a generator-based coroutine. + + The return value includes the LF character. + + Args: + m: Maximum number bytes to read; this is a security limit. + + Raises: + EOFError: If the stream ends without a LF. + RuntimeError: If the stream ends in more than ``m`` bytes. + + """ + n = 0 # number of bytes to read + p = 0 # number of bytes without a newline + while True: + n = self.buffer.find(b"\n", p) + 1 + if n > 0: + break + p = len(self.buffer) + if p > m: + raise RuntimeError(f"read {p} bytes, expected no more than {m} bytes") + if self.eof: + raise EOFError(f"stream ends after {p} bytes, before end of line") + yield + if n > m: + raise RuntimeError(f"read {n} bytes, expected no more than {m} bytes") + r = self.buffer[:n] + del self.buffer[:n] + return r + + def read_exact(self, n: int) -> Generator[None, None, bytearray]: + """ + Read a given number of bytes from the stream. + + This is a generator-based coroutine. + + Args: + n: How many bytes to read. + + Raises: + EOFError: If the stream ends in less than ``n`` bytes. + + """ + assert n >= 0 + while len(self.buffer) < n: + if self.eof: + p = len(self.buffer) + raise EOFError(f"stream ends after {p} bytes, expected {n} bytes") + yield + r = self.buffer[:n] + del self.buffer[:n] + return r + + def read_to_eof(self, m: int) -> Generator[None, None, bytearray]: + """ + Read all bytes from the stream. + + This is a generator-based coroutine. + + Args: + m: Maximum number bytes to read; this is a security limit. + + Raises: + RuntimeError: If the stream ends in more than ``m`` bytes. + + """ + while not self.eof: + p = len(self.buffer) + if p > m: + raise RuntimeError(f"read {p} bytes, expected no more than {m} bytes") + yield + r = self.buffer[:] + del self.buffer[:] + return r + + def at_eof(self) -> Generator[None, None, bool]: + """ + Tell whether the stream has ended and all data was read. + + This is a generator-based coroutine. + + """ + while True: + if self.buffer: + return False + if self.eof: + return True + # When all data was read but the stream hasn't ended, we can't + # tell if until either feed_data() or feed_eof() is called. + yield + + def feed_data(self, data: bytes | bytearray) -> None: + """ + Write data to the stream. + + :meth:`feed_data` cannot be called after :meth:`feed_eof`. + + Args: + data: Data to write. + + Raises: + EOFError: If the stream has ended. + + """ + if self.eof: + raise EOFError("stream ended") + self.buffer += data + + def feed_eof(self) -> None: + """ + End the stream. + + :meth:`feed_eof` cannot be called more than once. + + Raises: + EOFError: If the stream has ended. + + """ + if self.eof: + raise EOFError("stream ended") + self.eof = True + + def discard(self) -> None: + """ + Discard all buffered data, but don't end the stream. + + """ + del self.buffer[:] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a8ccc37ba68119b50817f287e76061738ec7b68 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/__pycache__/client.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/__pycache__/client.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca42f100a4a74754b21ef54a69930bd998c1b7aa Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/__pycache__/client.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/__pycache__/connection.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/__pycache__/connection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67cc99bafc8354781b394b1c3e4cec0d48b7ea5f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/__pycache__/connection.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/__pycache__/messages.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/__pycache__/messages.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc449b6f19767b75afb2d590036ca9fcd26821d4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/__pycache__/messages.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/__pycache__/router.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/__pycache__/router.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8260c3e40befd39009c6785e93074ffbfe369ff Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/__pycache__/router.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/__pycache__/server.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/__pycache__/server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccf5f962bb620f4f99450b724604dded1eab5a7f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/__pycache__/server.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/__pycache__/utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50b4b90d4a2a702a885508fbedd90021e8351f86 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/__pycache__/utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/client.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/client.py new file mode 100644 index 0000000000000000000000000000000000000000..6e3ea12877842f2679fa036ad5648c4550c28340 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/client.py @@ -0,0 +1,633 @@ +from __future__ import annotations + +import socket +import ssl as ssl_module +import threading +import warnings +from collections.abc import Sequence +from typing import Any, Callable, Literal, TypeVar, cast + +from ..client import ClientProtocol +from ..datastructures import HeadersLike +from ..exceptions import InvalidProxyMessage, InvalidProxyStatus, ProxyError +from ..extensions.base import ClientExtensionFactory +from ..extensions.permessage_deflate import enable_client_permessage_deflate +from ..headers import validate_subprotocols +from ..http11 import USER_AGENT, Response +from ..protocol import CONNECTING, Event +from ..proxy import Proxy, get_proxy, parse_proxy, prepare_connect_request +from ..streams import StreamReader +from ..typing import BytesLike, LoggerLike, Origin, Subprotocol +from ..uri import WebSocketURI, parse_uri +from .connection import Connection +from .utils import Deadline + + +__all__ = ["connect", "unix_connect", "ClientConnection"] + + +class ClientConnection(Connection): + """ + :mod:`threading` implementation of a WebSocket client connection. + + :class:`ClientConnection` provides :meth:`recv` and :meth:`send` methods for + receiving and sending messages. + + It supports iteration to receive messages:: + + for message in websocket: + process(message) + + The iterator exits normally when the connection is closed with code + 1000 (OK) or 1001 (going away) or without a close code. It raises a + :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is + closed with any other code. + + The ``ping_interval``, ``ping_timeout``, ``close_timeout``, and + ``max_queue`` arguments have the same meaning as in :func:`connect`. + + Args: + socket: Socket connected to a WebSocket server. + protocol: Sans-I/O connection. + + """ + + def __init__( + self, + socket: socket.socket, + protocol: ClientProtocol, + *, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + max_queue: int | None | tuple[int | None, int | None] = 16, + ) -> None: + self.protocol: ClientProtocol + self.response_rcvd = threading.Event() + super().__init__( + socket, + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + ) + + def handshake( + self, + additional_headers: HeadersLike | None = None, + user_agent_header: str | None = USER_AGENT, + timeout: float | None = None, + ) -> None: + """ + Perform the opening handshake. + + """ + with self.send_context(expected_state=CONNECTING): + self.request = self.protocol.connect() + if additional_headers is not None: + self.request.headers.update(additional_headers) + if user_agent_header is not None: + self.request.headers.setdefault("User-Agent", user_agent_header) + self.protocol.send_request(self.request) + + if not self.response_rcvd.wait(timeout): + raise TimeoutError("timed out while waiting for handshake response") + + # self.protocol.handshake_exc is set when the connection is lost before + # receiving a response, when the response cannot be parsed, or when the + # response fails the handshake. + + if self.protocol.handshake_exc is not None: + raise self.protocol.handshake_exc + + def process_event(self, event: Event) -> None: + """ + Process one incoming event. + + """ + # First event - handshake response. + if self.response is None: + assert isinstance(event, Response) + self.response = event + self.response_rcvd.set() + # Later events - frames. + else: + super().process_event(event) + + def recv_events(self) -> None: + """ + Read incoming data from the socket and process events. + + """ + try: + super().recv_events() + finally: + # If the connection is closed during the handshake, unblock it. + self.response_rcvd.set() + + +def connect( + uri: str, + *, + # TCP/TLS + sock: socket.socket | None = None, + ssl: ssl_module.SSLContext | None = None, + server_hostname: str | None = None, + # WebSocket + origin: Origin | None = None, + extensions: Sequence[ClientExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + compression: str | None = "deflate", + # HTTP + additional_headers: HeadersLike | None = None, + user_agent_header: str | None = USER_AGENT, + proxy: str | Literal[True] | None = True, + proxy_ssl: ssl_module.SSLContext | None = None, + proxy_server_hostname: str | None = None, + # Timeouts + open_timeout: float | None = 10, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + # Limits + max_size: int | None | tuple[int | None, int | None] = 2**20, + max_queue: int | None | tuple[int | None, int | None] = 16, + # Logging + logger: LoggerLike | None = None, + # Escape hatch for advanced customization + create_connection: type[ClientConnection] | None = None, + **kwargs: Any, +) -> ClientConnection: + """ + Connect to the WebSocket server at ``uri``. + + This function returns a :class:`ClientConnection` instance, which you can + use to send and receive messages. + + :func:`connect` may be used as a context manager:: + + from websockets.sync.client import connect + + with connect(...) as websocket: + ... + + The connection is closed automatically when exiting the context. + + Args: + uri: URI of the WebSocket server. + sock: Preexisting TCP socket. ``sock`` overrides the host and port + from ``uri``. You may call :func:`socket.create_connection` to + create a suitable TCP socket. + ssl: Configuration for enabling TLS on the connection. + server_hostname: Host name for the TLS handshake. ``server_hostname`` + overrides the host name from ``uri``. + origin: Value of the ``Origin`` header, for servers that require it. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + compression: The "permessage-deflate" extension is enabled by default. + Set ``compression`` to :obj:`None` to disable it. See the + :doc:`compression guide <../../topics/compression>` for details. + additional_headers (HeadersLike | None): Arbitrary HTTP headers to add + to the handshake request. + user_agent_header: Value of the ``User-Agent`` request header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. + Setting it to :obj:`None` removes the header. + proxy: If a proxy is configured, it is used by default. Set ``proxy`` + to :obj:`None` to disable the proxy or to the address of a proxy + to override the system configuration. See the :doc:`proxy docs + <../../topics/proxies>` for details. + proxy_ssl: Configuration for enabling TLS on the proxy connection. + proxy_server_hostname: Host name for the TLS handshake with the proxy. + ``proxy_server_hostname`` overrides the host name from ``proxy``. + open_timeout: Timeout for opening the connection in seconds. + :obj:`None` disables the timeout. + ping_interval: Interval between keepalive pings in seconds. + :obj:`None` disables keepalive. + ping_timeout: Timeout for keepalive pings in seconds. + :obj:`None` disables timeouts. + close_timeout: Timeout for closing the connection in seconds. + :obj:`None` disables the timeout. + max_size: Maximum size of incoming messages in bytes. + :obj:`None` disables the limit. You may pass a ``(max_message_size, + max_fragment_size)`` tuple to set different limits for messages and + fragments when you expect long messages sent in short fragments. + max_queue: High-water mark of the buffer where frames are received. + It defaults to 16 frames. The low-water mark defaults to ``max_queue + // 4``. You may pass a ``(high, low)`` tuple to set the high-water + and low-water marks. If you want to disable flow control entirely, + you may set it to ``None``, although that's a bad idea. + logger: Logger for this client. + It defaults to ``logging.getLogger("websockets.client")``. + See the :doc:`logging guide <../../topics/logging>` for details. + create_connection: Factory for the :class:`ClientConnection` managing + the connection. Set it to a wrapper or a subclass to customize + connection handling. + + Any other keyword arguments are passed to :func:`~socket.create_connection`. + + Raises: + InvalidURI: If ``uri`` isn't a valid WebSocket URI. + OSError: If the TCP connection fails. + InvalidHandshake: If the opening handshake fails. + TimeoutError: If the opening handshake times out. + + """ + + # Process parameters + + # Backwards compatibility: ssl used to be called ssl_context. + if ssl is None and "ssl_context" in kwargs: + ssl = kwargs.pop("ssl_context") + warnings.warn( # deprecated in 13.0 - 2024-08-20 + "ssl_context was renamed to ssl", + DeprecationWarning, + ) + + ws_uri = parse_uri(uri) + if not ws_uri.secure and ssl is not None: + raise ValueError("ssl argument is incompatible with a ws:// URI") + + # Private APIs for unix_connect() + unix: bool = kwargs.pop("unix", False) + path: str | None = kwargs.pop("path", None) + + if unix: + if path is None and sock is None: + raise ValueError("missing path argument") + elif path is not None and sock is not None: + raise ValueError("path and sock arguments are incompatible") + + if subprotocols is not None: + validate_subprotocols(subprotocols) + + if compression == "deflate": + extensions = enable_client_permessage_deflate(extensions) + elif compression is not None: + raise ValueError(f"unsupported compression: {compression}") + + if unix: + proxy = None + if sock is not None: + proxy = None + if proxy is True: + proxy = get_proxy(ws_uri) + + # Calculate timeouts on the TCP, TLS, and WebSocket handshakes. + # The TCP and TLS timeouts must be set on the socket, then removed + # to avoid conflicting with the WebSocket timeout in handshake(). + deadline = Deadline(open_timeout) + + if create_connection is None: + create_connection = ClientConnection + + try: + # Connect socket + + if sock is None: + if unix: + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + sock.settimeout(deadline.timeout()) + assert path is not None # mypy cannot figure this out + sock.connect(path) + elif proxy is not None: + proxy_parsed = parse_proxy(proxy) + if proxy_parsed.scheme[:5] == "socks": + # Connect to the server through the proxy. + sock = connect_socks_proxy( + proxy_parsed, + ws_uri, + deadline, + # websockets is consistent with the socket module while + # python_socks is consistent across implementations. + local_addr=kwargs.pop("source_address", None), + ) + elif proxy_parsed.scheme[:4] == "http": + # Validate the proxy_ssl argument. + if proxy_parsed.scheme != "https" and proxy_ssl is not None: + raise ValueError( + "proxy_ssl argument is incompatible with an http:// proxy" + ) + # Connect to the server through the proxy. + sock = connect_http_proxy( + proxy_parsed, + ws_uri, + deadline, + user_agent_header=user_agent_header, + ssl=proxy_ssl, + server_hostname=proxy_server_hostname, + **kwargs, + ) + else: + raise AssertionError("unsupported proxy") + else: + kwargs.setdefault("timeout", deadline.timeout()) + sock = socket.create_connection( + (ws_uri.host, ws_uri.port), + **kwargs, + ) + sock.settimeout(None) + + # Disable Nagle algorithm + + if not unix: + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True) + + # Initialize TLS wrapper and perform TLS handshake + + if ws_uri.secure: + if ssl is None: + ssl = ssl_module.create_default_context() + if server_hostname is None: + server_hostname = ws_uri.host + sock.settimeout(deadline.timeout()) + if proxy_ssl is None: + sock = ssl.wrap_socket(sock, server_hostname=server_hostname) + else: + sock_2 = SSLSSLSocket(sock, ssl, server_hostname=server_hostname) + # Let's pretend that sock is a socket, even though it isn't. + sock = cast(socket.socket, sock_2) + sock.settimeout(None) + + # Initialize WebSocket protocol + + protocol = ClientProtocol( + ws_uri, + origin=origin, + extensions=extensions, + subprotocols=subprotocols, + max_size=max_size, + logger=logger, + ) + + # Initialize WebSocket connection + + connection = create_connection( + sock, + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + ) + except Exception: + if sock is not None: + sock.close() + raise + + try: + connection.handshake( + additional_headers, + user_agent_header, + deadline.timeout(), + ) + except Exception: + connection.close_socket() + connection.recv_events_thread.join() + raise + + connection.start_keepalive() + return connection + + +def unix_connect( + path: str | None = None, + uri: str | None = None, + **kwargs: Any, +) -> ClientConnection: + """ + Connect to a WebSocket server listening on a Unix socket. + + This function accepts the same keyword arguments as :func:`connect`. + + It's only available on Unix. + + It's mainly useful for debugging servers listening on Unix sockets. + + Args: + path: File system path to the Unix socket. + uri: URI of the WebSocket server. ``uri`` defaults to + ``ws://localhost/`` or, when a ``ssl`` is provided, to + ``wss://localhost/``. + + """ + if uri is None: + # Backwards compatibility: ssl used to be called ssl_context. + if kwargs.get("ssl") is None and kwargs.get("ssl_context") is None: + uri = "ws://localhost/" + else: + uri = "wss://localhost/" + return connect(uri=uri, unix=True, path=path, **kwargs) + + +try: + from python_socks import ProxyType + from python_socks.sync import Proxy as SocksProxy + +except ImportError: + + def connect_socks_proxy( + proxy: Proxy, + ws_uri: WebSocketURI, + deadline: Deadline, + **kwargs: Any, + ) -> socket.socket: + raise ImportError("connecting through a SOCKS proxy requires python-socks") + +else: + SOCKS_PROXY_TYPES = { + "socks5h": ProxyType.SOCKS5, + "socks5": ProxyType.SOCKS5, + "socks4a": ProxyType.SOCKS4, + "socks4": ProxyType.SOCKS4, + } + + SOCKS_PROXY_RDNS = { + "socks5h": True, + "socks5": False, + "socks4a": True, + "socks4": False, + } + + def connect_socks_proxy( + proxy: Proxy, + ws_uri: WebSocketURI, + deadline: Deadline, + **kwargs: Any, + ) -> socket.socket: + """Connect via a SOCKS proxy and return the socket.""" + socks_proxy = SocksProxy( + SOCKS_PROXY_TYPES[proxy.scheme], + proxy.host, + proxy.port, + proxy.username, + proxy.password, + SOCKS_PROXY_RDNS[proxy.scheme], + ) + kwargs.setdefault("timeout", deadline.timeout()) + # connect() is documented to raise OSError and TimeoutError. + # Wrap other exceptions in ProxyError, a subclass of InvalidHandshake. + try: + return socks_proxy.connect(ws_uri.host, ws_uri.port, **kwargs) + except (OSError, TimeoutError, socket.timeout): + raise + except Exception as exc: + raise ProxyError("failed to connect to SOCKS proxy") from exc + + +def read_connect_response(sock: socket.socket, deadline: Deadline) -> Response: + reader = StreamReader() + parser = Response.parse( + reader.read_line, + reader.read_exact, + reader.read_to_eof, + proxy=True, + ) + try: + while True: + sock.settimeout(deadline.timeout()) + data = sock.recv(4096) + if data: + reader.feed_data(data) + else: + reader.feed_eof() + next(parser) + except StopIteration as exc: + assert isinstance(exc.value, Response) # help mypy + response = exc.value + if 200 <= response.status_code < 300: + return response + else: + raise InvalidProxyStatus(response) + except socket.timeout: + raise TimeoutError("timed out while connecting to HTTP proxy") + except Exception as exc: + raise InvalidProxyMessage( + "did not receive a valid HTTP response from proxy" + ) from exc + finally: + sock.settimeout(None) + + +def connect_http_proxy( + proxy: Proxy, + ws_uri: WebSocketURI, + deadline: Deadline, + *, + user_agent_header: str | None = None, + ssl: ssl_module.SSLContext | None = None, + server_hostname: str | None = None, + **kwargs: Any, +) -> socket.socket: + # Connect socket + + kwargs.setdefault("timeout", deadline.timeout()) + sock = socket.create_connection((proxy.host, proxy.port), **kwargs) + + # Initialize TLS wrapper and perform TLS handshake + + if proxy.scheme == "https": + if ssl is None: + ssl = ssl_module.create_default_context() + if server_hostname is None: + server_hostname = proxy.host + sock.settimeout(deadline.timeout()) + sock = ssl.wrap_socket(sock, server_hostname=server_hostname) + sock.settimeout(None) + + # Send CONNECT request to the proxy and read response. + + sock.sendall(prepare_connect_request(proxy, ws_uri, user_agent_header)) + try: + read_connect_response(sock, deadline) + except Exception: + sock.close() + raise + + return sock + + +T = TypeVar("T") +F = TypeVar("F", bound=Callable[..., T]) + + +class SSLSSLSocket: + """ + Socket-like object providing TLS-in-TLS. + + Only methods that are used by websockets are implemented. + + """ + + recv_bufsize = 65536 + + def __init__( + self, + sock: socket.socket, + ssl_context: ssl_module.SSLContext, + server_hostname: str | None = None, + ) -> None: + self.incoming = ssl_module.MemoryBIO() + self.outgoing = ssl_module.MemoryBIO() + self.ssl_socket = sock + self.ssl_object = ssl_context.wrap_bio( + self.incoming, + self.outgoing, + server_hostname=server_hostname, + ) + self.run_io(self.ssl_object.do_handshake) + + def run_io(self, func: Callable[..., T], *args: Any) -> T: + while True: + want_read = False + want_write = False + try: + result = func(*args) + except ssl_module.SSLWantReadError: + want_read = True + except ssl_module.SSLWantWriteError: # pragma: no cover + want_write = True + + # Write outgoing data in all cases. + data = self.outgoing.read() + if data: + self.ssl_socket.sendall(data) + + # Read incoming data and retry on SSLWantReadError. + if want_read: + data = self.ssl_socket.recv(self.recv_bufsize) + if data: + self.incoming.write(data) + else: + self.incoming.write_eof() + continue + # Retry after writing outgoing data on SSLWantWriteError. + if want_write: # pragma: no cover + continue + # Return result if no error happened. + return result + + def recv(self, buflen: int) -> bytes: + try: + return self.run_io(self.ssl_object.read, buflen) + except ssl_module.SSLEOFError: + return b"" # always ignore ragged EOFs + + def send(self, data: BytesLike) -> int: + return self.run_io(self.ssl_object.write, data) + + def sendall(self, data: BytesLike) -> None: + # adapted from ssl_module.SSLSocket.sendall() + count = 0 + with memoryview(data) as view, view.cast("B") as byte_view: + amount = len(byte_view) + while count < amount: + count += self.send(byte_view[count:]) + + # recv_into(), recvfrom(), recvfrom_into(), sendto(), unwrap(), and the + # flags argument aren't implemented because websockets doesn't need them. + + def __getattr__(self, name: str) -> Any: + return getattr(self.ssl_socket, name) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/connection.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..928303c94a8ba71dd3ec5fbb949b61c5a90b84f0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/connection.py @@ -0,0 +1,1078 @@ +from __future__ import annotations + +import contextlib +import logging +import random +import socket +import struct +import threading +import time +import uuid +from collections.abc import Iterable, Iterator, Mapping +from types import TracebackType +from typing import Any, Literal, overload + +from ..exceptions import ( + ConcurrencyError, + ConnectionClosed, + ConnectionClosedOK, + ProtocolError, +) +from ..frames import DATA_OPCODES, CloseCode, Frame, Opcode +from ..http11 import Request, Response +from ..protocol import CLOSED, OPEN, Event, Protocol, State +from ..typing import BytesLike, Data, DataLike, LoggerLike, Subprotocol +from .messages import Assembler +from .utils import Deadline + + +__all__ = ["Connection"] + + +class Connection: + """ + :mod:`threading` implementation of a WebSocket connection. + + :class:`Connection` provides APIs shared between WebSocket servers and + clients. + + You shouldn't use it directly. Instead, use + :class:`~websockets.sync.client.ClientConnection` or + :class:`~websockets.sync.server.ServerConnection`. + + """ + + recv_bufsize = 65536 + + def __init__( + self, + socket: socket.socket, + protocol: Protocol, + *, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + max_queue: int | None | tuple[int | None, int | None] = 16, + ) -> None: + self.socket = socket + self.protocol = protocol + self.ping_interval = ping_interval + self.ping_timeout = ping_timeout + self.close_timeout = close_timeout + if isinstance(max_queue, int) or max_queue is None: + max_queue_high, max_queue_low = max_queue, None + else: + max_queue_high, max_queue_low = max_queue + + # Inject reference to this instance in the protocol's logger. + self.protocol.logger = logging.LoggerAdapter( + self.protocol.logger, + {"websocket": self}, + ) + + # Copy attributes from the protocol for convenience. + self.id: uuid.UUID = self.protocol.id + """Unique identifier of the connection. Useful in logs.""" + self.logger: LoggerLike = self.protocol.logger + """Logger for this connection.""" + self.debug = self.protocol.debug + + # HTTP handshake request and response. + self.request: Request | None = None + """Opening handshake request.""" + self.response: Response | None = None + """Opening handshake response.""" + + # Mutex serializing interactions with the protocol. + self.protocol_mutex = threading.Lock() + + # Lock stopping reads when the assembler buffer is full. + self.recv_flow_control = threading.Lock() + + # Assembler turning frames into messages and serializing reads. + self.recv_messages = Assembler( + max_queue_high, + max_queue_low, + pause=self.recv_flow_control.acquire, + resume=self.recv_flow_control.release, + ) + + # Deadline for the closing handshake. + self.close_deadline: Deadline | None = None + + # Whether we are busy sending a fragmented message. + self.send_in_progress = False + + # Mapping of ping IDs to pong waiters, in chronological order. + self.pending_pings: dict[bytes, tuple[threading.Event, float, bool]] = {} + + self.latency: float = 0.0 + """ + Latency of the connection, in seconds. + + Latency is defined as the round-trip time of the connection. It is + measured by sending a Ping frame and waiting for a matching Pong frame. + Before the first measurement, :attr:`latency` is ``0.0``. + + By default, websockets enables a :ref:`keepalive ` mechanism + that sends Ping frames automatically at regular intervals. You can also + send Ping frames and measure latency with :meth:`ping`. + """ + + # Thread that sends keepalive pings. None when ping_interval is None. + self.keepalive_thread: threading.Thread | None = None + + # Exception raised while reading from the connection, to be chained to + # ConnectionClosed in order to show why the TCP connection dropped. + self.recv_exc: BaseException | None = None + + # Receiving events from the socket. This thread is marked as daemon to + # allow creating a connection in a non-daemon thread and using it in a + # daemon thread. This mustn't prevent the interpreter from exiting. + self.recv_events_thread = threading.Thread( + target=self.recv_events, + daemon=True, + ) + + # Start recv_events only after all attributes are initialized. + self.recv_events_thread.start() + + # Public attributes + + @property + def local_address(self) -> Any: + """ + Local address of the connection. + + For IPv4 connections, this is a ``(host, port)`` tuple. + + The format of the address depends on the address family. + See :meth:`~socket.socket.getsockname`. + + """ + return self.socket.getsockname() + + @property + def remote_address(self) -> Any: + """ + Remote address of the connection. + + For IPv4 connections, this is a ``(host, port)`` tuple. + + The format of the address depends on the address family. + See :meth:`~socket.socket.getpeername`. + + """ + return self.socket.getpeername() + + @property + def state(self) -> State: + """ + State of the WebSocket connection, defined in :rfc:`6455`. + + This attribute is provided for completeness. Typical applications + shouldn't check its value. Instead, they should call :meth:`~recv` or + :meth:`send` and handle :exc:`~websockets.exceptions.ConnectionClosed` + exceptions. + + """ + return self.protocol.state + + @property + def subprotocol(self) -> Subprotocol | None: + """ + Subprotocol negotiated during the opening handshake. + + :obj:`None` if no subprotocol was negotiated. + + """ + return self.protocol.subprotocol + + @property + def close_code(self) -> int | None: + """ + State of the WebSocket connection, defined in :rfc:`6455`. + + This attribute is provided for completeness. Typical applications + shouldn't check its value. Instead, they should inspect attributes + of :exc:`~websockets.exceptions.ConnectionClosed` exceptions. + + """ + return self.protocol.close_code + + @property + def close_reason(self) -> str | None: + """ + State of the WebSocket connection, defined in :rfc:`6455`. + + This attribute is provided for completeness. Typical applications + shouldn't check its value. Instead, they should inspect attributes + of :exc:`~websockets.exceptions.ConnectionClosed` exceptions. + + """ + return self.protocol.close_reason + + # Public methods + + def __enter__(self) -> Connection: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + if exc_type is None: + self.close() + else: + self.close(CloseCode.INTERNAL_ERROR) + + def __iter__(self) -> Iterator[Data]: + """ + Iterate on incoming messages. + + The iterator calls :meth:`recv` and yields messages in an infinite loop. + + It exits when the connection is closed normally. It raises a + :exc:`~websockets.exceptions.ConnectionClosedError` exception after a + protocol error or a network failure. + + """ + try: + while True: + yield self.recv() + except ConnectionClosedOK: + return + + # This overload structure is required to avoid the error: + # "parameter without a default follows parameter with a default" + + @overload + def recv(self, timeout: float | None, decode: Literal[True]) -> str: ... + + @overload + def recv(self, timeout: float | None, decode: Literal[False]) -> bytes: ... + + @overload + def recv(self, timeout: float | None = None, *, decode: Literal[True]) -> str: ... + + @overload + def recv( + self, timeout: float | None = None, *, decode: Literal[False] + ) -> bytes: ... + + @overload + def recv( + self, timeout: float | None = None, decode: bool | None = None + ) -> Data: ... + + def recv(self, timeout: float | None = None, decode: bool | None = None) -> Data: + """ + Receive the next message. + + When the connection is closed, :meth:`recv` raises + :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises + :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal closure + and :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol + error or a network failure. This is how you detect the end of the + message stream. + + If ``timeout`` is :obj:`None`, block until a message is received. If + ``timeout`` is set, wait up to ``timeout`` seconds for a message to be + received and return it, else raise :exc:`TimeoutError`. If ``timeout`` + is ``0`` or negative, check if a message has been received already and + return it, else raise :exc:`TimeoutError`. + + When the message is fragmented, :meth:`recv` waits until all fragments + are received, reassembles them, and returns the whole message. + + Args: + timeout: Timeout for receiving a message in seconds. + decode: Set this flag to override the default behavior of returning + :class:`str` or :class:`bytes`. See below for details. + + Returns: + A string (:class:`str`) for a Text_ frame or a bytestring + (:class:`bytes`) for a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + You may override this behavior with the ``decode`` argument: + + * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames and + return a bytestring (:class:`bytes`). This improves performance + when decoding isn't needed, for example if the message contains + JSON and you're using a JSON library that expects a bytestring. + * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames and + return strings (:class:`str`). This may be useful for servers that + send binary frames instead of text frames. + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If two threads call :meth:`recv` or + :meth:`recv_streaming` concurrently. + + """ + try: + return self.recv_messages.get(timeout, decode) + except EOFError: + pass + # fallthrough + except ConcurrencyError: + raise ConcurrencyError( + "cannot call recv while another thread " + "is already running recv or recv_streaming" + ) from None + except UnicodeDecodeError as exc: + with self.send_context(): + self.protocol.fail( + CloseCode.INVALID_DATA, + f"{exc.reason} at position {exc.start}", + ) + # fallthrough + + # Wait for the protocol state to be CLOSED before accessing close_exc. + self.recv_events_thread.join() + raise self.protocol.close_exc from self.recv_exc + + @overload + def recv_streaming(self, decode: Literal[True]) -> Iterator[str]: ... + + @overload + def recv_streaming(self, decode: Literal[False]) -> Iterator[bytes]: ... + + @overload + def recv_streaming(self, decode: bool | None = None) -> Iterator[Data]: ... + + def recv_streaming(self, decode: bool | None = None) -> Iterator[Data]: + """ + Receive the next message frame by frame. + + This method is designed for receiving fragmented messages. It returns an + iterator that yields each fragment as it is received. This iterator must + be fully consumed. Else, future calls to :meth:`recv` or + :meth:`recv_streaming` will raise + :exc:`~websockets.exceptions.ConcurrencyError`, making the connection + unusable. + + :meth:`recv_streaming` raises the same exceptions as :meth:`recv`. + + Args: + decode: Set this flag to override the default behavior of returning + :class:`str` or :class:`bytes`. See below for details. + + Returns: + An iterator of strings (:class:`str`) for a Text_ frame or + bytestrings (:class:`bytes`) for a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + You may override this behavior with the ``decode`` argument: + + * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames and + yield bytestrings (:class:`bytes`). This improves performance + when decoding isn't needed. + * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames and + yield strings (:class:`str`). This may be useful for servers that + send binary frames instead of text frames. + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If two threads call :meth:`recv` or + :meth:`recv_streaming` concurrently. + + """ + try: + yield from self.recv_messages.get_iter(decode) + return + except EOFError: + pass + # fallthrough + except ConcurrencyError: + raise ConcurrencyError( + "cannot call recv_streaming while another thread " + "is already running recv or recv_streaming" + ) from None + except UnicodeDecodeError as exc: + with self.send_context(): + self.protocol.fail( + CloseCode.INVALID_DATA, + f"{exc.reason} at position {exc.start}", + ) + # fallthrough + + # Wait for the protocol state to be CLOSED before accessing close_exc. + self.recv_events_thread.join() + raise self.protocol.close_exc from self.recv_exc + + def send( + self, + message: DataLike | Iterable[DataLike], + text: bool | None = None, + ) -> None: + """ + Send a message. + + A string (:class:`str`) is sent as a Text_ frame. A bytestring or + bytes-like object (:class:`bytes`, :class:`bytearray`, or + :class:`memoryview`) is sent as a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + You may override this behavior with the ``text`` argument: + + * Set ``text=True`` to send an UTF-8 bytestring or bytes-like object + (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) in a + Text_ frame. This improves performance when the message is already + UTF-8 encoded, for example if the message contains JSON and you're + using a JSON library that produces a bytestring. + * Set ``text=False`` to send a string (:class:`str`) in a Binary_ + frame. This may be useful for servers that expect binary frames + instead of text frames. + + :meth:`send` also accepts an iterable of strings, bytestrings, or + bytes-like objects to enable fragmentation_. Each item is treated as a + message fragment and sent in its own frame. All items must be of the + same type, or else :meth:`send` will raise a :exc:`TypeError` and the + connection will be closed. + + .. _fragmentation: https://datatracker.ietf.org/doc/html/rfc6455#section-5.4 + + :meth:`send` rejects dict-like objects because this is often an error. + (If you really want to send the keys of a dict-like object as fragments, + call its :meth:`~dict.keys` method and pass the result to :meth:`send`.) + + When the connection is closed, :meth:`send` raises + :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it + raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal + connection closure and + :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol + error or a network failure. + + Args: + message: Message to send. + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If the connection is sending a fragmented message. + TypeError: If ``message`` doesn't have a supported type. + + """ + # Unfragmented message -- this case must be handled first because + # strings and bytes-like objects are iterable. + + if isinstance(message, str): + with self.send_context(): + if self.send_in_progress: + raise ConcurrencyError( + "cannot call send while another thread is already running send" + ) + if text is False: + self.protocol.send_binary(message.encode()) + else: + self.protocol.send_text(message.encode()) + + elif isinstance(message, BytesLike): + with self.send_context(): + if self.send_in_progress: + raise ConcurrencyError( + "cannot call send while another thread is already running send" + ) + if text is True: + self.protocol.send_text(message) + else: + self.protocol.send_binary(message) + + # Catch a common mistake -- passing a dict to send(). + + elif isinstance(message, Mapping): + raise TypeError("data is a dict-like object") + + # Fragmented message -- regular iterator. + + elif isinstance(message, Iterable): + chunks = iter(message) + try: + chunk = next(chunks) + except StopIteration: + return + + try: + # First fragment. + if isinstance(chunk, str): + with self.send_context(): + if self.send_in_progress: + raise ConcurrencyError( + "cannot call send while another thread " + "is already running send" + ) + self.send_in_progress = True + if text is False: + self.protocol.send_binary(chunk.encode(), fin=False) + else: + self.protocol.send_text(chunk.encode(), fin=False) + encode = True + elif isinstance(chunk, BytesLike): + with self.send_context(): + if self.send_in_progress: + raise ConcurrencyError( + "cannot call send while another thread " + "is already running send" + ) + self.send_in_progress = True + if text is True: + self.protocol.send_text(chunk, fin=False) + else: + self.protocol.send_binary(chunk, fin=False) + encode = False + else: + raise TypeError("iterable must contain bytes or str") + + # Other fragments + for chunk in chunks: + if isinstance(chunk, str) and encode: + with self.send_context(): + assert self.send_in_progress + self.protocol.send_continuation(chunk.encode(), fin=False) + elif isinstance(chunk, BytesLike) and not encode: + with self.send_context(): + assert self.send_in_progress + self.protocol.send_continuation(chunk, fin=False) + else: + raise TypeError("iterable must contain uniform types") + + # Final fragment. + with self.send_context(): + self.protocol.send_continuation(b"", fin=True) + self.send_in_progress = False + + except ConcurrencyError: + # We didn't start sending a fragmented message. + # The connection is still usable. + raise + + except Exception: + # We're half-way through a fragmented message and we can't + # complete it. This makes the connection unusable. + with self.send_context(): + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "error in fragmented message", + ) + raise + + else: + raise TypeError("data must be str, bytes, or iterable") + + def close( + self, + code: CloseCode | int = CloseCode.NORMAL_CLOSURE, + reason: str = "", + ) -> None: + """ + Perform the closing handshake. + + :meth:`close` waits for the other end to complete the handshake and + for the TCP connection to terminate. + + :meth:`close` is idempotent: it doesn't do anything once the + connection is closed. + + Args: + code: WebSocket close code. + reason: WebSocket close reason. + + """ + try: + # The context manager takes care of waiting for the TCP connection + # to terminate after calling a method that sends a close frame. + with self.send_context(): + if self.send_in_progress: + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "close during fragmented message", + ) + else: + self.protocol.send_close(code, reason) + except ConnectionClosed: + # Ignore ConnectionClosed exceptions raised from send_context(). + # They mean that the connection is closed, which was the goal. + pass + + def ping( + self, + data: DataLike | None = None, + ack_on_close: bool = False, + ) -> threading.Event: + """ + Send a Ping_. + + .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2 + + A ping may serve as a keepalive or as a check that the remote endpoint + received all messages up to this point + + Args: + data: Payload of the ping. A :class:`str` will be encoded to UTF-8. + If ``data`` is :obj:`None`, the payload is four random bytes. + ack_on_close: when this option is :obj:`True`, the event will also + be set when the connection is closed. While this avoids getting + stuck waiting for a pong that will never arrive, it requires + checking that the state of the connection is still ``OPEN`` to + confirm that a pong was received, rather than the connection + being closed. + + Returns: + An event that will be set when the corresponding pong is received. + You can ignore it if you don't intend to wait. + + :: + + pong_received = ws.ping() + # only if you want to wait for the corresponding pong + pong_received.wait() + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If another ping was sent with the same data and + the corresponding pong wasn't received yet. + + """ + if isinstance(data, BytesLike): + data = bytes(data) + elif isinstance(data, str): + data = data.encode() + elif data is not None: + raise TypeError("data must be str or bytes-like") + + with self.send_context(): + # Protect against duplicates if a payload is explicitly set. + if data in self.pending_pings: + raise ConcurrencyError("already waiting for a pong with the same data") + + # Generate a unique random payload otherwise. + while data is None or data in self.pending_pings: + data = struct.pack("!I", random.getrandbits(32)) + + pong_received = threading.Event() + ping_timestamp = time.monotonic() + self.pending_pings[data] = (pong_received, ping_timestamp, ack_on_close) + self.protocol.send_ping(data) + return pong_received + + def pong(self, data: DataLike = b"") -> None: + """ + Send a Pong_. + + .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3 + + An unsolicited pong may serve as a unidirectional heartbeat. + + Args: + data: Payload of the pong. A :class:`str` will be encoded to UTF-8. + + Raises: + ConnectionClosed: When the connection is closed. + + """ + if isinstance(data, BytesLike): + data = bytes(data) + elif isinstance(data, str): + data = data.encode() + else: + raise TypeError("data must be str or bytes-like") + + with self.send_context(): + self.protocol.send_pong(data) + + # Private methods + + def process_event(self, event: Event) -> None: + """ + Process one incoming event. + + This method is overridden in subclasses to handle the handshake. + + """ + assert isinstance(event, Frame) + if event.opcode in DATA_OPCODES: + self.recv_messages.put(event) + + if event.opcode is Opcode.PONG: + self.acknowledge_pings(bytes(event.data)) + + def acknowledge_pings(self, data: bytes) -> None: + """ + Acknowledge pings when receiving a pong. + + """ + with self.protocol_mutex: + # Ignore unsolicited pong. + if data not in self.pending_pings: + return + + pong_timestamp = time.monotonic() + + # Sending a pong for only the most recent ping is legal. + # Acknowledge all previous pings too in that case. + ping_id = None + ping_ids = [] + for ping_id, ( + pong_received, + ping_timestamp, + _ack_on_close, + ) in self.pending_pings.items(): + ping_ids.append(ping_id) + pong_received.set() + if ping_id == data: + self.latency = pong_timestamp - ping_timestamp + break + else: + raise AssertionError("solicited pong not found in pings") + + # Remove acknowledged pings from self.pending_pings. + for ping_id in ping_ids: + del self.pending_pings[ping_id] + + def terminate_pending_pings(self) -> None: + """ + Acknowledge pending pings when the connection is closed. + + """ + assert self.protocol_mutex.locked() + assert self.protocol.state is CLOSED + + for pong_received, _ping_timestamp, ack_on_close in self.pending_pings.values(): + if ack_on_close: + pong_received.set() + + self.pending_pings.clear() + + def keepalive(self) -> None: + """ + Send a Ping frame and wait for a Pong frame at regular intervals. + + """ + assert self.ping_interval is not None + try: + while True: + # If self.ping_timeout > self.latency > self.ping_interval, + # pings will be sent immediately after receiving pongs. + # The period will be longer than self.ping_interval. + self.recv_events_thread.join(self.ping_interval - self.latency) + if not self.recv_events_thread.is_alive(): + break + + try: + pong_received = self.ping(ack_on_close=True) + except ConnectionClosed: + break + if self.debug: + self.logger.debug("% sent keepalive ping") + + if self.ping_timeout is not None: + if pong_received.wait(self.ping_timeout): + if self.debug: + self.logger.debug("% received keepalive pong") + else: + if self.debug: + self.logger.debug("- timed out waiting for keepalive pong") + with self.send_context(): + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "keepalive ping timeout", + ) + break + except Exception: + self.logger.error("keepalive ping failed", exc_info=True) + + def start_keepalive(self) -> None: + """ + Run :meth:`keepalive` in a thread, unless keepalive is disabled. + + """ + if self.ping_interval is not None: + # This thread is marked as daemon like self.recv_events_thread. + self.keepalive_thread = threading.Thread( + target=self.keepalive, + daemon=True, + ) + self.keepalive_thread.start() + + def recv_events(self) -> None: + """ + Read incoming data from the socket and process events. + + Run this method in a thread as long as the connection is alive. + + ``recv_events()`` exits immediately when ``self.socket`` is closed. + + """ + try: + while True: + try: + # If the assembler buffer is full, block until it drains. + with self.recv_flow_control: + pass + if self.close_deadline is not None: + self.socket.settimeout(self.close_deadline.timeout()) + data = self.socket.recv(self.recv_bufsize) + except Exception as exc: + if self.debug: + self.logger.debug( + "! error while receiving data", + exc_info=True, + ) + # When the closing handshake is initiated by our side, + # recv() may block until send_context() closes the socket. + # In that case, send_context() already set recv_exc. + # Calling set_recv_exc() avoids overwriting it. + with self.protocol_mutex: + self.set_recv_exc(exc) + break + + if data == b"": + break + + # Acquire the connection lock. + with self.protocol_mutex: + # Feed incoming data to the protocol. + self.protocol.receive_data(data) + + # This isn't expected to raise an exception. + events = self.protocol.events_received() + + # Write outgoing data to the socket. + try: + self.send_data() + except Exception as exc: + if self.debug: + self.logger.debug( + "! error while sending data", + exc_info=True, + ) + # Similarly to the above, avoid overriding an exception + # set by send_context(), in case of a race condition + # i.e. send_context() closes the socket after recv() + # returns above but before send_data() calls send(). + self.set_recv_exc(exc) + break + + # If needed, set the close deadline based on the close timeout. + if self.protocol.close_expected(): + if self.close_deadline is None: + self.close_deadline = Deadline(self.close_timeout) + + # Unlock conn_mutex before processing events. Else, the + # application can't send messages in response to events. + + # If self.send_data raised an exception, then events are lost. + # Given that automatic responses write small amounts of data, + # this should be uncommon, so we don't handle the edge case. + + for event in events: + # This isn't expected to raise an exception. + self.process_event(event) + + # Breaking out of the while True: ... loop means that we believe + # that the socket doesn't work anymore. + + with self.protocol_mutex: + # Feed the end of the data stream to the protocol. + self.protocol.receive_eof() + + # This isn't expected to raise an exception. + events = self.protocol.events_received() + + # There is no error handling because send_data() can only write + # the end of the data stream and it handles errors by itself. + self.send_data() + + # This code path is triggered when receiving an HTTP response + # without a Content-Length header. This is the only case where + # reading until EOF generates an event; all other events have + # a known length. Ignore for coverage measurement because tests + # are in test_client.py rather than test_connection.py. + for event in events: # pragma: no cover + # This isn't expected to raise an exception. + self.process_event(event) + + except Exception as exc: + # This branch should never run. It's a safety net in case of bugs. + self.logger.error("unexpected internal error", exc_info=True) + with self.protocol_mutex: + self.set_recv_exc(exc) + finally: + # This isn't expected to raise an exception. + self.close_socket() + + @contextlib.contextmanager + def send_context( + self, + *, + expected_state: State = OPEN, # CONNECTING during the opening handshake + ) -> Iterator[None]: + """ + Create a context for writing to the connection from user code. + + On entry, :meth:`send_context` acquires the connection lock and checks + that the connection is open; on exit, it writes outgoing data to the + socket and releases the connection lock:: + + with self.send_context(): + self.protocol.send_text(message.encode()) + + When the connection isn't open on entry, when the connection is expected + to close on exit, or when an unexpected error happens, terminating the + connection, :meth:`send_context` waits until the connection is closed + then raises :exc:`~websockets.exceptions.ConnectionClosed`. + + """ + # Should we wait until the connection is closed? + wait_for_close = False + # Should we close the socket and raise ConnectionClosed? + raise_close_exc = False + # What exception should we chain ConnectionClosed to? + original_exc: BaseException | None = None + + # Acquire the protocol lock. + with self.protocol_mutex: + if self.protocol.state is expected_state: + # Let the caller interact with the protocol. + try: + yield + except (ProtocolError, ConcurrencyError): + # The protocol state wasn't changed. Exit immediately. + raise + except Exception as exc: + self.logger.error("unexpected internal error", exc_info=True) + # This branch should never run. It's a safety net in case of + # bugs. Since we don't know what happened, we will close the + # connection and raise the exception to the caller. + wait_for_close = False + raise_close_exc = True + original_exc = exc + else: + # Check if the connection is expected to close soon. + if self.protocol.close_expected(): + wait_for_close = True + # Set the close deadline based on the close timeout. + # Since we tested earlier that protocol.state is OPEN + # (or CONNECTING) and we didn't release protocol_mutex, + # self.close_deadline is still None. + assert self.close_deadline is None + self.close_deadline = Deadline(self.close_timeout) + # Write outgoing data to the socket. + try: + self.send_data() + except Exception as exc: + if self.debug: + self.logger.debug( + "! error while sending data", + exc_info=True, + ) + # While the only expected exception here is OSError, + # other exceptions would be treated identically. + wait_for_close = False + raise_close_exc = True + original_exc = exc + + else: # self.protocol.state is not expected_state + # Minor layering violation: we assume that the connection + # will be closing soon if it isn't in the expected state. + wait_for_close = True + # Calculate close_deadline if it wasn't set yet. + if self.close_deadline is None: + self.close_deadline = Deadline(self.close_timeout) + raise_close_exc = True + + # To avoid a deadlock, release the connection lock by exiting the + # context manager before waiting for recv_events() to terminate. + + # If the connection is expected to close soon and the close timeout + # elapses, close the socket to terminate the connection. + if wait_for_close: + # Thread.join() returns immediately if timeout is negative. + assert self.close_deadline is not None + timeout = self.close_deadline.timeout(raise_if_elapsed=False) + self.recv_events_thread.join(timeout) + if self.recv_events_thread.is_alive(): + # There's no risk of overwriting another error because + # original_exc is never set when wait_for_close is True. + assert original_exc is None + original_exc = TimeoutError("timed out while closing connection") + # Set recv_exc before closing the socket in order to get + # proper exception reporting. + raise_close_exc = True + with self.protocol_mutex: + self.set_recv_exc(original_exc) + + # If an error occurred, close the socket to terminate the connection and + # raise an exception. + if raise_close_exc: + self.close_socket() + # Wait for the protocol state to be CLOSED before accessing close_exc. + self.recv_events_thread.join() + raise self.protocol.close_exc from original_exc + + def send_data(self) -> None: + """ + Send outgoing data. + + This method requires holding protocol_mutex. + + """ + assert self.protocol_mutex.locked() + for data in self.protocol.data_to_send(): + if data: + if self.close_deadline is not None: + self.socket.settimeout(self.close_deadline.timeout()) + self.socket.sendall(data) + else: + try: + self.socket.shutdown(socket.SHUT_WR) + except OSError: # socket already closed + pass + + def set_recv_exc(self, exc: BaseException | None) -> None: + """ + Set recv_exc, if not set yet. + + This method requires holding protocol_mutex and must be called only from + the thread running recv_events(). + + """ + assert self.protocol_mutex.locked() + if self.recv_exc is None: + self.recv_exc = exc + + def close_socket(self) -> None: + """ + Shutdown and close socket. Close message assembler. + + Calling close_socket() guarantees that recv_events() terminates. Indeed, + recv_events() may block only on socket.recv() or on recv_messages.put(). + + """ + # shutdown() is required to interrupt recv() on Linux. + try: + self.socket.shutdown(socket.SHUT_RDWR) + except OSError: # socket already closed + pass + self.socket.close() + + # Calling protocol.receive_eof() is safe because it's idempotent. + # This guarantees that the protocol state becomes CLOSED. + with self.protocol_mutex: + self.protocol.receive_eof() + assert self.protocol.state is CLOSED + + # Abort recv() with a ConnectionClosed exception. + self.recv_messages.close() + + # Acknowledge pings sent with the ack_on_close option. + self.terminate_pending_pings() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/messages.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/messages.py new file mode 100644 index 0000000000000000000000000000000000000000..127f44430640de1e70effbfeaf1a989518276b42 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/messages.py @@ -0,0 +1,348 @@ +from __future__ import annotations + +import codecs +import queue +import threading +from typing import Any, Callable, Iterable, Iterator, Literal, overload + +from ..exceptions import ConcurrencyError +from ..frames import OP_BINARY, OP_CONT, OP_TEXT, Frame +from ..typing import Data +from .utils import Deadline + + +__all__ = ["Assembler"] + +UTF8Decoder = codecs.getincrementaldecoder("utf-8") + + +class Assembler: + """ + Assemble messages from frames. + + :class:`Assembler` expects only data frames. The stream of frames must + respect the protocol; if it doesn't, the behavior is undefined. + + Args: + pause: Called when the buffer of frames goes above the high water mark; + should pause reading from the network. + resume: Called when the buffer of frames goes below the low water mark; + should resume reading from the network. + + """ + + def __init__( + self, + high: int | None = None, + low: int | None = None, + pause: Callable[[], Any] = lambda: None, + resume: Callable[[], Any] = lambda: None, + ) -> None: + # Serialize reads and writes -- except for reads via synchronization + # primitives provided by the threading and queue modules. + self.mutex = threading.Lock() + + # Queue of incoming frames. + self.frames: queue.SimpleQueue[Frame | None] = queue.SimpleQueue() + + # We cannot put a hard limit on the size of the queue because a single + # call to Protocol.data_received() could produce thousands of frames, + # which must be buffered. Instead, we pause reading when the buffer goes + # above the high limit and we resume when it goes under the low limit. + if high is not None and low is None: + low = high // 4 + if high is None and low is not None: + high = low * 4 + if high is not None and low is not None: + if low < 0: + raise ValueError("low must be positive or equal to zero") + if high < low: + raise ValueError("high must be greater than or equal to low") + self.high, self.low = high, low + self.pause = pause + self.resume = resume + self.paused = False + + # This flag prevents concurrent calls to get() by user code. + self.get_in_progress = False + + # This flag marks the end of the connection. + self.closed = False + + def get_next_frame(self, timeout: float | None = None) -> Frame: + # Helper to factor out the logic for getting the next frame from the + # queue, while handling timeouts and reaching the end of the stream. + if self.closed: + try: + frame = self.frames.get(block=False) + except queue.Empty: + raise EOFError("stream of frames ended") from None + else: + try: + # Check for a frame that's already received if timeout <= 0. + # SimpleQueue.get() doesn't support negative timeout values. + if timeout is not None and timeout <= 0: + frame = self.frames.get(block=False) + else: + frame = self.frames.get(block=True, timeout=timeout) + except queue.Empty: + raise TimeoutError(f"timed out in {timeout:.1f}s") from None + if frame is None: + raise EOFError("stream of frames ended") + return frame + + def reset_queue(self, frames: Iterable[Frame]) -> None: + # Helper to put frames back into the queue after they were fetched. + # This happens only when the queue is empty. However, by the time + # we acquire self.mutex, put() may have added items in the queue. + # Therefore, we must handle the case where the queue is not empty. + frame: Frame | None + with self.mutex: + queued = [] + try: + while True: + queued.append(self.frames.get(block=False)) + except queue.Empty: + pass + for frame in frames: + self.frames.put(frame) + # This loop runs only when a race condition occurs. + for frame in queued: # pragma: no cover + self.frames.put(frame) + + # This overload structure is required to avoid the error: + # "parameter without a default follows parameter with a default" + + @overload + def get(self, timeout: float | None, decode: Literal[True]) -> str: ... + + @overload + def get(self, timeout: float | None, decode: Literal[False]) -> bytes: ... + + @overload + def get(self, timeout: float | None = None, *, decode: Literal[True]) -> str: ... + + @overload + def get(self, timeout: float | None = None, *, decode: Literal[False]) -> bytes: ... + + @overload + def get(self, timeout: float | None = None, decode: bool | None = None) -> Data: ... + + def get(self, timeout: float | None = None, decode: bool | None = None) -> Data: + """ + Read the next message. + + :meth:`get` returns a single :class:`str` or :class:`bytes`. + + If the message is fragmented, :meth:`get` waits until the last frame is + received, then it reassembles the message and returns it. To receive + messages frame by frame, use :meth:`get_iter` instead. + + Args: + timeout: If a timeout is provided and elapses before a complete + message is received, :meth:`get` raises :exc:`TimeoutError`. + decode: :obj:`False` disables UTF-8 decoding of text frames and + returns :class:`bytes`. :obj:`True` forces UTF-8 decoding of + binary frames and returns :class:`str`. + + Raises: + EOFError: If the stream of frames has ended. + UnicodeDecodeError: If a text frame contains invalid UTF-8. + ConcurrencyError: If two coroutines run :meth:`get` or + :meth:`get_iter` concurrently. + TimeoutError: If a timeout is provided and elapses before a + complete message is received. + + """ + with self.mutex: + if self.get_in_progress: + raise ConcurrencyError("get() or get_iter() is already running") + self.get_in_progress = True + + # Locking with get_in_progress prevents concurrent execution + # until get() fetches a complete message or times out. + + try: + deadline = Deadline(timeout) + + # Fetch the first frame. + frame = self.get_next_frame(deadline.timeout(raise_if_elapsed=False)) + with self.mutex: + self.maybe_resume() + assert frame.opcode is OP_TEXT or frame.opcode is OP_BINARY + if decode is None: + decode = frame.opcode is OP_TEXT + frames = [frame] + + # Fetch subsequent frames for fragmented messages. + while not frame.fin: + try: + frame = self.get_next_frame( + deadline.timeout(raise_if_elapsed=False) + ) + except TimeoutError: + # Put frames already received back into the queue + # so that future calls to get() can return them. + self.reset_queue(frames) + raise + with self.mutex: + self.maybe_resume() + assert frame.opcode is OP_CONT + frames.append(frame) + + finally: + self.get_in_progress = False + + # This converts frame.data to bytes when it's a bytearray. + data = b"".join(frame.data for frame in frames) + if decode: + return data.decode() + else: + return data + + @overload + def get_iter(self, decode: Literal[True]) -> Iterator[str]: ... + + @overload + def get_iter(self, decode: Literal[False]) -> Iterator[bytes]: ... + + @overload + def get_iter(self, decode: bool | None = None) -> Iterator[Data]: ... + + def get_iter(self, decode: bool | None = None) -> Iterator[Data]: + """ + Stream the next message. + + Iterating the return value of :meth:`get_iter` yields a :class:`str` or + :class:`bytes` for each frame in the message. + + The iterator must be fully consumed before calling :meth:`get_iter` or + :meth:`get` again. Else, :exc:`ConcurrencyError` is raised. + + This method only makes sense for fragmented messages. If messages aren't + fragmented, use :meth:`get` instead. + + Args: + decode: :obj:`False` disables UTF-8 decoding of text frames and + returns :class:`bytes`. :obj:`True` forces UTF-8 decoding of + binary frames and returns :class:`str`. + + Raises: + EOFError: If the stream of frames has ended. + UnicodeDecodeError: If a text frame contains invalid UTF-8. + ConcurrencyError: If two coroutines run :meth:`get` or + :meth:`get_iter` concurrently. + + """ + with self.mutex: + if self.get_in_progress: + raise ConcurrencyError("get() or get_iter() is already running") + self.get_in_progress = True + + # Locking with get_in_progress prevents concurrent execution + # until get_iter() fetches a complete message or times out. + + # If get_iter() raises an exception e.g. in decoder.decode(), + # get_in_progress remains set and the connection becomes unusable. + + # Yield the first frame. + frame = self.get_next_frame() + with self.mutex: + self.maybe_resume() + assert frame.opcode is OP_TEXT or frame.opcode is OP_BINARY + if decode is None: + decode = frame.opcode is OP_TEXT + if decode: + decoder = UTF8Decoder() + yield decoder.decode(frame.data, frame.fin) + else: + # Convert to bytes when frame.data is a bytearray. + yield bytes(frame.data) + + # Yield subsequent frames for fragmented messages. + while not frame.fin: + frame = self.get_next_frame() + with self.mutex: + self.maybe_resume() + assert frame.opcode is OP_CONT + if decode: + yield decoder.decode(frame.data, frame.fin) + else: + # Convert to bytes when frame.data is a bytearray. + yield bytes(frame.data) + + self.get_in_progress = False + + def put(self, frame: Frame) -> None: + """ + Add ``frame`` to the next message. + + Raises: + EOFError: If the stream of frames has ended. + + """ + with self.mutex: + if self.closed: + raise EOFError("stream of frames ended") + + self.frames.put(frame) + self.maybe_pause() + + # put() and get/get_iter() call maybe_pause() and maybe_resume() while + # holding self.mutex. This guarantees that the calls interleave properly. + # Specifically, it prevents a race condition where maybe_resume() would + # run before maybe_pause(), leaving the connection incorrectly paused. + + # A race condition is possible when get/get_iter() call self.frames.get() + # without holding self.mutex. However, it's harmless — and even beneficial! + # It can only result in popping an item from the queue before maybe_resume() + # runs and skipping a pause() - resume() cycle that would otherwise occur. + + def maybe_pause(self) -> None: + """Pause the writer if queue is above the high water mark.""" + # Skip if flow control is disabled. + if self.high is None: + return + + assert self.mutex.locked() + + # Check for "> high" to support high = 0. + if self.frames.qsize() > self.high and not self.paused: + self.paused = True + self.pause() + + def maybe_resume(self) -> None: + """Resume the writer if queue is below the low water mark.""" + # Skip if flow control is disabled. + if self.low is None: + return + + assert self.mutex.locked() + + # Check for "<= low" to support low = 0. + if self.frames.qsize() <= self.low and self.paused: + self.paused = False + self.resume() + + def close(self) -> None: + """ + End the stream of frames. + + Calling :meth:`close` concurrently with :meth:`get`, :meth:`get_iter`, + or :meth:`put` is safe. They will raise :exc:`EOFError`. + + """ + with self.mutex: + if self.closed: + return + + self.closed = True + + if self.get_in_progress: + # Unblock get() or get_iter(). + self.frames.put(None) + + if self.paused: + # Unblock recv_events(). + self.paused = False + self.resume() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/router.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/router.py new file mode 100644 index 0000000000000000000000000000000000000000..99af23b313896f0242c4a313dd3b4d1a61b28eed --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/router.py @@ -0,0 +1,213 @@ +from __future__ import annotations + +import http +import ssl as ssl_module +import urllib.parse +from typing import Any, Callable, Literal + +from ..http11 import Request, Response +from .server import Server, ServerConnection, serve + + +__all__ = ["route", "unix_route", "Router"] + + +try: + from werkzeug.exceptions import NotFound + from werkzeug.routing import Map, RequestRedirect + +except ImportError: + + def route( + url_map: Map, + *args: Any, + server_name: str | None = None, + ssl: ssl_module.SSLContext | Literal[True] | None = None, + create_router: type[Router] | None = None, + **kwargs: Any, + ) -> Server: + raise ImportError("route() requires werkzeug") + + def unix_route( + url_map: Map, + path: str | None = None, + **kwargs: Any, + ) -> Server: + raise ImportError("unix_route() requires werkzeug") + +else: + + def route( + url_map: Map, + *args: Any, + server_name: str | None = None, + ssl: ssl_module.SSLContext | Literal[True] | None = None, + create_router: type[Router] | None = None, + **kwargs: Any, + ) -> Server: + """ + Create a WebSocket server dispatching connections to different handlers. + + This feature requires the third-party library `werkzeug`_: + + .. code-block:: console + + $ pip install werkzeug + + .. _werkzeug: https://werkzeug.palletsprojects.com/ + + :func:`route` accepts the same arguments as + :func:`~websockets.sync.server.serve`, except as described below. + + The first argument is a :class:`werkzeug.routing.Map` that maps URL patterns + to connection handlers. In addition to the connection, handlers receive + parameters captured in the URL as keyword arguments. + + Here's an example:: + + + from websockets.sync.router import route + from werkzeug.routing import Map, Rule + + def channel_handler(websocket, channel_id): + ... + + url_map = Map([ + Rule("/channel/", endpoint=channel_handler), + ... + ]) + + with route(url_map, ...) as server: + server.serve_forever() + + Refer to the documentation of :mod:`werkzeug.routing` for details. + + If you define redirects with ``Rule(..., redirect_to=...)`` in the URL map, + when the server runs behind a reverse proxy that modifies the ``Host`` + header or terminates TLS, you need additional configuration: + + * Set ``server_name`` to the name of the server as seen by clients. When + not provided, websockets uses the value of the ``Host`` header. + + * Set ``ssl=True`` to generate ``wss://`` URIs without enabling TLS. + Under the hood, this bind the URL map with a ``url_scheme`` of + ``wss://`` instead of ``ws://``. + + There is no need to specify ``websocket=True`` in each rule. It is added + automatically. + + Args: + url_map: Mapping of URL patterns to connection handlers. + server_name: Name of the server as seen by clients. If :obj:`None`, + websockets uses the value of the ``Host`` header. + ssl: Configuration for enabling TLS on the connection. Set it to + :obj:`True` if a reverse proxy terminates TLS connections. + create_router: Factory for the :class:`Router` dispatching requests to + handlers. Set it to a wrapper or a subclass to customize routing. + + """ + url_scheme = "ws" if ssl is None else "wss" + if ssl is not True and ssl is not None: + kwargs["ssl"] = ssl + + if create_router is None: + create_router = Router + + router = create_router(url_map, server_name, url_scheme) + + _process_request: ( + Callable[ + [ServerConnection, Request], + Response | None, + ] + | None + ) = kwargs.pop("process_request", None) + if _process_request is None: + process_request: Callable[ + [ServerConnection, Request], + Response | None, + ] = router.route_request + else: + + def process_request( + connection: ServerConnection, request: Request + ) -> Response | None: + response = _process_request(connection, request) + if response is not None: + return response + return router.route_request(connection, request) + + return serve(router.handler, *args, process_request=process_request, **kwargs) + + def unix_route( + url_map: Map, + path: str | None = None, + **kwargs: Any, + ) -> Server: + """ + Create a WebSocket Unix server dispatching connections to different handlers. + + :func:`unix_route` combines the behaviors of :func:`route` and + :func:`~websockets.sync.server.unix_serve`. + + Args: + url_map: Mapping of URL patterns to connection handlers. + path: File system path to the Unix socket. + + """ + return route(url_map, unix=True, path=path, **kwargs) + + +class Router: + """WebSocket router supporting :func:`route`.""" + + def __init__( + self, + url_map: Map, + server_name: str | None = None, + url_scheme: str = "ws", + ) -> None: + self.url_map = url_map + self.server_name = server_name + self.url_scheme = url_scheme + for rule in self.url_map.iter_rules(): + rule.websocket = True + + def get_server_name(self, connection: ServerConnection, request: Request) -> str: + if self.server_name is None: + return request.headers["Host"] + else: + return self.server_name + + def redirect(self, connection: ServerConnection, url: str) -> Response: + response = connection.respond(http.HTTPStatus.FOUND, f"Found at {url}") + response.headers["Location"] = url + return response + + def not_found(self, connection: ServerConnection) -> Response: + return connection.respond(http.HTTPStatus.NOT_FOUND, "Not Found") + + def route_request( + self, connection: ServerConnection, request: Request + ) -> Response | None: + """Route incoming request.""" + url_map_adapter = self.url_map.bind( + server_name=self.get_server_name(connection, request), + url_scheme=self.url_scheme, + ) + try: + parsed = urllib.parse.urlparse(request.path) + handler, kwargs = url_map_adapter.match( + path_info=parsed.path, + query_args=parsed.query, + ) + except RequestRedirect as redirect: + return self.redirect(connection, redirect.new_url) + except NotFound: + return self.not_found(connection) + connection.handler, connection.handler_kwargs = handler, kwargs + return None + + def handler(self, connection: ServerConnection) -> None: + """Handle a connection.""" + return connection.handler(connection, **connection.handler_kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/server.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/server.py new file mode 100644 index 0000000000000000000000000000000000000000..24f77e51be7580a985eedd2997d2f4562b00806f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/server.py @@ -0,0 +1,765 @@ +from __future__ import annotations + +import hmac +import http +import logging +import os +import re +import selectors +import socket +import ssl as ssl_module +import sys +import threading +import warnings +from collections.abc import Iterable, Sequence +from types import TracebackType +from typing import Any, Callable, Mapping, cast + +from ..exceptions import InvalidHeader +from ..extensions.base import ServerExtensionFactory +from ..extensions.permessage_deflate import enable_server_permessage_deflate +from ..frames import CloseCode +from ..headers import ( + build_www_authenticate_basic, + parse_authorization_basic, + validate_subprotocols, +) +from ..http11 import SERVER, Request, Response +from ..protocol import CONNECTING, OPEN, Event +from ..server import ServerProtocol +from ..typing import LoggerLike, Origin, StatusLike, Subprotocol +from .connection import Connection +from .utils import Deadline + + +__all__ = ["serve", "unix_serve", "ServerConnection", "Server", "basic_auth"] + + +class ServerConnection(Connection): + """ + :mod:`threading` implementation of a WebSocket server connection. + + :class:`ServerConnection` provides :meth:`recv` and :meth:`send` methods for + receiving and sending messages. + + It supports iteration to receive messages:: + + for message in websocket: + process(message) + + The iterator exits normally when the connection is closed with code + 1000 (OK) or 1001 (going away) or without a close code. It raises a + :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is + closed with any other code. + + The ``ping_interval``, ``ping_timeout``, ``close_timeout``, and + ``max_queue`` arguments have the same meaning as in :func:`serve`. + + Args: + socket: Socket connected to a WebSocket client. + protocol: Sans-I/O connection. + + """ + + def __init__( + self, + socket: socket.socket, + protocol: ServerProtocol, + *, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + max_queue: int | None | tuple[int | None, int | None] = 16, + ) -> None: + self.protocol: ServerProtocol + self.request_rcvd = threading.Event() + super().__init__( + socket, + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + ) + self.username: str # see basic_auth() + self.handler: Callable[[ServerConnection], None] # see route() + self.handler_kwargs: Mapping[str, Any] # see route() + + def respond(self, status: StatusLike, text: str) -> Response: + """ + Create a plain text HTTP response. + + ``process_request`` and ``process_response`` may call this method to + return an HTTP response instead of performing the WebSocket opening + handshake. + + You can modify the response before returning it, for example by changing + HTTP headers. + + Args: + status: HTTP status code. + text: HTTP response body; it will be encoded to UTF-8. + + Returns: + HTTP response to send to the client. + + """ + return self.protocol.reject(status, text) + + def handshake( + self, + process_request: ( + Callable[ + [ServerConnection, Request], + Response | None, + ] + | None + ) = None, + process_response: ( + Callable[ + [ServerConnection, Request, Response], + Response | None, + ] + | None + ) = None, + server_header: str | None = SERVER, + timeout: float | None = None, + ) -> None: + """ + Perform the opening handshake. + + """ + if not self.request_rcvd.wait(timeout): + raise TimeoutError("timed out while waiting for handshake request") + + if self.request is not None: + with self.send_context(expected_state=CONNECTING): + response = None + + if process_request is not None: + try: + response = process_request(self, self.request) + except Exception as exc: + self.protocol.handshake_exc = exc + response = self.protocol.reject( + http.HTTPStatus.INTERNAL_SERVER_ERROR, + ( + "Failed to open a WebSocket connection.\n" + "See server log for more information.\n" + ), + ) + + if response is None: + self.response = self.protocol.accept(self.request) + else: + self.response = response + + if server_header: + self.response.headers["Server"] = server_header + + response = None + + if process_response is not None: + try: + response = process_response(self, self.request, self.response) + except Exception as exc: + self.protocol.handshake_exc = exc + response = self.protocol.reject( + http.HTTPStatus.INTERNAL_SERVER_ERROR, + ( + "Failed to open a WebSocket connection.\n" + "See server log for more information.\n" + ), + ) + + if response is not None: + self.response = response + + self.protocol.send_response(self.response) + + # self.protocol.handshake_exc is set when the connection is lost before + # receiving a request, when the request cannot be parsed, or when the + # handshake fails, including when process_request or process_response + # raises an exception. + + # It isn't set when process_request or process_response sends an HTTP + # response that rejects the handshake. + + if self.protocol.handshake_exc is not None: + raise self.protocol.handshake_exc + + def process_event(self, event: Event) -> None: + """ + Process one incoming event. + + """ + # First event - handshake request. + if self.request is None: + assert isinstance(event, Request) + self.request = event + self.request_rcvd.set() + # Later events - frames. + else: + super().process_event(event) + + def recv_events(self) -> None: + """ + Read incoming data from the socket and process events. + + """ + try: + super().recv_events() + finally: + # If the connection is closed during the handshake, unblock it. + self.request_rcvd.set() + + +class Server: + """ + WebSocket server returned by :func:`serve`. + + This class mirrors the API of :class:`~socketserver.BaseServer`, notably the + :meth:`~socketserver.BaseServer.serve_forever` and + :meth:`~socketserver.BaseServer.shutdown` methods, as well as the context + manager protocol. + + Args: + socket: Server socket listening for new connections. + handler: Handler for one connection. Receives the socket and address + returned by :meth:`~socket.socket.accept`. + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.server")``. + See the :doc:`logging guide <../../topics/logging>` for details. + + """ + + def __init__( + self, + socket: socket.socket, + handler: Callable[[socket.socket, Any], None], + logger: LoggerLike | None = None, + ) -> None: + self.socket = socket + self.handler = handler + if logger is None: + logger = logging.getLogger("websockets.server") + self.logger = logger + if sys.platform != "win32": + self.shutdown_watcher, self.shutdown_notifier = os.pipe() + + def serve_forever(self) -> None: + """ + See :meth:`socketserver.BaseServer.serve_forever`. + + This method doesn't return. Calling :meth:`shutdown` from another thread + stops the server. + + Typical use:: + + with serve(...) as server: + server.serve_forever() + + """ + poller = selectors.DefaultSelector() + try: + poller.register(self.socket, selectors.EVENT_READ) + except ValueError: # pragma: no cover + # If shutdown() is called before poller.register(), + # the socket is closed and poller.register() raises + # ValueError: Invalid file descriptor: -1 + return + if sys.platform != "win32": + poller.register(self.shutdown_watcher, selectors.EVENT_READ) + + while True: + poller.select() + try: + # If the socket is closed, this will raise an exception and exit + # the loop. So we don't need to check the return value of select(). + sock, addr = self.socket.accept() + except OSError: + break + # Since there isn't a mechanism for tracking connections and waiting + # for them to terminate, we cannot use daemon threads, or else all + # connections would be terminate brutally when closing the server. + thread = threading.Thread(target=self.handler, args=(sock, addr)) + thread.start() + + def shutdown(self) -> None: + """ + See :meth:`socketserver.BaseServer.shutdown`. + + """ + self.socket.close() + if sys.platform != "win32": + os.write(self.shutdown_notifier, b"x") + + def fileno(self) -> int: + """ + See :meth:`socketserver.BaseServer.fileno`. + + """ + return self.socket.fileno() + + def __enter__(self) -> Server: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + self.shutdown() + + +def __getattr__(name: str) -> Any: + if name == "WebSocketServer": + warnings.warn( # deprecated in 13.0 - 2024-08-20 + "WebSocketServer was renamed to Server", + DeprecationWarning, + ) + return Server + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + +def serve( + handler: Callable[[ServerConnection], None], + host: str | None = None, + port: int | None = None, + *, + # TCP/TLS + sock: socket.socket | None = None, + ssl: ssl_module.SSLContext | None = None, + # WebSocket + origins: Sequence[Origin | re.Pattern[str] | None] | None = None, + extensions: Sequence[ServerExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + select_subprotocol: ( + Callable[ + [ServerConnection, Sequence[Subprotocol]], + Subprotocol | None, + ] + | None + ) = None, + compression: str | None = "deflate", + # HTTP + process_request: ( + Callable[ + [ServerConnection, Request], + Response | None, + ] + | None + ) = None, + process_response: ( + Callable[ + [ServerConnection, Request, Response], + Response | None, + ] + | None + ) = None, + server_header: str | None = SERVER, + # Timeouts + open_timeout: float | None = 10, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + # Limits + max_size: int | None | tuple[int | None, int | None] = 2**20, + max_queue: int | None | tuple[int | None, int | None] = 16, + # Logging + logger: LoggerLike | None = None, + # Escape hatch for advanced customization + create_connection: type[ServerConnection] | None = None, + **kwargs: Any, +) -> Server: + """ + Create a WebSocket server listening on ``host`` and ``port``. + + Whenever a client connects, the server creates a :class:`ServerConnection`, + performs the opening handshake, and delegates to the ``handler``. + + The handler receives the :class:`ServerConnection` instance, which you can + use to send and receive messages. + + Once the handler completes, either normally or with an exception, the server + performs the closing handshake and closes the connection. + + This function returns a :class:`Server` whose API mirrors + :class:`~socketserver.BaseServer`. Treat it as a context manager to ensure + that it will be closed and call :meth:`~Server.serve_forever` to serve + requests:: + + from websockets.sync.server import serve + + def handler(websocket): + ... + + with serve(handler, ...) as server: + server.serve_forever() + + Args: + handler: Connection handler. It receives the WebSocket connection, + which is a :class:`ServerConnection`, in argument. + host: Network interfaces the server binds to. + See :func:`~socket.create_server` for details. + port: TCP port the server listens on. + See :func:`~socket.create_server` for details. + sock: Preexisting TCP socket. ``sock`` replaces ``host`` and ``port``. + You may call :func:`socket.create_server` to create a suitable TCP + socket. + ssl: Configuration for enabling TLS on the connection. + origins: Acceptable values of the ``Origin`` header, for defending + against Cross-Site WebSocket Hijacking attacks. Values can be + :class:`str` to test for an exact match or regular expressions + compiled by :func:`re.compile` to test against a pattern. Include + :obj:`None` in the list if the lack of an origin is acceptable. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + select_subprotocol: Callback for selecting a subprotocol among + those supported by the client and the server. It receives a + :class:`ServerConnection` (not a + :class:`~websockets.server.ServerProtocol`!) instance and a list of + subprotocols offered by the client. Other than the first argument, + it has the same behavior as the + :meth:`ServerProtocol.select_subprotocol + ` method. + compression: The "permessage-deflate" extension is enabled by default. + Set ``compression`` to :obj:`None` to disable it. See the + :doc:`compression guide <../../topics/compression>` for details. + process_request: Intercept the request during the opening handshake. + Return an HTTP response to force the response. Return :obj:`None` to + continue normally. When you force an HTTP 101 Continue response, the + handshake is successful. Else, the connection is aborted. + process_response: Intercept the response during the opening handshake. + Modify the response or return a new HTTP response to force the + response. Return :obj:`None` to continue normally. When you force an + HTTP 101 Continue response, the handshake is successful. Else, the + connection is aborted. + server_header: Value of the ``Server`` response header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to + :obj:`None` removes the header. + open_timeout: Timeout for opening connections in seconds. + :obj:`None` disables the timeout. + ping_interval: Interval between keepalive pings in seconds. + :obj:`None` disables keepalive. + ping_timeout: Timeout for keepalive pings in seconds. + :obj:`None` disables timeouts. + close_timeout: Timeout for closing connections in seconds. + :obj:`None` disables the timeout. + max_size: Maximum size of incoming messages in bytes. + :obj:`None` disables the limit. You may pass a ``(max_message_size, + max_fragment_size)`` tuple to set different limits for messages and + fragments when you expect long messages sent in short fragments. + max_queue: High-water mark of the buffer where frames are received. + It defaults to 16 frames. The low-water mark defaults to ``max_queue + // 4``. You may pass a ``(high, low)`` tuple to set the high-water + and low-water marks. If you want to disable flow control entirely, + you may set it to ``None``, although that's a bad idea. + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.server")``. See the + :doc:`logging guide <../../topics/logging>` for details. + create_connection: Factory for the :class:`ServerConnection` managing + the connection. Set it to a wrapper or a subclass to customize + connection handling. + + Any other keyword arguments are passed to :func:`~socket.create_server`. + + """ + + # Process parameters + + # Backwards compatibility: ssl used to be called ssl_context. + if ssl is None and "ssl_context" in kwargs: + ssl = kwargs.pop("ssl_context") + warnings.warn( # deprecated in 13.0 - 2024-08-20 + "ssl_context was renamed to ssl", + DeprecationWarning, + ) + + if subprotocols is not None: + validate_subprotocols(subprotocols) + + if compression == "deflate": + extensions = enable_server_permessage_deflate(extensions) + elif compression is not None: + raise ValueError(f"unsupported compression: {compression}") + + if create_connection is None: + create_connection = ServerConnection + + # Bind socket and listen + + # Private APIs for unix_connect() + unix: bool = kwargs.pop("unix", False) + path: str | None = kwargs.pop("path", None) + + if sock is None: + if unix: + if path is None: + raise ValueError("missing path argument") + kwargs.setdefault("family", socket.AF_UNIX) + sock = socket.create_server(path, **kwargs) + else: + sock = socket.create_server((host, port), **kwargs) + else: + if path is not None: + raise ValueError("path and sock arguments are incompatible") + + # Initialize TLS wrapper + + if ssl is not None: + sock = ssl.wrap_socket( + sock, + server_side=True, + # Delay TLS handshake until after we set a timeout on the socket. + do_handshake_on_connect=False, + ) + + # Define request handler + + def conn_handler(sock: socket.socket, addr: Any) -> None: + # Calculate timeouts on the TLS and WebSocket handshakes. + # The TLS timeout must be set on the socket, then removed + # to avoid conflicting with the WebSocket timeout in handshake(). + deadline = Deadline(open_timeout) + + try: + # Disable Nagle algorithm + + if not unix: + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True) + + # Perform TLS handshake + + if ssl is not None: + sock.settimeout(deadline.timeout()) + # mypy cannot figure this out + assert isinstance(sock, ssl_module.SSLSocket) + sock.do_handshake() + sock.settimeout(None) + + # Create a closure to give select_subprotocol access to connection. + protocol_select_subprotocol: ( + Callable[ + [ServerProtocol, Sequence[Subprotocol]], + Subprotocol | None, + ] + | None + ) = None + if select_subprotocol is not None: + + def protocol_select_subprotocol( + protocol: ServerProtocol, + subprotocols: Sequence[Subprotocol], + ) -> Subprotocol | None: + # mypy doesn't know that select_subprotocol is immutable. + assert select_subprotocol is not None + # Ensure this function is only used in the intended context. + assert protocol is connection.protocol + return select_subprotocol(connection, subprotocols) + + # Initialize WebSocket protocol + + protocol = ServerProtocol( + origins=origins, + extensions=extensions, + subprotocols=subprotocols, + select_subprotocol=protocol_select_subprotocol, + max_size=max_size, + logger=logger, + ) + + # Initialize WebSocket connection + + assert create_connection is not None # help mypy + connection = create_connection( + sock, + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + ) + except Exception: + sock.close() + return + + try: + try: + connection.handshake( + process_request, + process_response, + server_header, + deadline.timeout(), + ) + except TimeoutError: + connection.close_socket() + connection.recv_events_thread.join() + return + except Exception: + connection.logger.error("opening handshake failed", exc_info=True) + connection.close_socket() + connection.recv_events_thread.join() + return + + assert connection.protocol.state is OPEN + try: + connection.start_keepalive() + handler(connection) + except Exception: + connection.logger.error("connection handler failed", exc_info=True) + connection.close(CloseCode.INTERNAL_ERROR) + else: + connection.close() + + except Exception: # pragma: no cover + # Don't leak sockets on unexpected errors. + sock.close() + + # Initialize server + + return Server(sock, conn_handler, logger) + + +def unix_serve( + handler: Callable[[ServerConnection], None], + path: str | None = None, + **kwargs: Any, +) -> Server: + """ + Create a WebSocket server listening on a Unix socket. + + This function accepts the same keyword arguments as :func:`serve`. + + It's only available on Unix. + + It's useful for deploying a server behind a reverse proxy such as nginx. + + Args: + handler: Connection handler. It receives the WebSocket connection, + which is a :class:`ServerConnection`, in argument. + path: File system path to the Unix socket. + + """ + return serve(handler, unix=True, path=path, **kwargs) + + +def is_credentials(credentials: Any) -> bool: + try: + username, password = credentials + except (TypeError, ValueError): + return False + else: + return isinstance(username, str) and isinstance(password, str) + + +def basic_auth( + realm: str = "", + credentials: tuple[str, str] | Iterable[tuple[str, str]] | None = None, + check_credentials: Callable[[str, str], bool] | None = None, +) -> Callable[[ServerConnection, Request], Response | None]: + """ + Factory for ``process_request`` to enforce HTTP Basic Authentication. + + :func:`basic_auth` is designed to integrate with :func:`serve` as follows:: + + from websockets.sync.server import basic_auth, serve + + with serve( + ..., + process_request=basic_auth( + realm="my dev server", + credentials=("hello", "iloveyou"), + ), + ): + + If authentication succeeds, the connection's ``username`` attribute is set. + If it fails, the server responds with an HTTP 401 Unauthorized status. + + One of ``credentials`` or ``check_credentials`` must be provided; not both. + + Args: + realm: Scope of protection. It should contain only ASCII characters + because the encoding of non-ASCII characters is undefined. Refer to + section 2.2 of :rfc:`7235` for details. + credentials: Hard coded authorized credentials. It can be a + ``(username, password)`` pair or a list of such pairs. + check_credentials: Function that verifies credentials. + It receives ``username`` and ``password`` arguments and returns + whether they're valid. + Raises: + TypeError: If ``credentials`` or ``check_credentials`` is wrong. + ValueError: If ``credentials`` and ``check_credentials`` are both + provided or both not provided. + + """ + if (credentials is None) == (check_credentials is None): + raise ValueError("provide either credentials or check_credentials") + + if credentials is not None: + if is_credentials(credentials): + credentials_list = [cast(tuple[str, str], credentials)] + elif isinstance(credentials, Iterable): + credentials_list = list(cast(Iterable[tuple[str, str]], credentials)) + if not all(is_credentials(item) for item in credentials_list): + raise TypeError(f"invalid credentials argument: {credentials}") + else: + raise TypeError(f"invalid credentials argument: {credentials}") + + credentials_dict = dict(credentials_list) + + def check_credentials(username: str, password: str) -> bool: + try: + expected_password = credentials_dict[username] + except KeyError: + return False + return hmac.compare_digest(expected_password, password) + + assert check_credentials is not None # help mypy + + def process_request( + connection: ServerConnection, + request: Request, + ) -> Response | None: + """ + Perform HTTP Basic Authentication. + + If it succeeds, set the connection's ``username`` attribute and return + :obj:`None`. If it fails, return an HTTP 401 Unauthorized responss. + + """ + try: + authorization = request.headers["Authorization"] + except KeyError: + response = connection.respond( + http.HTTPStatus.UNAUTHORIZED, + "Missing credentials\n", + ) + response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm) + return response + + try: + username, password = parse_authorization_basic(authorization) + except InvalidHeader: + response = connection.respond( + http.HTTPStatus.UNAUTHORIZED, + "Unsupported credentials\n", + ) + response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm) + return response + + if not check_credentials(username, password): + response = connection.respond( + http.HTTPStatus.UNAUTHORIZED, + "Invalid credentials\n", + ) + response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm) + return response + + connection.username = username + return None + + return process_request diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d8890411e16d144dec095b4c2eb86183d0f05bca --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/sync/utils.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +import time + + +__all__ = ["Deadline"] + + +class Deadline: + """ + Manage timeouts across multiple steps. + + Args: + timeout: Time available in seconds or :obj:`None` if there is no limit. + + """ + + def __init__(self, timeout: float | None) -> None: + self.deadline: float | None + if timeout is None: + self.deadline = None + else: + self.deadline = time.monotonic() + timeout + + def timeout(self, *, raise_if_elapsed: bool = True) -> float | None: + """ + Calculate a timeout from a deadline. + + Args: + raise_if_elapsed: Whether to raise :exc:`TimeoutError` + if the deadline lapsed. + + Raises: + TimeoutError: If the deadline lapsed. + + Returns: + Time left in seconds or :obj:`None` if there is no limit. + + """ + if self.deadline is None: + return None + timeout = self.deadline - time.monotonic() + if raise_if_elapsed and timeout <= 0: + raise TimeoutError("timed out") + return timeout diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/typing.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/typing.py new file mode 100644 index 0000000000000000000000000000000000000000..5103336ffe8be86d508893d95d929300ac6bf5db --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/typing.py @@ -0,0 +1,75 @@ +from __future__ import annotations + +import http +import logging +from typing import TYPE_CHECKING, Any, NewType, Sequence + + +__all__ = [ + "Data", + "LoggerLike", + "StatusLike", + "Origin", + "Subprotocol", + "ExtensionName", + "ExtensionParameter", +] + + +# Public types used in the signature of public APIs + +Data = str | bytes +"""Types supported in a WebSocket message: +:class:`str` for a Text_ frame, :class:`bytes` for a Binary_ frame. + +.. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 +.. _Binary : https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + +""" + +BytesLike = bytes | bytearray | memoryview +"""Types accepted where :class:`bytes` is expected.""" + +DataLike = str | bytes | bytearray | memoryview +"""Types accepted where :class:`Data` is expected.""" + +if TYPE_CHECKING: + LoggerLike = logging.Logger | logging.LoggerAdapter[Any] + """Types accepted where a :class:`~logging.Logger` is expected.""" +else: # remove this branch when dropping support for Python < 3.11 + LoggerLike = logging.Logger | logging.LoggerAdapter + """Types accepted where a :class:`~logging.Logger` is expected.""" + + +StatusLike = http.HTTPStatus | int +""" +Types accepted where an :class:`~http.HTTPStatus` is expected.""" + + +Origin = NewType("Origin", str) +"""Value of a ``Origin`` header.""" + + +Subprotocol = NewType("Subprotocol", str) +"""Subprotocol in a ``Sec-WebSocket-Protocol`` header.""" + + +ExtensionName = NewType("ExtensionName", str) +"""Name of a WebSocket extension.""" + +ExtensionParameter = tuple[str, str | None] +"""Parameter of a WebSocket extension.""" + + +# Private types + +ExtensionHeader = tuple[ExtensionName, Sequence[ExtensionParameter]] +"""Extension in a ``Sec-WebSocket-Extensions`` header.""" + + +ConnectionOption = NewType("ConnectionOption", str) +"""Connection option in a ``Connection`` header.""" + + +UpgradeProtocol = NewType("UpgradeProtocol", str) +"""Upgrade protocol in an ``Upgrade`` header.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/uri.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/uri.py new file mode 100644 index 0000000000000000000000000000000000000000..1d5b71a172bbde66bbb08bd127a4f0cc42829750 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/uri.py @@ -0,0 +1,107 @@ +from __future__ import annotations + +import dataclasses +import urllib.parse + +from .exceptions import InvalidURI + + +__all__ = ["parse_uri", "WebSocketURI"] + + +# All characters from the gen-delims and sub-delims sets in RFC 3987. +DELIMS = ":/?#[]@!$&'()*+,;=" + + +@dataclasses.dataclass +class WebSocketURI: + """ + WebSocket URI. + + Attributes: + secure: :obj:`True` for a ``wss`` URI, :obj:`False` for a ``ws`` URI. + host: Normalized to lower case. + port: Always set even if it's the default. + path: May be empty. + query: May be empty if the URI doesn't include a query component. + username: Available when the URI contains `User Information`_. + password: Available when the URI contains `User Information`_. + + .. _User Information: https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.1 + + """ + + secure: bool + host: str + port: int + path: str + query: str + username: str | None = None + password: str | None = None + + @property + def resource_name(self) -> str: + if self.path: + resource_name = self.path + else: + resource_name = "/" + if self.query: + resource_name += "?" + self.query + return resource_name + + @property + def user_info(self) -> tuple[str, str] | None: + if self.username is None: + return None + assert self.password is not None + return (self.username, self.password) + + +def parse_uri(uri: str) -> WebSocketURI: + """ + Parse and validate a WebSocket URI. + + Args: + uri: WebSocket URI. + + Returns: + Parsed WebSocket URI. + + Raises: + InvalidURI: If ``uri`` isn't a valid WebSocket URI. + + """ + parsed = urllib.parse.urlparse(uri) + if parsed.scheme not in ["ws", "wss"]: + raise InvalidURI(uri, "scheme isn't ws or wss") + if parsed.hostname is None: + raise InvalidURI(uri, "hostname isn't provided") + if parsed.fragment != "": + raise InvalidURI(uri, "fragment identifier is meaningless") + + secure = parsed.scheme == "wss" + host = parsed.hostname + port = parsed.port or (443 if secure else 80) + path = parsed.path + query = parsed.query + username = parsed.username + password = parsed.password + # urllib.parse.urlparse accepts URLs with a username but without a + # password. This doesn't make sense for HTTP Basic Auth credentials. + if username is not None and password is None: + raise InvalidURI(uri, "username provided without password") + + try: + uri.encode("ascii") + except UnicodeEncodeError: + # Input contains non-ASCII characters. + # It must be an IRI. Convert it to a URI. + host = host.encode("idna").decode() + path = urllib.parse.quote(path, safe=DELIMS) + query = urllib.parse.quote(query, safe=DELIMS) + if username is not None: + assert password is not None + username = urllib.parse.quote(username, safe=DELIMS) + password = urllib.parse.quote(password, safe=DELIMS) + + return WebSocketURI(secure, host, port, path, query, username, password) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..874479ed4cfac4de94a1ee2cdffb0ff86ba95727 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/utils.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +import base64 +import hashlib +import secrets +import sys + +from .typing import BytesLike + + +__all__ = ["accept_key", "apply_mask"] + + +GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + + +def generate_key() -> str: + """ + Generate a random key for the Sec-WebSocket-Key header. + + """ + key = secrets.token_bytes(16) + return base64.b64encode(key).decode() + + +def accept_key(key: str) -> str: + """ + Compute the value of the Sec-WebSocket-Accept header. + + Args: + key: Value of the Sec-WebSocket-Key header. + + """ + sha1 = hashlib.sha1((key + GUID).encode()).digest() + return base64.b64encode(sha1).decode() + + +def apply_mask(data: BytesLike, mask: bytes | bytearray) -> bytes: + """ + Apply masking to the data of a WebSocket message. + + Args: + data: Data to mask. + mask: 4-bytes mask. + + """ + if len(mask) != 4: + raise ValueError("mask must contain 4 bytes") + + data_int = int.from_bytes(data, sys.byteorder) + mask_repeated = mask * (len(data) // 4) + mask[: len(data) % 4] + mask_int = int.from_bytes(mask_repeated, sys.byteorder) + return (data_int ^ mask_int).to_bytes(len(data), sys.byteorder) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/version.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/version.py new file mode 100644 index 0000000000000000000000000000000000000000..b7a192afb70f012b2c25eb578b4532e25cf9b550 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/websockets/version.py @@ -0,0 +1,92 @@ +from __future__ import annotations + +import importlib.metadata + + +__all__ = ["tag", "version", "commit"] + + +# ========= =========== =================== +# release development +# ========= =========== =================== +# tag X.Y X.Y (upcoming) +# version X.Y X.Y.dev1+g5678cde +# commit X.Y 5678cde +# ========= =========== =================== + + +# When tagging a release, set `released = True`. +# After tagging a release, set `released = False` and increment `tag`. + +released = True + +tag = version = commit = "16.0" + + +if not released: # pragma: no cover + import pathlib + import re + import subprocess + + def get_version(tag: str) -> str: + # Since setup.py executes the contents of src/websockets/version.py, + # __file__ can point to either of these two files. + file_path = pathlib.Path(__file__) + root_dir = file_path.parents[0 if file_path.name == "setup.py" else 2] + + # Read version from package metadata if it is installed. + try: + version = importlib.metadata.version("websockets") + except ImportError: + pass + else: + # Check that this file belongs to the installed package. + files = importlib.metadata.files("websockets") + if files: + version_files = [f for f in files if f.name == file_path.name] + if version_files: + version_file = version_files[0] + if version_file.locate() == file_path: + return version + + # Read version from git if available. + try: + description = subprocess.run( + ["git", "describe", "--dirty", "--tags", "--long"], + capture_output=True, + cwd=root_dir, + timeout=1, + check=True, + text=True, + ).stdout.strip() + # subprocess.run raises FileNotFoundError if git isn't on $PATH. + except ( + FileNotFoundError, + subprocess.CalledProcessError, + subprocess.TimeoutExpired, + ): + pass + else: + description_re = r"[0-9.]+-([0-9]+)-(g[0-9a-f]{7,}(?:-dirty)?)" + match = re.fullmatch(description_re, description) + if match is None: + raise ValueError(f"Unexpected git description: {description}") + distance, remainder = match.groups() + remainder = remainder.replace("-", ".") # required by PEP 440 + return f"{tag}.dev{distance}+{remainder}" + + # Avoid crashing if the development version cannot be determined. + return f"{tag}.dev0+gunknown" + + version = get_version(tag) + + def get_commit(tag: str, version: str) -> str: + # Extract commit from version, falling back to tag if not available. + version_re = r"[0-9.]+\.dev[0-9]+\+g([0-9a-f]{7,}|unknown)(?:\.dirty)?" + match = re.fullmatch(version_re, version) + if match is None: + raise ValueError(f"Unexpected version: {version}") + (commit,) = match.groups() + return tag if commit == "unknown" else commit + + commit = get_commit(tag, version) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel-0.47.0.dist-info/METADATA b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel-0.47.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..4824efd691bd43c24df8d404960db1561f931af3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel-0.47.0.dist-info/METADATA @@ -0,0 +1,66 @@ +Metadata-Version: 2.4 +Name: wheel +Version: 0.47.0 +Summary: Command line tool for manipulating wheel files +Keywords: wheel,packaging +Author-email: Daniel Holth +Maintainer-email: Alex Grönholm +Requires-Python: >=3.9 +Description-Content-Type: text/x-rst +License-Expression: MIT +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Topic :: System :: Archiving :: Packaging +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +License-File: LICENSE.txt +Requires-Dist: packaging >= 24.0 +Project-URL: Changelog, https://wheel.readthedocs.io/en/stable/news.html +Project-URL: Documentation, https://wheel.readthedocs.io/ +Project-URL: Issue Tracker, https://github.com/pypa/wheel/issues +Project-URL: Source, https://github.com/pypa/wheel + +wheel +===== + +This is a command line tool for manipulating Python wheel files, as defined in +`PEP 427`_. It contains the following functionality: + +* Convert ``.egg`` archives into ``.whl`` +* Unpack wheel archives +* Repack wheel archives +* Add or remove tags in existing wheel archives + +.. _PEP 427: https://peps.python.org/pep-0427/ + +Historical note +--------------- + +This project used to contain the implementation of the setuptools_ ``bdist_wheel`` +command, but as of setuptools v70.1, it no longer needs ``wheel`` installed for that to +work. Thus, you should install this **only** if you intend to use the ``wheel`` command +line tool! + +.. _setuptools: https://pypi.org/project/setuptools/ + +Documentation +------------- + +The documentation_ can be found on Read The Docs. + +.. _documentation: https://wheel.readthedocs.io/ + +Code of Conduct +--------------- + +Everyone interacting in the wheel project's codebases, issue trackers, chat +rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_. + +.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel-0.47.0.dist-info/RECORD b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel-0.47.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..9ed691d975273e34e6fd1ce3d8cae7d0114c4bac --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel-0.47.0.dist-info/RECORD @@ -0,0 +1,21 @@ +../../../bin/wheel,sha256=9qA3eYHsaprwr4O2kOsCypQyT04JTVNUQuMy7i4XhvU,497 +wheel-0.47.0.dist-info/METADATA,sha256=1ujLv6IVE-1GvkAn5heEsTGxLFyvrL3mkTzlrQF2dkM,2282 +wheel-0.47.0.dist-info/RECORD,, +wheel-0.47.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +wheel-0.47.0.dist-info/entry_points.txt,sha256=JJdtSAGTvMLbIkTVZUAMvGKO39FtWfCVF8mp_NH6e4g,110 +wheel-0.47.0.dist-info/licenses/LICENSE.txt,sha256=MMI2GGeRCPPo6h0qZYx8pBe9_IkcmO8aifpP8MmChlQ,1107 +wheel/__init__.py,sha256=hvOb7D5MtyR4b9_B_vS_nn6LevSY3Z4cItbGpnQKO20,59 +wheel/__main__.py,sha256=2H-pZZw-0uFWPYT46XjFt7wUi7eJ1afPXwocKkDzXXM,516 +wheel/_bdist_wheel.py,sha256=bpmNa7_s-CYFkVgXf9ENAYTiJ01XBhRW4pxH1T8XYsI,21729 +wheel/_commands/__init__.py,sha256=agjM7BnNxNU93HBm9eb-9zVn5wRB8pWPXNMfPB1QsJk,4964 +wheel/_commands/convert.py,sha256=0wSJMU0m-6LY16Om8Wmmloy-hJWFZeOmI8hT-2Z7Qms,12743 +wheel/_commands/info.py,sha256=GzV4h1sovB3DYsCCNQ5CYzavbA0z2EU2d1e1qqi9mH0,4446 +wheel/_commands/pack.py,sha256=o3iwjfRHl7N9ul-M2kHbewLJZnqBLAWf0tzUCwoiTMw,3078 +wheel/_commands/tags.py,sha256=Rv2ySVb8-qX3osKp3uJgxcIMXkjt43XUD0-zvC6KvnY,4775 +wheel/_commands/unpack.py,sha256=AjDSS23XYyCSFfifnMutinrpPv-DK_2wbNHkKAUFwgM,1016 +wheel/_metadata.py,sha256=BP5jC9uC1hyicp7nL4FJ2LYixNFpEJIV_uMDY1KBZBg,6188 +wheel/_setuptools_logging.py,sha256=-5KC-lne0ilOUWIDfOkqapUWGMFZhuKYDIavIZiB5kM,781 +wheel/bdist_wheel.py,sha256=HrzYiSzMkh5ohAAhlQnYBS1p8qbr85X6F59xqxd9kBg,1102 +wheel/macosx_libfile.py,sha256=pL0wm88jRMl_4ASgGlNg_mz69Zmv5xm8JSkjLdwyvIQ,16712 +wheel/metadata.py,sha256=GknOO7JJiZMlcEe_fiD7nqnDTTLd0sX_-IgipM4L3-4,757 +wheel/wheelfile.py,sha256=Lr-hlD6vlagOoXjHkJseN7bKD4qsWQlsPBaB5QnJrVs,9288 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel-0.47.0.dist-info/WHEEL b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel-0.47.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel-0.47.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/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel-0.47.0.dist-info/entry_points.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel-0.47.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..dcebd58811da1ee2758dd0f45c575704afdd61bd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel-0.47.0.dist-info/entry_points.txt @@ -0,0 +1,6 @@ +[console_scripts] +wheel=wheel._commands:main + +[distutils.commands] +bdist_wheel=wheel.bdist_wheel:bdist_wheel + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel-0.47.0.dist-info/licenses/LICENSE.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel-0.47.0.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..a31470f14c5978d5fcc3bc173b8399b6c9a6443f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel-0.47.0.dist-info/licenses/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2012 Daniel Holth and contributors + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0d9049b66070777a9aefae62b1f20fc39753d776 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__init__.py @@ -0,0 +1,3 @@ +from __future__ import annotations + +__version__ = "0.47.0" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__main__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..ce9a58d3b945a810109aaa3211f091630c19d72b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__main__.py @@ -0,0 +1,25 @@ +""" +Wheel command line tool (enables the ``python -m wheel`` syntax) +""" + +from __future__ import annotations + +import sys +from typing import NoReturn + + +def main() -> NoReturn: # needed for console script + if __spec__.parent == "": + # To be able to run 'python wheel-0.9.whl/wheel': + import os.path + + path = os.path.dirname(os.path.dirname(__file__)) + sys.path[0:0] = [path] + + from ._commands import main as cli_main + + sys.exit(cli_main()) + + +if __name__ == "__main__": + main() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e858bcb7809fc1bd193f3e1ea0c31b0ed4cbdcf7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/__main__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/__main__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65a52c7da672a7aeb487b3dbe6b0a97f2dd45790 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/__main__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/_bdist_wheel.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/_bdist_wheel.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02668fcc0e38fe26398a0a34b544b221ec4402ab Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/_bdist_wheel.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/_metadata.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/_metadata.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a031a546b761af5f1efde1a2ff5d7852e5c0834e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/_metadata.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/_setuptools_logging.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/_setuptools_logging.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e822ea0667b90beebb3433515792e98bb050c2de Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/_setuptools_logging.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/bdist_wheel.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/bdist_wheel.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6650e5cf605916e20dacb229c169ce20b7101d45 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/bdist_wheel.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/macosx_libfile.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/macosx_libfile.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..564c681b4d36421724c000be7313d9d2e837e43f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/macosx_libfile.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/metadata.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/metadata.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb1867fb5de00ec8407a1d11394419a41c4c871e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/metadata.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/wheelfile.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/wheelfile.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e0f72db2cad4f2475a462d2fa5a9f8f9e4b086b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/__pycache__/wheelfile.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_bdist_wheel.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_bdist_wheel.py new file mode 100644 index 0000000000000000000000000000000000000000..575fbfb35105eb82faee5a368781ecf818379354 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_bdist_wheel.py @@ -0,0 +1,616 @@ +""" +Create a wheel (.whl) distribution. + +A wheel is a built archive format. +""" + +from __future__ import annotations + +import logging +import os +import re +import shutil +import stat +import struct +import sys +import sysconfig +import warnings +from collections.abc import Iterable, Sequence +from email.generator import BytesGenerator, Generator +from email.policy import EmailPolicy +from glob import iglob +from shutil import rmtree +from typing import TYPE_CHECKING, Callable, Literal, cast +from zipfile import ZIP_DEFLATED, ZIP_STORED + +import setuptools +from packaging import tags +from packaging import version as _packaging_version +from setuptools import Command + +from . import __version__ as wheel_version +from ._metadata import pkginfo_to_metadata +from .wheelfile import WheelFile + +if TYPE_CHECKING: + import types + +# ensure Python logging is configured +try: + __import__("setuptools.logging") +except ImportError: + # setuptools < ?? + from . import _setuptools_logging + + _setuptools_logging.configure() + +log = logging.getLogger("wheel") + + +def safe_name(name: str) -> str: + """Convert an arbitrary string to a standard distribution name + Any runs of non-alphanumeric/. characters are replaced with a single '-'. + """ + return re.sub("[^A-Za-z0-9.]+", "-", name) + + +def safe_version(version: str) -> str: + """ + Convert an arbitrary string to a standard version string + """ + try: + # normalize the version + return str(_packaging_version.Version(version)) + except _packaging_version.InvalidVersion: + version = version.replace(" ", ".") + return re.sub("[^A-Za-z0-9.]+", "-", version) + + +setuptools_major_version = int(setuptools.__version__.split(".")[0]) + +PY_LIMITED_API_PATTERN = r"cp3\d" + + +def _is_32bit_interpreter() -> bool: + return struct.calcsize("P") == 4 + + +def python_tag() -> str: + return f"py{sys.version_info[0]}" + + +def get_platform(archive_root: str | None) -> str: + """Return our platform name 'win32', 'linux_x86_64'""" + result = sysconfig.get_platform() + if result.startswith("macosx") and archive_root is not None: + from .macosx_libfile import calculate_macosx_platform_tag + + result = calculate_macosx_platform_tag(archive_root, result) + elif _is_32bit_interpreter(): + if result == "linux-x86_64": + # pip pull request #3497 + result = "linux-i686" + elif result == "linux-aarch64": + # packaging pull request #234 + # TODO armv8l, packaging pull request #690 => this did not land + # in pip/packaging yet + result = "linux-armv7l" + + return result.replace("-", "_") + + +def get_flag( + var: str, fallback: bool, expected: bool = True, warn: bool = True +) -> bool: + """Use a fallback value for determining SOABI flags if the needed config + var is unset or unavailable.""" + val = sysconfig.get_config_var(var) + if val is None: + if warn: + warnings.warn( + f"Config variable '{var}' is unset, Python ABI tag may be incorrect", + RuntimeWarning, + stacklevel=2, + ) + return fallback + return val == expected + + +def get_abi_tag() -> str | None: + """Return the ABI tag based on SOABI (if available) or emulate SOABI (PyPy2).""" + soabi: str = sysconfig.get_config_var("SOABI") + impl = tags.interpreter_name() + if not soabi and impl in ("cp", "pp") and hasattr(sys, "maxunicode"): + d = "" + m = "" + u = "" + if get_flag("Py_DEBUG", hasattr(sys, "gettotalrefcount"), warn=(impl == "cp")): + d = "d" + + if get_flag( + "WITH_PYMALLOC", + impl == "cp", + warn=(impl == "cp" and sys.version_info < (3, 8)), + ) and sys.version_info < (3, 8): + m = "m" + + abi = f"{impl}{tags.interpreter_version()}{d}{m}{u}" + elif soabi and impl == "cp" and soabi.startswith("cpython"): + # non-Windows + abi = "cp" + soabi.split("-")[1] + elif soabi and impl == "cp" and soabi.startswith("cp"): + # Windows + abi = soabi.split("-")[0] + elif soabi and impl == "pp": + # we want something like pypy36-pp73 + abi = "-".join(soabi.split("-")[:2]) + abi = abi.replace(".", "_").replace("-", "_") + elif soabi and impl == "graalpy": + abi = "-".join(soabi.split("-")[:3]) + abi = abi.replace(".", "_").replace("-", "_") + elif soabi: + abi = soabi.replace(".", "_").replace("-", "_") + else: + abi = None + + return abi + + +def safer_name(name: str) -> str: + return safe_name(name).replace("-", "_") + + +def safer_version(version: str) -> str: + return safe_version(version).replace("-", "_") + + +def remove_readonly( + func: Callable[..., object], + path: str, + excinfo: tuple[type[Exception], Exception, types.TracebackType], +) -> None: + remove_readonly_exc(func, path, excinfo[1]) + + +def remove_readonly_exc(func: Callable[..., object], path: str, exc: Exception) -> None: + os.chmod(path, stat.S_IWRITE) + func(path) + + +class bdist_wheel(Command): + description = "create a wheel distribution" + + supported_compressions = { + "stored": ZIP_STORED, + "deflated": ZIP_DEFLATED, + } + + user_options = [ + ("bdist-dir=", "b", "temporary directory for creating the distribution"), + ( + "plat-name=", + "p", + "platform name to embed in generated filenames " + f"(default: {get_platform(None)})", + ), + ( + "keep-temp", + "k", + "keep the pseudo-installation tree around after " + "creating the distribution archive", + ), + ("dist-dir=", "d", "directory to put final built distributions in"), + ("skip-build", None, "skip rebuilding everything (for testing/debugging)"), + ( + "relative", + None, + "build the archive using relative paths (default: false)", + ), + ( + "owner=", + "u", + "Owner name used when creating a tar file [default: current user]", + ), + ( + "group=", + "g", + "Group name used when creating a tar file [default: current group]", + ), + ("universal", None, "make a universal wheel (default: false)"), + ( + "compression=", + None, + "zipfile compression (one of: {}) (default: 'deflated')".format( + ", ".join(supported_compressions) + ), + ), + ( + "python-tag=", + None, + f"Python implementation compatibility tag (default: '{python_tag()}')", + ), + ( + "build-number=", + None, + "Build number for this particular version. " + "As specified in PEP-0427, this must start with a digit. " + "[default: None]", + ), + ( + "py-limited-api=", + None, + "Python tag (cp32|cp33|cpNN) for abi3 wheel tag (default: false)", + ), + ] + + boolean_options = ["keep-temp", "skip-build", "relative", "universal"] + + def initialize_options(self): + self.bdist_dir: str = None + self.data_dir = None + self.plat_name: str | None = None + self.plat_tag = None + self.format = "zip" + self.keep_temp = False + self.dist_dir: str | None = None + self.egginfo_dir = None + self.root_is_pure: bool | None = None + self.skip_build = None + self.relative = False + self.owner = None + self.group = None + self.universal: bool = False + self.compression: str | int = "deflated" + self.python_tag: str = python_tag() + self.build_number: str | None = None + self.py_limited_api: str | Literal[False] = False + self.plat_name_supplied = False + + def finalize_options(self): + if self.bdist_dir is None: + bdist_base = self.get_finalized_command("bdist").bdist_base + self.bdist_dir = os.path.join(bdist_base, "wheel") + + egg_info = self.distribution.get_command_obj("egg_info") + egg_info.ensure_finalized() # needed for correct `wheel_dist_name` + + self.data_dir = self.wheel_dist_name + ".data" + self.plat_name_supplied = self.plat_name is not None + + try: + self.compression = self.supported_compressions[self.compression] + except KeyError: + raise ValueError(f"Unsupported compression: {self.compression}") from None + + need_options = ("dist_dir", "plat_name", "skip_build") + + self.set_undefined_options("bdist", *zip(need_options, need_options)) + + self.root_is_pure = not ( + self.distribution.has_ext_modules() or self.distribution.has_c_libraries() + ) + + if self.py_limited_api and not re.match( + PY_LIMITED_API_PATTERN, self.py_limited_api + ): + raise ValueError(f"py-limited-api must match '{PY_LIMITED_API_PATTERN}'") + + # Support legacy [wheel] section for setting universal + wheel = self.distribution.get_option_dict("wheel") + if "universal" in wheel: + # please don't define this in your global configs + log.warning( + "The [wheel] section is deprecated. Use [bdist_wheel] instead.", + ) + val = wheel["universal"][1].strip() + if val.lower() in ("1", "true", "yes"): + self.universal = True + + if self.build_number is not None and not self.build_number[:1].isdigit(): + raise ValueError("Build tag (build-number) must start with a digit.") + + @property + def wheel_dist_name(self): + """Return distribution full name with - replaced with _""" + components = ( + safer_name(self.distribution.get_name()), + safer_version(self.distribution.get_version()), + ) + if self.build_number: + components += (self.build_number,) + return "-".join(components) + + def get_tag(self) -> tuple[str, str, str]: + # bdist sets self.plat_name if unset, we should only use it for purepy + # wheels if the user supplied it. + if self.plat_name_supplied: + plat_name = cast(str, self.plat_name) + elif self.root_is_pure: + plat_name = "any" + else: + # macosx contains system version in platform name so need special handle + if self.plat_name and not self.plat_name.startswith("macosx"): + plat_name = self.plat_name + else: + # on macosx always limit the platform name to comply with any + # c-extension modules in bdist_dir, since the user can specify + # a higher MACOSX_DEPLOYMENT_TARGET via tools like CMake + + # on other platforms, and on macosx if there are no c-extension + # modules, use the default platform name. + plat_name = get_platform(self.bdist_dir) + + if _is_32bit_interpreter(): + if plat_name in ("linux-x86_64", "linux_x86_64"): + plat_name = "linux_i686" + if plat_name in ("linux-aarch64", "linux_aarch64"): + # TODO armv8l, packaging pull request #690 => this did not land + # in pip/packaging yet + plat_name = "linux_armv7l" + + plat_name = ( + plat_name.lower().replace("-", "_").replace(".", "_").replace(" ", "_") + ) + + if self.root_is_pure: + if self.universal: + impl = "py2.py3" + else: + impl = self.python_tag + tag = (impl, "none", plat_name) + else: + impl_name = tags.interpreter_name() + impl_ver = tags.interpreter_version() + impl = impl_name + impl_ver + # We don't work on CPython 3.1, 3.0. + if self.py_limited_api and (impl_name + impl_ver).startswith("cp3"): + impl = self.py_limited_api + abi_tag = "abi3" + else: + abi_tag = str(get_abi_tag()).lower() + tag = (impl, abi_tag, plat_name) + # issue gh-374: allow overriding plat_name + supported_tags = [ + (t.interpreter, t.abi, plat_name) for t in tags.sys_tags() + ] + assert tag in supported_tags, ( + f"would build wheel with unsupported tag {tag}" + ) + return tag + + def run(self): + build_scripts = self.reinitialize_command("build_scripts") + build_scripts.executable = "python" + build_scripts.force = True + + build_ext = self.reinitialize_command("build_ext") + build_ext.inplace = False + + if not self.skip_build: + self.run_command("build") + + install = self.reinitialize_command("install", reinit_subcommands=True) + install.root = self.bdist_dir + install.compile = False + install.skip_build = self.skip_build + install.warn_dir = False + + # A wheel without setuptools scripts is more cross-platform. + # Use the (undocumented) `no_ep` option to setuptools' + # install_scripts command to avoid creating entry point scripts. + install_scripts = self.reinitialize_command("install_scripts") + install_scripts.no_ep = True + + # Use a custom scheme for the archive, because we have to decide + # at installation time which scheme to use. + for key in ("headers", "scripts", "data", "purelib", "platlib"): + setattr(install, "install_" + key, os.path.join(self.data_dir, key)) + + basedir_observed = "" + + if os.name == "nt": + # win32 barfs if any of these are ''; could be '.'? + # (distutils.command.install:change_roots bug) + basedir_observed = os.path.normpath(os.path.join(self.data_dir, "..")) + self.install_libbase = self.install_lib = basedir_observed + + setattr( + install, + "install_purelib" if self.root_is_pure else "install_platlib", + basedir_observed, + ) + + log.info(f"installing to {self.bdist_dir}") + + self.run_command("install") + + impl_tag, abi_tag, plat_tag = self.get_tag() + archive_basename = f"{self.wheel_dist_name}-{impl_tag}-{abi_tag}-{plat_tag}" + if not self.relative: + archive_root = self.bdist_dir + else: + archive_root = os.path.join( + self.bdist_dir, self._ensure_relative(install.install_base) + ) + + self.set_undefined_options("install_egg_info", ("target", "egginfo_dir")) + distinfo_dirname = ( + f"{safer_name(self.distribution.get_name())}-" + f"{safer_version(self.distribution.get_version())}.dist-info" + ) + distinfo_dir = os.path.join(self.bdist_dir, distinfo_dirname) + self.egg2dist(self.egginfo_dir, distinfo_dir) + + self.write_wheelfile(distinfo_dir) + + # Make the archive + if not os.path.exists(self.dist_dir): + os.makedirs(self.dist_dir) + + wheel_path = os.path.join(self.dist_dir, archive_basename + ".whl") + with WheelFile(wheel_path, "w", self.compression) as wf: + wf.write_files(archive_root) + + # Add to 'Distribution.dist_files' so that the "upload" command works + getattr(self.distribution, "dist_files", []).append( + ( + "bdist_wheel", + "{}.{}".format(*sys.version_info[:2]), # like 3.7 + wheel_path, + ) + ) + + if not self.keep_temp: + log.info(f"removing {self.bdist_dir}") + if not self.dry_run: + if sys.version_info < (3, 12): + rmtree(self.bdist_dir, onerror=remove_readonly) + else: + rmtree(self.bdist_dir, onexc=remove_readonly_exc) + + def write_wheelfile( + self, wheelfile_base: str, generator: str = f"bdist_wheel ({wheel_version})" + ): + from email.message import Message + + msg = Message() + msg["Wheel-Version"] = "1.0" # of the spec + msg["Generator"] = generator + msg["Root-Is-Purelib"] = str(self.root_is_pure).lower() + if self.build_number is not None: + msg["Build"] = self.build_number + + # Doesn't work for bdist_wininst + impl_tag, abi_tag, plat_tag = self.get_tag() + for impl in impl_tag.split("."): + for abi in abi_tag.split("."): + for plat in plat_tag.split("."): + msg["Tag"] = "-".join((impl, abi, plat)) + + wheelfile_path = os.path.join(wheelfile_base, "WHEEL") + log.info(f"creating {wheelfile_path}") + with open(wheelfile_path, "wb") as f: + BytesGenerator(f, maxheaderlen=0).flatten(msg) + + def _ensure_relative(self, path: str) -> str: + # copied from dir_util, deleted + drive, path = os.path.splitdrive(path) + if path[0:1] == os.sep: + path = drive + path[1:] + return path + + @property + def license_paths(self) -> Iterable[str]: + if setuptools_major_version >= 57: + # Setuptools has resolved any patterns to actual file names + return self.distribution.metadata.license_files or () + + files: set[str] = set() + metadata = self.distribution.get_option_dict("metadata") + if setuptools_major_version >= 42: + # Setuptools recognizes the license_files option but does not do globbing + patterns = cast(Sequence[str], self.distribution.metadata.license_files) + else: + # Prior to those, wheel is entirely responsible for handling license files + if "license_files" in metadata: + patterns = metadata["license_files"][1].split() + else: + patterns = () + + if "license_file" in metadata: + warnings.warn( + 'The "license_file" option is deprecated. Use "license_files" instead.', + DeprecationWarning, + stacklevel=2, + ) + files.add(metadata["license_file"][1]) + + if not files and not patterns and not isinstance(patterns, list): + patterns = ("LICEN[CS]E*", "COPYING*", "NOTICE*", "AUTHORS*") + + for pattern in patterns: + for path in iglob(pattern): + if path.endswith("~"): + log.debug( + f'ignoring license file "{path}" as it looks like a backup' + ) + continue + + if path not in files and os.path.isfile(path): + log.info( + f'adding license file "{path}" (matched pattern "{pattern}")' + ) + files.add(path) + + return files + + def egg2dist(self, egginfo_path: str, distinfo_path: str): + """Convert an .egg-info directory into a .dist-info directory""" + + def adios(p: str) -> None: + """Appropriately delete directory, file or link.""" + if os.path.exists(p) and not os.path.islink(p) and os.path.isdir(p): + shutil.rmtree(p) + elif os.path.exists(p): + os.unlink(p) + + adios(distinfo_path) + + if not os.path.exists(egginfo_path): + # There is no egg-info. This is probably because the egg-info + # file/directory is not named matching the distribution name used + # to name the archive file. Check for this case and report + # accordingly. + import glob + + pat = os.path.join(os.path.dirname(egginfo_path), "*.egg-info") + possible = glob.glob(pat) + err = f"Egg metadata expected at {egginfo_path} but not found" + if possible: + alt = os.path.basename(possible[0]) + err += f" ({alt} found - possible misnamed archive file?)" + + raise ValueError(err) + + if os.path.isfile(egginfo_path): + # .egg-info is a single file + pkg_info = pkginfo_to_metadata(egginfo_path, egginfo_path) + os.mkdir(distinfo_path) + else: + # .egg-info is a directory + pkginfo_path = os.path.join(egginfo_path, "PKG-INFO") + pkg_info = pkginfo_to_metadata(egginfo_path, pkginfo_path) + + # ignore common egg metadata that is useless to wheel + shutil.copytree( + egginfo_path, + distinfo_path, + ignore=lambda x, y: { + "PKG-INFO", + "requires.txt", + "SOURCES.txt", + "not-zip-safe", + }, + ) + + # delete dependency_links if it is only whitespace + dependency_links_path = os.path.join(distinfo_path, "dependency_links.txt") + with open(dependency_links_path, encoding="utf-8") as dependency_links_file: + dependency_links = dependency_links_file.read().strip() + if not dependency_links: + adios(dependency_links_path) + + pkg_info_path = os.path.join(distinfo_path, "METADATA") + serialization_policy = EmailPolicy( + utf8=True, + mangle_from_=False, + max_line_length=0, + ) + with open(pkg_info_path, "w", encoding="utf-8") as out: + Generator(out, policy=serialization_policy).flatten(pkg_info) + + for license_path in self.license_paths: + filename = os.path.basename(license_path) + shutil.copy(license_path, os.path.join(distinfo_path, filename)) + + adios(egginfo_path) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c60772c671e4deb14d3c4daf33d1c94759b7ebb1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/__init__.py @@ -0,0 +1,169 @@ +""" +Wheel command-line utility. +""" + +from __future__ import annotations + +import argparse +import os +import sys +from argparse import ArgumentTypeError + +from ..wheelfile import WheelError + + +def unpack_f(args: argparse.Namespace) -> None: + from .unpack import unpack + + unpack(args.wheelfile, args.dest) + + +def pack_f(args: argparse.Namespace) -> None: + from .pack import pack + + pack(args.directory, args.dest_dir, args.build_number) + + +def convert_f(args: argparse.Namespace) -> None: + from .convert import convert + + convert(args.files, args.dest_dir, args.verbose) + + +def tags_f(args: argparse.Namespace) -> None: + from .tags import tags + + names = ( + tags( + wheel, + args.python_tag, + args.abi_tag, + args.platform_tag, + args.build, + args.remove, + ) + for wheel in args.wheel + ) + + for name in names: + print(name) + + +def info_f(args: argparse.Namespace) -> None: + from .info import info + + try: + info(args.wheelfile, args.verbose) + except FileNotFoundError as e: + raise WheelError(str(e)) from e + + +def version_f(args: argparse.Namespace) -> None: + from .. import __version__ + + print(f"wheel {__version__}") + + +def parse_build_tag(build_tag: str) -> str: + if build_tag and not build_tag[0].isdigit(): + raise ArgumentTypeError("build tag must begin with a digit") + elif "-" in build_tag: + raise ArgumentTypeError("invalid character ('-') in build tag") + + return build_tag + + +TAGS_HELP = """\ +Make a new wheel with given tags. Any tags unspecified will remain the same. +Starting the tags with a "+" will append to the existing tags. Starting with a +"-" will remove a tag (use --option=-TAG syntax). Multiple tags can be +separated by ".". The original file will remain unless --remove is given. The +output filename(s) will be displayed on stdout for further processing. +""" + + +def parser() -> argparse.ArgumentParser: + p = argparse.ArgumentParser() + s = p.add_subparsers(help="commands") + + unpack_parser = s.add_parser("unpack", help="Unpack wheel") + unpack_parser.add_argument( + "--dest", "-d", help="Destination directory", default="." + ) + unpack_parser.add_argument("wheelfile", help="Wheel file") + unpack_parser.set_defaults(func=unpack_f) + + repack_parser = s.add_parser("pack", help="Repack wheel") + repack_parser.add_argument("directory", help="Root directory of the unpacked wheel") + repack_parser.add_argument( + "--dest-dir", + "-d", + default=os.path.curdir, + help="Directory to store the wheel (default %(default)s)", + ) + repack_parser.add_argument( + "--build-number", help="Build tag to use in the wheel name" + ) + repack_parser.set_defaults(func=pack_f) + + convert_parser = s.add_parser("convert", help="Convert egg or wininst to wheel") + convert_parser.add_argument("files", nargs="*", help="Files to convert") + convert_parser.add_argument( + "--dest-dir", + "-d", + default=os.path.curdir, + help="Directory to store wheels (default %(default)s)", + ) + convert_parser.add_argument("--verbose", "-v", action="store_true") + convert_parser.set_defaults(func=convert_f) + + tags_parser = s.add_parser( + "tags", help="Add or replace the tags on a wheel", description=TAGS_HELP + ) + tags_parser.add_argument("wheel", nargs="*", help="Existing wheel(s) to retag") + tags_parser.add_argument( + "--remove", + action="store_true", + help="Remove the original files, keeping only the renamed ones", + ) + tags_parser.add_argument( + "--python-tag", metavar="TAG", help="Specify an interpreter tag(s)" + ) + tags_parser.add_argument("--abi-tag", metavar="TAG", help="Specify an ABI tag(s)") + tags_parser.add_argument( + "--platform-tag", metavar="TAG", help="Specify a platform tag(s)" + ) + tags_parser.add_argument( + "--build", type=parse_build_tag, metavar="BUILD", help="Specify a build tag" + ) + tags_parser.set_defaults(func=tags_f) + + info_parser = s.add_parser("info", help="Show information about a wheel file") + info_parser.add_argument("wheelfile", help="Wheel file to show information for") + info_parser.add_argument( + "--verbose", "-v", action="store_true", help="Show detailed file listing" + ) + info_parser.set_defaults(func=info_f) + + version_parser = s.add_parser("version", help="Print version and exit") + version_parser.set_defaults(func=version_f) + + help_parser = s.add_parser("help", help="Show this help") + help_parser.set_defaults(func=lambda args: p.print_help()) + + return p + + +def main() -> int: + p = parser() + args = p.parse_args() + if not hasattr(args, "func"): + p.print_help() + else: + try: + args.func(args) + return 0 + except WheelError as e: + print(e, file=sys.stderr) + + return 1 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17c9397c54e111d7f4cb095f23a57f996b60ff85 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/__pycache__/convert.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/__pycache__/convert.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56f04ffef1b6c9bb2707fb4f4830e6f38f984468 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/__pycache__/convert.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/__pycache__/info.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/__pycache__/info.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..665601746e10693c825e62d5e69083e46bb7e97e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/__pycache__/info.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/__pycache__/pack.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/__pycache__/pack.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76aec61dd1fdb9e5da77079939b3792556d771ab Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/__pycache__/pack.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/__pycache__/tags.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/__pycache__/tags.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2e4e204b1571edf329a8286ec5be1da007def02 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/__pycache__/tags.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/__pycache__/unpack.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/__pycache__/unpack.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7ac2d64dd6c2daf4511218694c2354e222b0190 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/__pycache__/unpack.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/convert.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..cafd12c86cbc0a661e69b9243ec5525a95274c9e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/convert.py @@ -0,0 +1,337 @@ +from __future__ import annotations + +import os.path +import re +from abc import ABCMeta, abstractmethod +from collections import defaultdict +from collections.abc import Iterator +from email.message import Message +from email.parser import Parser +from email.policy import EmailPolicy +from glob import iglob +from pathlib import Path +from textwrap import dedent +from zipfile import ZipFile + +from packaging.tags import parse_tag + +from .. import __version__ +from .._metadata import generate_requirements +from ..wheelfile import WheelFile + +egg_filename_re = re.compile( + r""" + (?P.+?)-(?P.+?) + (-(?Ppy\d\.\d+) + (-(?P.+?))? + )?.egg$""", + re.VERBOSE, +) +egg_info_re = re.compile( + r""" + ^(?P.+?)-(?P.+?) + (-(?Ppy\d\.\d+) + )?.egg-info/""", + re.VERBOSE, +) +wininst_re = re.compile( + r"\.(?Pwin32|win-amd64)(?:-(?Ppy\d\.\d))?\.exe$" +) +pyd_re = re.compile(r"\.(?P[a-z0-9]+)-(?Pwin32|win_amd64)\.pyd$") +serialization_policy = EmailPolicy( + utf8=True, + mangle_from_=False, + max_line_length=0, +) +GENERATOR = f"wheel {__version__}" + + +def convert_requires(requires: str, metadata: Message) -> None: + extra: str | None = None + requirements: dict[str | None, list[str]] = defaultdict(list) + for line in requires.splitlines(): + line = line.strip() + if not line: + continue + + if line.startswith("[") and line.endswith("]"): + extra = line[1:-1] + continue + + requirements[extra].append(line) + + for key, value in generate_requirements(requirements): + metadata.add_header(key, value) + + +def convert_pkg_info(pkginfo: str, metadata: Message) -> None: + parsed_message = Parser().parsestr(pkginfo) + for key, value in parsed_message.items(): + key_lower = key.lower() + if value == "UNKNOWN": + continue + + if key_lower == "description": + description_lines = value.splitlines() + if description_lines: + value = "\n".join( + ( + description_lines[0].lstrip(), + dedent("\n".join(description_lines[1:])), + "\n", + ) + ) + else: + value = "\n" + + metadata.set_payload(value) + elif key_lower == "home-page": + metadata.add_header("Project-URL", f"Homepage, {value}") + elif key_lower == "download-url": + metadata.add_header("Project-URL", f"Download, {value}") + else: + metadata.add_header(key, value) + + metadata.replace_header("Metadata-Version", "2.4") + + +def normalize(name: str) -> str: + return re.sub(r"[-_.]+", "-", name).lower().replace("-", "_") + + +class ConvertSource(metaclass=ABCMeta): + name: str + version: str + pyver: str = "py2.py3" + abi: str = "none" + platform: str = "any" + metadata: Message + + @property + def dist_info_dir(self) -> str: + return f"{self.name}-{self.version}.dist-info" + + @abstractmethod + def generate_contents(self) -> Iterator[tuple[str, bytes]]: + pass + + +class EggFileSource(ConvertSource): + def __init__(self, path: Path): + if not (match := egg_filename_re.match(path.name)): + raise ValueError(f"Invalid egg file name: {path.name}") + + # Binary wheels are assumed to be for CPython + self.path = path + self.name = normalize(match.group("name")) + self.version = match.group("ver") + if pyver := match.group("pyver"): + self.pyver = pyver.replace(".", "") + if arch := match.group("arch"): + self.abi = self.pyver.replace("py", "cp") + self.platform = normalize(arch) + + self.metadata = Message() + + def generate_contents(self) -> Iterator[tuple[str, bytes]]: + with ZipFile(self.path, "r") as zip_file: + for filename in sorted(zip_file.namelist()): + # Skip pure directory entries + if filename.endswith("/"): + continue + + # Handle files in the egg-info directory specially, selectively moving + # them to the dist-info directory while converting as needed + if filename.startswith("EGG-INFO/"): + if filename == "EGG-INFO/requires.txt": + requires = zip_file.read(filename).decode("utf-8") + convert_requires(requires, self.metadata) + elif filename == "EGG-INFO/PKG-INFO": + pkginfo = zip_file.read(filename).decode("utf-8") + convert_pkg_info(pkginfo, self.metadata) + elif filename == "EGG-INFO/entry_points.txt": + yield ( + f"{self.dist_info_dir}/entry_points.txt", + zip_file.read(filename), + ) + + continue + + # For any other file, just pass it through + yield filename, zip_file.read(filename) + + +class EggDirectorySource(EggFileSource): + def generate_contents(self) -> Iterator[tuple[str, bytes]]: + for dirpath, _, filenames in os.walk(self.path): + for filename in sorted(filenames): + path = Path(dirpath, filename) + if path.parent.name == "EGG-INFO": + if path.name == "requires.txt": + requires = path.read_text("utf-8") + convert_requires(requires, self.metadata) + elif path.name == "PKG-INFO": + pkginfo = path.read_text("utf-8") + convert_pkg_info(pkginfo, self.metadata) + if name := self.metadata.get("Name"): + self.name = normalize(name) + + if version := self.metadata.get("Version"): + self.version = version + elif path.name == "entry_points.txt": + yield ( + f"{self.dist_info_dir}/entry_points.txt", + path.read_bytes(), + ) + + continue + + # For any other file, just pass it through + yield str(path.relative_to(self.path)), path.read_bytes() + + +class WininstFileSource(ConvertSource): + """ + Handles distributions created with ``bdist_wininst``. + + The egginfo filename has the format:: + + name-ver(-pyver)(-arch).egg-info + + The installer filename has the format:: + + name-ver.arch(-pyver).exe + + Some things to note: + + 1. The installer filename is not definitive. An installer can be renamed + and work perfectly well as an installer. So more reliable data should + be used whenever possible. + 2. The egg-info data should be preferred for the name and version, because + these come straight from the distutils metadata, and are mandatory. + 3. The pyver from the egg-info data should be ignored, as it is + constructed from the version of Python used to build the installer, + which is irrelevant - the installer filename is correct here (even to + the point that when it's not there, any version is implied). + 4. The architecture must be taken from the installer filename, as it is + not included in the egg-info data. + 5. Architecture-neutral installers still have an architecture because the + installer format itself (being executable) is architecture-specific. We + should therefore ignore the architecture if the content is pure-python. + """ + + def __init__(self, path: Path): + self.path = path + self.metadata = Message() + + # Determine the initial architecture and Python version from the file name + # (if possible) + if match := wininst_re.search(path.name): + self.platform = normalize(match.group("platform")) + if pyver := match.group("pyver"): + self.pyver = pyver.replace(".", "") + + # Look for an .egg-info directory and any .pyd files for more precise info + egg_info_found = pyd_found = False + with ZipFile(self.path) as zip_file: + for filename in zip_file.namelist(): + prefix, filename = filename.split("/", 1) + if not egg_info_found and (match := egg_info_re.match(filename)): + egg_info_found = True + self.name = normalize(match.group("name")) + self.version = match.group("ver") + if pyver := match.group("pyver"): + self.pyver = pyver.replace(".", "") + elif not pyd_found and (match := pyd_re.search(filename)): + pyd_found = True + self.abi = match.group("abi") + self.platform = match.group("platform") + + if egg_info_found and pyd_found: + break + + def generate_contents(self) -> Iterator[tuple[str, bytes]]: + dist_info_dir = f"{self.name}-{self.version}.dist-info" + data_dir = f"{self.name}-{self.version}.data" + with ZipFile(self.path, "r") as zip_file: + for filename in sorted(zip_file.namelist()): + # Skip pure directory entries + if filename.endswith("/"): + continue + + # Handle files in the egg-info directory specially, selectively moving + # them to the dist-info directory while converting as needed + prefix, target_filename = filename.split("/", 1) + if egg_info_re.search(target_filename): + basename = target_filename.rsplit("/", 1)[-1] + if basename == "requires.txt": + requires = zip_file.read(filename).decode("utf-8") + convert_requires(requires, self.metadata) + elif basename == "PKG-INFO": + pkginfo = zip_file.read(filename).decode("utf-8") + convert_pkg_info(pkginfo, self.metadata) + elif basename == "entry_points.txt": + yield ( + f"{dist_info_dir}/entry_points.txt", + zip_file.read(filename), + ) + + continue + elif prefix == "SCRIPTS": + target_filename = f"{data_dir}/scripts/{target_filename}" + + # For any other file, just pass it through + yield target_filename, zip_file.read(filename) + + +def convert(files: list[str], dest_dir: str, verbose: bool) -> None: + for pat in files: + for archive in iglob(pat): + path = Path(archive) + if path.suffix == ".egg": + if path.is_dir(): + source: ConvertSource = EggDirectorySource(path) + else: + source = EggFileSource(path) + else: + source = WininstFileSource(path) + + if verbose: + print(f"{archive}...", flush=True, end="") + + dest_path = Path(dest_dir) / ( + f"{source.name}-{source.version}-{source.pyver}-{source.abi}" + f"-{source.platform}.whl" + ) + with WheelFile(dest_path, "w") as wheelfile: + for name_or_zinfo, contents in source.generate_contents(): + wheelfile.writestr(name_or_zinfo, contents) + + # Write the METADATA file + wheelfile.writestr( + f"{source.dist_info_dir}/METADATA", + source.metadata.as_string(policy=serialization_policy).encode( + "utf-8" + ), + ) + + # Write the WHEEL file + wheel_message = Message() + wheel_message.add_header("Wheel-Version", "1.0") + wheel_message.add_header("Generator", GENERATOR) + wheel_message.add_header( + "Root-Is-Purelib", str(source.platform == "any").lower() + ) + tags = parse_tag(f"{source.pyver}-{source.abi}-{source.platform}") + for tag in sorted(tags, key=lambda tag: tag.interpreter): + wheel_message.add_header("Tag", str(tag)) + + wheelfile.writestr( + f"{source.dist_info_dir}/WHEEL", + wheel_message.as_string(policy=serialization_policy).encode( + "utf-8" + ), + ) + + if verbose: + print("OK") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/info.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/info.py new file mode 100644 index 0000000000000000000000000000000000000000..27ad47a28601e939f11714c49c809490d10763c3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/info.py @@ -0,0 +1,124 @@ +""" +Display information about wheel files. +""" + +from __future__ import annotations + +import email.policy +import sys +from email.parser import BytesParser +from pathlib import Path + +from ..wheelfile import WheelFile + + +def info(path: str, verbose: bool = False) -> None: + """Display information about a wheel file. + + :param path: The path to the wheel file + :param verbose: Show detailed file listing + """ + wheel_path = Path(path) + if not wheel_path.exists(): + raise FileNotFoundError(f"Wheel file not found: {path}") + + with WheelFile(path) as wf: + # Extract basic wheel information from filename + parsed = wf.parsed_filename + name = parsed.group("name") + version = parsed.group("ver") + build_tag = parsed.group("build") + + print(f"Name: {name}") + print(f"Version: {version}") + if build_tag: + print(f"Build: {build_tag}") + + # Read WHEEL metadata + try: + with wf.open(f"{wf.dist_info_path}/WHEEL") as wheel_file: + wheel_metadata = BytesParser(policy=email.policy.compat32).parse( + wheel_file + ) + + print( + f"Wheel-Version: {wheel_metadata.get('Wheel-Version', 'Unknown')}" + ) + print( + f"Root-Is-Purelib: {wheel_metadata.get('Root-Is-Purelib', 'Unknown')}" + ) + + # Get all tags + tags = wheel_metadata.get_all("Tag", []) + if tags: + print("Tags:") + for tag in sorted(tags): # Sort tags for consistent output + print(f" {tag}") + + generators = wheel_metadata.get_all("Generator", []) + for generator in generators: + print(f"Generator: {generator}") + except KeyError: + print("Warning: WHEEL metadata file not found", file=sys.stderr) + + # Read package METADATA + try: + with wf.open(f"{wf.dist_info_path}/METADATA") as metadata_file: + pkg_metadata = BytesParser(policy=email.policy.compat32).parse( + metadata_file + ) + + summary = pkg_metadata.get("Summary", "") + if summary and summary != "UNKNOWN": + print(f"Summary: {summary}") + + author = pkg_metadata.get("Author", "") + if author and author != "UNKNOWN": + print(f"Author: {author}") + + author_email = pkg_metadata.get("Author-email") + if author_email and author_email != "UNKNOWN": + print(f"Author-email: {author_email}") + + homepage = pkg_metadata.get("Home-page") + if homepage and homepage != "UNKNOWN": + print(f"Home-page: {homepage}") + + license_info = pkg_metadata.get("License") + if license_info and license_info != "UNKNOWN": + print(f"License: {license_info}") + + # Show classifiers + classifiers = pkg_metadata.get_all("Classifier", []) + if classifiers: + print("Classifiers:") + for classifier in sorted( + classifiers[:5] + ): # Sort and limit to first 5 + print(f" {classifier}") + + if len(classifiers) > 5: + print(f" ... and {len(classifiers) - 5} more") + + # Show dependencies + requires_dist = pkg_metadata.get_all("Requires-Dist", []) + if requires_dist: + print("Requires-Dist:") + for req in sorted(requires_dist): # Sort dependencies + print(f" {req}") + except KeyError: + print("Warning: METADATA file not found", file=sys.stderr) + + # File information + file_count = len(wf.filelist) + total_size = sum(zinfo.file_size for zinfo in wf.filelist) + + print(f"Files: {file_count}") + print(f"Size: {total_size:,} bytes") + + # Show file listing if verbose + if verbose: + print("\nFile listing:") + for zinfo in wf.filelist: + size_str = f"{zinfo.file_size:,}" if zinfo.file_size > 0 else "0" + print(f" {zinfo.filename:60} {size_str:>10} bytes") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/pack.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..1321ce9308a68f00cf2f839d4ba02869c16ec26f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/pack.py @@ -0,0 +1,84 @@ +from __future__ import annotations + +import email.policy +import os.path +import re +from email.generator import BytesGenerator +from email.parser import BytesParser + +from ..wheelfile import WheelError, WheelFile + +DIST_INFO_RE = re.compile(r"^(?P(?P.+?)-(?P\d.*?))\.dist-info$") + + +def pack(directory: str, dest_dir: str, build_number: str | None) -> None: + """Repack a previously unpacked wheel directory into a new wheel file. + + The .dist-info/WHEEL file must contain one or more tags so that the target + wheel file name can be determined. + + :param directory: The unpacked wheel directory + :param dest_dir: Destination directory (defaults to the current directory) + """ + # Find the .dist-info directory + dist_info_dirs = [ + fn + for fn in os.listdir(directory) + if os.path.isdir(os.path.join(directory, fn)) and DIST_INFO_RE.match(fn) + ] + if len(dist_info_dirs) > 1: + raise WheelError(f"Multiple .dist-info directories found in {directory}") + elif not dist_info_dirs: + raise WheelError(f"No .dist-info directories found in {directory}") + + # Determine the target wheel filename + dist_info_dir = dist_info_dirs[0] + name_version = DIST_INFO_RE.match(dist_info_dir).group("namever") + + # Read the tags and the existing build number from .dist-info/WHEEL + wheel_file_path = os.path.join(directory, dist_info_dir, "WHEEL") + with open(wheel_file_path, "rb") as f: + info = BytesParser(policy=email.policy.compat32).parse(f) + tags: list[str] = info.get_all("Tag", []) + existing_build_number = info.get("Build") + + if not tags: + raise WheelError( + f"No tags present in {dist_info_dir}/WHEEL; cannot determine target " + f"wheel filename" + ) + + # Set the wheel file name and add/replace/remove the Build tag in .dist-info/WHEEL + build_number = build_number if build_number is not None else existing_build_number + if build_number is not None: + del info["Build"] + if build_number: + info["Build"] = build_number + name_version += "-" + build_number + + if build_number != existing_build_number: + with open(wheel_file_path, "wb") as f: + BytesGenerator(f, maxheaderlen=0).flatten(info) + + # Reassemble the tags for the wheel file + tagline = compute_tagline(tags) + + # Repack the wheel + wheel_path = os.path.join(dest_dir, f"{name_version}-{tagline}.whl") + with WheelFile(wheel_path, "w") as wf: + print(f"Repacking wheel as {wheel_path}...", end="", flush=True) + wf.write_files(directory) + + print("OK") + + +def compute_tagline(tags: list[str]) -> str: + """Compute a tagline from a list of tags. + + :param tags: A list of tags + :return: A tagline + """ + impls = sorted({tag.split("-")[0] for tag in tags}) + abivers = sorted({tag.split("-")[1] for tag in tags}) + platforms = sorted({tag.split("-")[2] for tag in tags}) + return "-".join([".".join(impls), ".".join(abivers), ".".join(platforms)]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/tags.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/tags.py new file mode 100644 index 0000000000000000000000000000000000000000..cec896b55b726d29a53f10e06d06b79e645b2e94 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/tags.py @@ -0,0 +1,140 @@ +from __future__ import annotations + +import email.policy +import itertools +import os +from collections.abc import Iterable +from email.parser import BytesParser + +from ..wheelfile import WheelFile + + +def _compute_tags(original_tags: Iterable[str], new_tags: str | None) -> set[str]: + """Add or replace tags. Supports dot-separated tags""" + if new_tags is None: + return set(original_tags) + + if new_tags.startswith("+"): + return {*original_tags, *new_tags[1:].split(".")} + + if new_tags.startswith("-"): + return set(original_tags) - set(new_tags[1:].split(".")) + + return set(new_tags.split(".")) + + +def tags( + wheel: str, + python_tags: str | None = None, + abi_tags: str | None = None, + platform_tags: str | None = None, + build_tag: str | None = None, + remove: bool = False, +) -> str: + """Change the tags on a wheel file. + + The tags are left unchanged if they are not specified. To specify "none", + use ["none"]. To append to the previous tags, a tag should start with a + "+". If a tag starts with "-", it will be removed from existing tags. + Processing is done left to right. + + :param wheel: The paths to the wheels + :param python_tags: The Python tags to set + :param abi_tags: The ABI tags to set + :param platform_tags: The platform tags to set + :param build_tag: The build tag to set + :param remove: Remove the original wheel + """ + with WheelFile(wheel, "r") as f: + assert f.filename, f"{f.filename} must be available" + + wheel_info = f.read(f.dist_info_path + "/WHEEL") + info = BytesParser(policy=email.policy.compat32).parsebytes(wheel_info) + + original_wheel_name = os.path.basename(f.filename) + namever = f.parsed_filename.group("namever") + build = f.parsed_filename.group("build") + original_python_tags = f.parsed_filename.group("pyver").split(".") + original_abi_tags = f.parsed_filename.group("abi").split(".") + original_plat_tags = f.parsed_filename.group("plat").split(".") + + tags: list[str] = info.get_all("Tag", []) + existing_build_tag = info.get("Build") + + impls = {tag.split("-")[0] for tag in tags} + abivers = {tag.split("-")[1] for tag in tags} + platforms = {tag.split("-")[2] for tag in tags} + + if impls != set(original_python_tags): + msg = f"Wheel internal tags {impls!r} != filename tags {original_python_tags!r}" + raise AssertionError(msg) + + if abivers != set(original_abi_tags): + msg = f"Wheel internal tags {abivers!r} != filename tags {original_abi_tags!r}" + raise AssertionError(msg) + + if platforms != set(original_plat_tags): + msg = ( + f"Wheel internal tags {platforms!r} != filename tags {original_plat_tags!r}" + ) + raise AssertionError(msg) + + if existing_build_tag != build: + msg = ( + f"Incorrect filename '{build}' " + f"& *.dist-info/WHEEL '{existing_build_tag}' build numbers" + ) + raise AssertionError(msg) + + # Start changing as needed + if build_tag is not None: + build = build_tag + + final_python_tags = sorted(_compute_tags(original_python_tags, python_tags)) + final_abi_tags = sorted(_compute_tags(original_abi_tags, abi_tags)) + final_plat_tags = sorted(_compute_tags(original_plat_tags, platform_tags)) + + final_tags = [ + namever, + ".".join(final_python_tags), + ".".join(final_abi_tags), + ".".join(final_plat_tags), + ] + if build: + final_tags.insert(1, build) + + final_wheel_name = "-".join(final_tags) + ".whl" + + if original_wheel_name != final_wheel_name: + del info["Tag"], info["Build"] + for a, b, c in itertools.product( + final_python_tags, final_abi_tags, final_plat_tags + ): + info["Tag"] = f"{a}-{b}-{c}" + if build: + info["Build"] = build + + original_wheel_path = os.path.join( + os.path.dirname(f.filename), original_wheel_name + ) + final_wheel_path = os.path.join(os.path.dirname(f.filename), final_wheel_name) + + with ( + WheelFile(original_wheel_path, "r") as fin, + WheelFile(final_wheel_path, "w") as fout, + ): + fout.comment = fin.comment # preserve the comment + for item in fin.infolist(): + if item.is_dir(): + continue + if item.filename == f.dist_info_path + "/RECORD": + continue + if item.filename == f.dist_info_path + "/WHEEL": + fout.writestr(item, info.as_bytes()) + else: + fout.writestr(item, fin.read(item)) + + if remove: + os.remove(original_wheel_path) + + return final_wheel_name diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/unpack.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/unpack.py new file mode 100644 index 0000000000000000000000000000000000000000..83dc7423f8171a3b6ffd6641475af037b7c59495 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_commands/unpack.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +from pathlib import Path + +from ..wheelfile import WheelFile + + +def unpack(path: str, dest: str = ".") -> None: + """Unpack a wheel. + + Wheel content will be unpacked to {dest}/{name}-{ver}, where {name} + is the package name and {ver} its version. + + :param path: The path to the wheel. + :param dest: Destination directory (default to current directory). + """ + with WheelFile(path) as wf: + namever = wf.parsed_filename.group("namever") + destination = Path(dest) / namever + print(f"Unpacking to: {destination}...", end="", flush=True) + for zinfo in wf.filelist: + target_path = Path(wf.extract(zinfo, destination)) + + # Set permissions to the same values as they were set in the archive + # We have to do this manually due to + # https://github.com/python/cpython/issues/59999 + permissions = zinfo.external_attr >> 16 & 0o777 + target_path.chmod(permissions) + + print("OK") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_metadata.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..e17a7b924526b9fcad83fc44996f17695dea0161 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_metadata.py @@ -0,0 +1,184 @@ +""" +Tools for converting old- to new-style metadata. +""" + +from __future__ import annotations + +import functools +import itertools +import os.path +import re +import textwrap +from collections.abc import Generator, Iterable, Iterator +from email.message import Message +from email.parser import Parser +from typing import Literal + +from packaging.requirements import Requirement + + +def _nonblank(str: str) -> bool | Literal[""]: + return str and not str.startswith("#") + + +@functools.singledispatch +def yield_lines(iterable: Iterable[str]) -> Iterator[str]: + r""" + Yield valid lines of a string or iterable. + >>> list(yield_lines('')) + [] + >>> list(yield_lines(['foo', 'bar'])) + ['foo', 'bar'] + >>> list(yield_lines('foo\nbar')) + ['foo', 'bar'] + >>> list(yield_lines('\nfoo\n#bar\nbaz #comment')) + ['foo', 'baz #comment'] + >>> list(yield_lines(['foo\nbar', 'baz', 'bing\n\n\n'])) + ['foo', 'bar', 'baz', 'bing'] + """ + return itertools.chain.from_iterable(map(yield_lines, iterable)) + + +@yield_lines.register(str) +def _(text: str) -> Iterator[str]: + return filter(_nonblank, map(str.strip, text.splitlines())) + + +def split_sections( + s: str | Iterator[str], +) -> Generator[tuple[str | None, list[str]], None, None]: + """Split a string or iterable thereof into (section, content) pairs + Each ``section`` is a stripped version of the section header ("[section]") + and each ``content`` is a list of stripped lines excluding blank lines and + comment-only lines. If there are any such lines before the first section + header, they're returned in a first ``section`` of ``None``. + """ + section = None + content: list[str] = [] + for line in yield_lines(s): + if line.startswith("["): + if line.endswith("]"): + if section or content: + yield section, content + section = line[1:-1].strip() + content = [] + else: + raise ValueError("Invalid section heading", line) + else: + content.append(line) + + # wrap up last segment + yield section, content + + +def safe_extra(extra: str) -> str: + """Convert an arbitrary string to a standard 'extra' name + Any runs of non-alphanumeric characters are replaced with a single '_', + and the result is always lowercased. + """ + return re.sub("[^A-Za-z0-9.-]+", "_", extra).lower() + + +def safe_name(name: str) -> str: + """Convert an arbitrary string to a standard distribution name + Any runs of non-alphanumeric/. characters are replaced with a single '-'. + """ + return re.sub("[^A-Za-z0-9.]+", "-", name) + + +def requires_to_requires_dist(requirement: Requirement) -> str: + """Return the version specifier for a requirement in PEP 345/566 fashion.""" + if requirement.url: + return " @ " + requirement.url + + requires_dist: list[str] = [] + for spec in requirement.specifier: + requires_dist.append(spec.operator + spec.version) + + if requires_dist: + return " " + ",".join(sorted(requires_dist)) + else: + return "" + + +def convert_requirements(requirements: list[str]) -> Iterator[str]: + """Yield Requires-Dist: strings for parsed requirements strings.""" + for req in requirements: + parsed_requirement = Requirement(req) + spec = requires_to_requires_dist(parsed_requirement) + extras = ",".join(sorted(safe_extra(e) for e in parsed_requirement.extras)) + if extras: + extras = f"[{extras}]" + + yield safe_name(parsed_requirement.name) + extras + spec + + +def generate_requirements( + extras_require: dict[str | None, list[str]], +) -> Iterator[tuple[str, str]]: + """ + Convert requirements from a setup()-style dictionary to + ('Requires-Dist', 'requirement') and ('Provides-Extra', 'extra') tuples. + + extras_require is a dictionary of {extra: [requirements]} as passed to setup(), + using the empty extra {'': [requirements]} to hold install_requires. + """ + for extra, depends in extras_require.items(): + condition = "" + extra = extra or "" + if ":" in extra: # setuptools extra:condition syntax + extra, condition = extra.split(":", 1) + + extra = safe_extra(extra) + if extra: + yield "Provides-Extra", extra + if condition: + condition = "(" + condition + ") and " + condition += f"extra == '{extra}'" + + if condition: + condition = " ; " + condition + + for new_req in convert_requirements(depends): + canonical_req = str(Requirement(new_req + condition)) + yield "Requires-Dist", canonical_req + + +def pkginfo_to_metadata(egg_info_path: str, pkginfo_path: str) -> Message: + """ + Convert .egg-info directory with PKG-INFO to the Metadata 2.1 format + """ + with open(pkginfo_path, encoding="utf-8") as headers: + pkg_info = Parser().parse(headers) + + pkg_info.replace_header("Metadata-Version", "2.1") + # Those will be regenerated from `requires.txt`. + del pkg_info["Provides-Extra"] + del pkg_info["Requires-Dist"] + requires_path = os.path.join(egg_info_path, "requires.txt") + if os.path.exists(requires_path): + with open(requires_path, encoding="utf-8") as requires_file: + requires = requires_file.read() + + parsed_requirements = sorted(split_sections(requires), key=lambda x: x[0] or "") + for extra, reqs in parsed_requirements: + for key, value in generate_requirements({extra: reqs}): + if (key, value) not in pkg_info.items(): + pkg_info[key] = value + + description = pkg_info["Description"] + if description: + description_lines = pkg_info["Description"].splitlines() + dedented_description = "\n".join( + # if the first line of long_description is blank, + # the first line here will be indented. + ( + description_lines[0].lstrip(), + textwrap.dedent("\n".join(description_lines[1:])), + "\n", + ) + ) + pkg_info.set_payload(dedented_description) + del pkg_info["Description"] + + return pkg_info diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_setuptools_logging.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_setuptools_logging.py new file mode 100644 index 0000000000000000000000000000000000000000..a1a2482ba29ac5290c8f7d7688452ec3faf59332 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/_setuptools_logging.py @@ -0,0 +1,26 @@ +# copied from setuptools.logging, omitting monkeypatching +from __future__ import annotations + +import logging +import sys + + +def _not_warning(record: logging.LogRecord) -> bool: + return record.levelno < logging.WARNING + + +def configure() -> None: + """ + Configure logging to emit warning and above to stderr + and everything else to stdout. This behavior is provided + for compatibility with distutils.log but may change in + the future. + """ + err_handler = logging.StreamHandler() + err_handler.setLevel(logging.WARNING) + out_handler = logging.StreamHandler(sys.stdout) + out_handler.addFilter(_not_warning) + handlers = err_handler, out_handler + logging.basicConfig( + format="{message}", style="{", handlers=handlers, level=logging.DEBUG + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/bdist_wheel.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/bdist_wheel.py new file mode 100644 index 0000000000000000000000000000000000000000..24199c246d44a6874ad991c2f3492ca30fc10f27 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/bdist_wheel.py @@ -0,0 +1,26 @@ +from typing import TYPE_CHECKING +from warnings import warn + +warn( + "The 'wheel' package is no longer the canonical location of the 'bdist_wheel' " + "command, and will be removed in a future release. Please update to setuptools " + "v70.1 or later which contains an integrated version of this command.", + FutureWarning, + stacklevel=1, +) + +if TYPE_CHECKING: + from ._bdist_wheel import bdist_wheel as bdist_wheel +else: + try: + # Better integration/compatibility with setuptools: + # in the case new fixes or PEPs are implemented in setuptools + # there is no need to backport them to the deprecated code base. + # This is useful in the case of old packages in the ecosystem + # that are still used but have low maintenance. + from setuptools.command.bdist_wheel import bdist_wheel + except ImportError: + # Only used in the case of old setuptools versions. + # If the user wants to get the latest fixes/PEPs, + # they are encouraged to address the deprecation warning. + from ._bdist_wheel import bdist_wheel as bdist_wheel diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/macosx_libfile.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/macosx_libfile.py new file mode 100644 index 0000000000000000000000000000000000000000..06e51af299d0fe15f7618f803cfb8ff52d199cf7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/macosx_libfile.py @@ -0,0 +1,486 @@ +""" +IMPORTANT: DO NOT IMPORT THIS MODULE DIRECTLY. +THIS IS ONLY KEPT IN PLACE FOR BACKWARDS COMPATIBILITY WITH +setuptools.command.bdist_wheel. + +This module contains function to analyse dynamic library +headers to extract system information + +Currently only for MacOSX + +Library file on macosx system starts with Mach-O or Fat field. +This can be distinguish by first 32 bites and it is called magic number. +Proper value of magic number is with suffix _MAGIC. Suffix _CIGAM means +reversed bytes order. +Both fields can occur in two types: 32 and 64 bytes. + +FAT field inform that this library contains few version of library +(typically for different types version). It contains +information where Mach-O headers starts. + +Each section started with Mach-O header contains one library +(So if file starts with this field it contains only one version). + +After filed Mach-O there are section fields. +Each of them starts with two fields: +cmd - magic number for this command +cmdsize - total size occupied by this section information. + +In this case only sections LC_VERSION_MIN_MACOSX (for macosx 10.13 and earlier) +and LC_BUILD_VERSION (for macosx 10.14 and newer) are interesting, +because them contains information about minimal system version. + +Important remarks: +- For fat files this implementation looks for maximum number version. + It not check if it is 32 or 64 and do not compare it with currently built package. + So it is possible to false report higher version that needed. +- All structures signatures are taken form macosx header files. +- I think that binary format will be more stable than `otool` output. + and if apple introduce some changes both implementation will need to be updated. +- The system compile will set the deployment target no lower than + 11.0 for arm64 builds. For "Universal 2" builds use the x86_64 deployment + target when the arm64 target is 11.0. +""" + +from __future__ import annotations + +import ctypes +import os +import sys +from io import BufferedIOBase +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from typing import Union + + StrPath = Union[str, os.PathLike[str]] + +"""here the needed const and struct from mach-o header files""" + +FAT_MAGIC = 0xCAFEBABE +FAT_CIGAM = 0xBEBAFECA +FAT_MAGIC_64 = 0xCAFEBABF +FAT_CIGAM_64 = 0xBFBAFECA +MH_MAGIC = 0xFEEDFACE +MH_CIGAM = 0xCEFAEDFE +MH_MAGIC_64 = 0xFEEDFACF +MH_CIGAM_64 = 0xCFFAEDFE + +LC_VERSION_MIN_MACOSX = 0x24 +LC_BUILD_VERSION = 0x32 + +CPU_TYPE_ARM64 = 0x0100000C + +mach_header_fields = [ + ("magic", ctypes.c_uint32), + ("cputype", ctypes.c_int), + ("cpusubtype", ctypes.c_int), + ("filetype", ctypes.c_uint32), + ("ncmds", ctypes.c_uint32), + ("sizeofcmds", ctypes.c_uint32), + ("flags", ctypes.c_uint32), +] +""" +struct mach_header { + uint32_t magic; /* mach magic number identifier */ + cpu_type_t cputype; /* cpu specifier */ + cpu_subtype_t cpusubtype; /* machine specifier */ + uint32_t filetype; /* type of file */ + uint32_t ncmds; /* number of load commands */ + uint32_t sizeofcmds; /* the size of all the load commands */ + uint32_t flags; /* flags */ +}; +typedef integer_t cpu_type_t; +typedef integer_t cpu_subtype_t; +""" + +mach_header_fields_64 = mach_header_fields + [("reserved", ctypes.c_uint32)] +""" +struct mach_header_64 { + uint32_t magic; /* mach magic number identifier */ + cpu_type_t cputype; /* cpu specifier */ + cpu_subtype_t cpusubtype; /* machine specifier */ + uint32_t filetype; /* type of file */ + uint32_t ncmds; /* number of load commands */ + uint32_t sizeofcmds; /* the size of all the load commands */ + uint32_t flags; /* flags */ + uint32_t reserved; /* reserved */ +}; +""" + +fat_header_fields = [("magic", ctypes.c_uint32), ("nfat_arch", ctypes.c_uint32)] +""" +struct fat_header { + uint32_t magic; /* FAT_MAGIC or FAT_MAGIC_64 */ + uint32_t nfat_arch; /* number of structs that follow */ +}; +""" + +fat_arch_fields = [ + ("cputype", ctypes.c_int), + ("cpusubtype", ctypes.c_int), + ("offset", ctypes.c_uint32), + ("size", ctypes.c_uint32), + ("align", ctypes.c_uint32), +] +""" +struct fat_arch { + cpu_type_t cputype; /* cpu specifier (int) */ + cpu_subtype_t cpusubtype; /* machine specifier (int) */ + uint32_t offset; /* file offset to this object file */ + uint32_t size; /* size of this object file */ + uint32_t align; /* alignment as a power of 2 */ +}; +""" + +fat_arch_64_fields = [ + ("cputype", ctypes.c_int), + ("cpusubtype", ctypes.c_int), + ("offset", ctypes.c_uint64), + ("size", ctypes.c_uint64), + ("align", ctypes.c_uint32), + ("reserved", ctypes.c_uint32), +] +""" +struct fat_arch_64 { + cpu_type_t cputype; /* cpu specifier (int) */ + cpu_subtype_t cpusubtype; /* machine specifier (int) */ + uint64_t offset; /* file offset to this object file */ + uint64_t size; /* size of this object file */ + uint32_t align; /* alignment as a power of 2 */ + uint32_t reserved; /* reserved */ +}; +""" + +segment_base_fields = [("cmd", ctypes.c_uint32), ("cmdsize", ctypes.c_uint32)] +"""base for reading segment info""" + +segment_command_fields = [ + ("cmd", ctypes.c_uint32), + ("cmdsize", ctypes.c_uint32), + ("segname", ctypes.c_char * 16), + ("vmaddr", ctypes.c_uint32), + ("vmsize", ctypes.c_uint32), + ("fileoff", ctypes.c_uint32), + ("filesize", ctypes.c_uint32), + ("maxprot", ctypes.c_int), + ("initprot", ctypes.c_int), + ("nsects", ctypes.c_uint32), + ("flags", ctypes.c_uint32), +] +""" +struct segment_command { /* for 32-bit architectures */ + uint32_t cmd; /* LC_SEGMENT */ + uint32_t cmdsize; /* includes sizeof section structs */ + char segname[16]; /* segment name */ + uint32_t vmaddr; /* memory address of this segment */ + uint32_t vmsize; /* memory size of this segment */ + uint32_t fileoff; /* file offset of this segment */ + uint32_t filesize; /* amount to map from the file */ + vm_prot_t maxprot; /* maximum VM protection */ + vm_prot_t initprot; /* initial VM protection */ + uint32_t nsects; /* number of sections in segment */ + uint32_t flags; /* flags */ +}; +typedef int vm_prot_t; +""" + +segment_command_fields_64 = [ + ("cmd", ctypes.c_uint32), + ("cmdsize", ctypes.c_uint32), + ("segname", ctypes.c_char * 16), + ("vmaddr", ctypes.c_uint64), + ("vmsize", ctypes.c_uint64), + ("fileoff", ctypes.c_uint64), + ("filesize", ctypes.c_uint64), + ("maxprot", ctypes.c_int), + ("initprot", ctypes.c_int), + ("nsects", ctypes.c_uint32), + ("flags", ctypes.c_uint32), +] +""" +struct segment_command_64 { /* for 64-bit architectures */ + uint32_t cmd; /* LC_SEGMENT_64 */ + uint32_t cmdsize; /* includes sizeof section_64 structs */ + char segname[16]; /* segment name */ + uint64_t vmaddr; /* memory address of this segment */ + uint64_t vmsize; /* memory size of this segment */ + uint64_t fileoff; /* file offset of this segment */ + uint64_t filesize; /* amount to map from the file */ + vm_prot_t maxprot; /* maximum VM protection */ + vm_prot_t initprot; /* initial VM protection */ + uint32_t nsects; /* number of sections in segment */ + uint32_t flags; /* flags */ +}; +""" + +version_min_command_fields = segment_base_fields + [ + ("version", ctypes.c_uint32), + ("sdk", ctypes.c_uint32), +] +""" +struct version_min_command { + uint32_t cmd; /* LC_VERSION_MIN_MACOSX or + LC_VERSION_MIN_IPHONEOS or + LC_VERSION_MIN_WATCHOS or + LC_VERSION_MIN_TVOS */ + uint32_t cmdsize; /* sizeof(struct min_version_command) */ + uint32_t version; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */ + uint32_t sdk; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */ +}; +""" + +build_version_command_fields = segment_base_fields + [ + ("platform", ctypes.c_uint32), + ("minos", ctypes.c_uint32), + ("sdk", ctypes.c_uint32), + ("ntools", ctypes.c_uint32), +] +""" +struct build_version_command { + uint32_t cmd; /* LC_BUILD_VERSION */ + uint32_t cmdsize; /* sizeof(struct build_version_command) plus */ + /* ntools * sizeof(struct build_tool_version) */ + uint32_t platform; /* platform */ + uint32_t minos; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */ + uint32_t sdk; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */ + uint32_t ntools; /* number of tool entries following this */ +}; +""" + + +def swap32(x: int) -> int: + return ( + ((x << 24) & 0xFF000000) + | ((x << 8) & 0x00FF0000) + | ((x >> 8) & 0x0000FF00) + | ((x >> 24) & 0x000000FF) + ) + + +def get_base_class_and_magic_number( + lib_file: BufferedIOBase, + seek: int | None = None, +) -> tuple[type[ctypes.Structure], int]: + if seek is None: + seek = lib_file.tell() + else: + lib_file.seek(seek) + magic_number = ctypes.c_uint32.from_buffer_copy( + lib_file.read(ctypes.sizeof(ctypes.c_uint32)) + ).value + + # Handle wrong byte order + if magic_number in [FAT_CIGAM, FAT_CIGAM_64, MH_CIGAM, MH_CIGAM_64]: + if sys.byteorder == "little": + BaseClass = ctypes.BigEndianStructure + else: + BaseClass = ctypes.LittleEndianStructure + + magic_number = swap32(magic_number) + else: + BaseClass = ctypes.Structure + + lib_file.seek(seek) + return BaseClass, magic_number + + +def read_data(struct_class: type[ctypes.Structure], lib_file: BufferedIOBase): + return struct_class.from_buffer_copy(lib_file.read(ctypes.sizeof(struct_class))) + + +def extract_macosx_min_system_version(path_to_lib: str): + with open(path_to_lib, "rb") as lib_file: + BaseClass, magic_number = get_base_class_and_magic_number(lib_file, 0) + if magic_number not in [FAT_MAGIC, FAT_MAGIC_64, MH_MAGIC, MH_MAGIC_64]: + return + + if magic_number in [FAT_MAGIC, FAT_CIGAM_64]: + + class FatHeader(BaseClass): + _fields_ = fat_header_fields + + fat_header = read_data(FatHeader, lib_file) + if magic_number == FAT_MAGIC: + + class FatArch(BaseClass): + _fields_ = fat_arch_fields + + else: + + class FatArch(BaseClass): + _fields_ = fat_arch_64_fields + + fat_arch_list = [ + read_data(FatArch, lib_file) for _ in range(fat_header.nfat_arch) + ] + + versions_list: list[tuple[int, int, int]] = [] + for el in fat_arch_list: + try: + version = read_mach_header(lib_file, el.offset) + if version is not None: + if el.cputype == CPU_TYPE_ARM64 and len(fat_arch_list) != 1: + # Xcode will not set the deployment target below 11.0.0 + # for the arm64 architecture. Ignore the arm64 deployment + # in fat binaries when the target is 11.0.0, that way + # the other architectures can select a lower deployment + # target. + # This is safe because there is no arm64 variant for + # macOS 10.15 or earlier. + if version == (11, 0, 0): + continue + versions_list.append(version) + except ValueError: + pass + + if len(versions_list) > 0: + return max(versions_list) + else: + return None + + else: + try: + return read_mach_header(lib_file, 0) + except ValueError: + """when some error during read library files""" + return None + + +def read_mach_header( + lib_file: BufferedIOBase, + seek: int | None = None, +) -> tuple[int, int, int] | None: + """ + This function parses a Mach-O header and extracts + information about the minimal macOS version. + + :param lib_file: reference to opened library file with pointer + """ + base_class, magic_number = get_base_class_and_magic_number(lib_file, seek) + arch = "32" if magic_number == MH_MAGIC else "64" + + class SegmentBase(base_class): + _fields_ = segment_base_fields + + if arch == "32": + + class MachHeader(base_class): + _fields_ = mach_header_fields + + else: + + class MachHeader(base_class): + _fields_ = mach_header_fields_64 + + mach_header = read_data(MachHeader, lib_file) + for _i in range(mach_header.ncmds): + pos = lib_file.tell() + segment_base = read_data(SegmentBase, lib_file) + lib_file.seek(pos) + if segment_base.cmd == LC_VERSION_MIN_MACOSX: + + class VersionMinCommand(base_class): + _fields_ = version_min_command_fields + + version_info = read_data(VersionMinCommand, lib_file) + return parse_version(version_info.version) + elif segment_base.cmd == LC_BUILD_VERSION: + + class VersionBuild(base_class): + _fields_ = build_version_command_fields + + version_info = read_data(VersionBuild, lib_file) + return parse_version(version_info.minos) + else: + lib_file.seek(pos + segment_base.cmdsize) + continue + + +def parse_version(version: int) -> tuple[int, int, int]: + x = (version & 0xFFFF0000) >> 16 + y = (version & 0x0000FF00) >> 8 + z = version & 0x000000FF + return x, y, z + + +def calculate_macosx_platform_tag(archive_root: StrPath, platform_tag: str) -> str: + """ + Calculate proper macosx platform tag basing on files which are included to wheel + + Example platform tag `macosx-10.14-x86_64` + """ + prefix, base_version, suffix = platform_tag.split("-") + base_version = tuple(int(x) for x in base_version.split(".")) + base_version = base_version[:2] + if base_version[0] > 10: + base_version = (base_version[0], 0) + assert len(base_version) == 2 + if "MACOSX_DEPLOYMENT_TARGET" in os.environ: + deploy_target = tuple( + int(x) for x in os.environ["MACOSX_DEPLOYMENT_TARGET"].split(".") + ) + deploy_target = deploy_target[:2] + if deploy_target[0] > 10: + deploy_target = (deploy_target[0], 0) + if deploy_target < base_version: + sys.stderr.write( + "[WARNING] MACOSX_DEPLOYMENT_TARGET is set to a lower value ({}) than " + "the version on which the Python interpreter was compiled ({}), and " + "will be ignored.\n".format( + ".".join(str(x) for x in deploy_target), + ".".join(str(x) for x in base_version), + ) + ) + else: + base_version = deploy_target + + assert len(base_version) == 2 + start_version = base_version + versions_dict: dict[str, tuple[int, int]] = {} + for dirpath, _dirnames, filenames in os.walk(archive_root): + for filename in filenames: + if filename.endswith(".dylib") or filename.endswith(".so"): + lib_path = os.path.join(dirpath, filename) + min_ver = extract_macosx_min_system_version(lib_path) + if min_ver is not None: + min_ver = min_ver[0:2] + if min_ver[0] > 10: + min_ver = (min_ver[0], 0) + versions_dict[lib_path] = min_ver + + if len(versions_dict) > 0: + base_version = max(base_version, max(versions_dict.values())) + + # macosx platform tag do not support minor bugfix release + fin_base_version = "_".join([str(x) for x in base_version]) + if start_version < base_version: + problematic_files = [k for k, v in versions_dict.items() if v > start_version] + problematic_files = "\n".join(problematic_files) + if len(problematic_files) == 1: + files_form = "this file" + else: + files_form = "these files" + error_message = ( + "[WARNING] This wheel needs a higher macOS version than {} " + "To silence this warning, set MACOSX_DEPLOYMENT_TARGET to at least " + + fin_base_version + + " or recreate " + + files_form + + " with lower " + "MACOSX_DEPLOYMENT_TARGET: \n" + problematic_files + ) + + if "MACOSX_DEPLOYMENT_TARGET" in os.environ: + error_message = error_message.format( + "is set in MACOSX_DEPLOYMENT_TARGET variable." + ) + else: + error_message = error_message.format( + "the version your Python interpreter is compiled against." + ) + + sys.stderr.write(error_message) + + platform_tag = prefix + "_" + fin_base_version + "_" + suffix + return platform_tag diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/metadata.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..e27900a2565c859ff32b0e4bf497c2548e4912de --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/metadata.py @@ -0,0 +1,17 @@ +from warnings import warn + +from ._metadata import convert_requirements as convert_requirements +from ._metadata import generate_requirements as generate_requirements +from ._metadata import pkginfo_to_metadata as pkginfo_to_metadata +from ._metadata import requires_to_requires_dist as requires_to_requires_dist +from ._metadata import safe_extra as safe_extra +from ._metadata import safe_name as safe_name +from ._metadata import split_sections as split_sections + +warn( + f"The {__name__!r} package has been made private and should no longer be imported. " + f"Please either copy the code or find an alternative library to import it from, as " + f"this warning will be removed in a future version of 'wheel'.", + DeprecationWarning, + stacklevel=2, +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/wheelfile.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/wheelfile.py new file mode 100644 index 0000000000000000000000000000000000000000..bb96a2ac706b8504c7c2556df20fe35eea02a083 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/wheel/wheelfile.py @@ -0,0 +1,252 @@ +from __future__ import annotations + +__all__ = ["WHEEL_INFO_RE", "WheelFile", "WheelError"] + +import base64 +import csv +import hashlib +import logging +import os.path +import re +import stat +import time +from io import StringIO, TextIOWrapper +from typing import IO, TYPE_CHECKING, Literal +from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo + +if TYPE_CHECKING: + from _typeshed import SizedBuffer, StrPath + + +# Non-greedy matching of an optional build number may be too clever (more +# invalid wheel filenames will match). Separate regex for .dist-info? +WHEEL_INFO_RE = re.compile( + r"""^(?P(?P[^\s-]+?)-(?P[^\s-]+?))(-(?P\d[^\s-]*))? + -(?P[^\s-]+?)-(?P[^\s-]+?)-(?P\S+)\.whl$""", + re.VERBOSE, +) +MINIMUM_TIMESTAMP = 315532800 # 1980-01-01 00:00:00 UTC + +log = logging.getLogger("wheel") + + +class WheelError(Exception): + pass + + +def urlsafe_b64encode(data: bytes) -> bytes: + """urlsafe_b64encode without padding""" + return base64.urlsafe_b64encode(data).rstrip(b"=") + + +def urlsafe_b64decode(data: bytes) -> bytes: + """urlsafe_b64decode without padding""" + pad = b"=" * (4 - (len(data) & 3)) + return base64.urlsafe_b64decode(data + pad) + + +def get_zipinfo_datetime( + timestamp: float | None = None, +) -> tuple[int, int, int, int, int]: + # Some applications need reproducible .whl files, but they can't do this without + # forcing the timestamp of the individual ZipInfo objects. See issue #143. + timestamp = int(os.environ.get("SOURCE_DATE_EPOCH", timestamp or time.time())) + timestamp = max(timestamp, MINIMUM_TIMESTAMP) + return time.gmtime(timestamp)[0:6] + + +class WheelFile(ZipFile): + """A ZipFile derivative class that also reads SHA-256 hashes from + .dist-info/RECORD and checks any read files against those. + """ + + _default_algorithm = hashlib.sha256 + + def __init__( + self, + file: StrPath, + mode: Literal["r", "w", "x", "a"] = "r", + compression: int = ZIP_DEFLATED, + ): + basename = os.path.basename(file) + self.parsed_filename = WHEEL_INFO_RE.match(basename) + if not basename.endswith(".whl") or self.parsed_filename is None: + raise WheelError(f"Bad wheel filename {basename!r}") + + ZipFile.__init__(self, file, mode, compression=compression, allowZip64=True) + + self.dist_info_path = "{}.dist-info".format( + self.parsed_filename.group("namever") + ) + self.record_path = self.dist_info_path + "/RECORD" + self._file_hashes: dict[str, tuple[None, None] | tuple[int, bytes]] = {} + self._file_sizes = {} + if mode == "r": + # The .dist-info directory inside the wheel may use normalized + # (lowercase) naming even when the filename does not. Resolve the + # actual path case-insensitively. + if self.record_path not in self.namelist(): + lowered = self.dist_info_path.lower() + "/record" + for name in self.namelist(): + if name.lower() == lowered: + self.dist_info_path = name.rsplit("/RECORD", 1)[0] + self.record_path = name + break + + # Ignore RECORD and any embedded wheel signatures + self._file_hashes[self.record_path] = None, None + self._file_hashes[self.record_path + ".jws"] = None, None + self._file_hashes[self.record_path + ".p7s"] = None, None + + # Fill in the expected hashes by reading them from RECORD + try: + record = self.open(self.record_path) + except KeyError: + raise WheelError(f"Missing {self.record_path} file") from None + + with record: + for line in csv.reader( + TextIOWrapper(record, newline="", encoding="utf-8") + ): + path, hash_sum, size = line + if not hash_sum: + continue + + algorithm, hash_sum = hash_sum.split("=") + try: + hashlib.new(algorithm) + except ValueError: + raise WheelError( + f"Unsupported hash algorithm: {algorithm}" + ) from None + + if algorithm.lower() in {"md5", "sha1"}: + raise WheelError( + f"Weak hash algorithm ({algorithm}) is not permitted by " + f"PEP 427" + ) + + self._file_hashes[path] = ( + algorithm, + urlsafe_b64decode(hash_sum.encode("ascii")), + ) + + def open( + self, + name_or_info: str | ZipInfo, + mode: Literal["r", "w"] = "r", + pwd: bytes | None = None, + ) -> IO[bytes]: + def _update_crc(newdata: bytes) -> None: + eof = ef._eof + update_crc_orig(newdata) + running_hash.update(newdata) + if eof and running_hash.digest() != expected_hash: + raise WheelError(f"Hash mismatch for file '{ef_name}'") + + ef_name = ( + name_or_info.filename if isinstance(name_or_info, ZipInfo) else name_or_info + ) + if ( + mode == "r" + and not ef_name.endswith("/") + and ef_name not in self._file_hashes + ): + raise WheelError(f"No hash found for file '{ef_name}'") + + ef = ZipFile.open(self, name_or_info, mode, pwd) + if mode == "r" and not ef_name.endswith("/"): + algorithm, expected_hash = self._file_hashes[ef_name] + if expected_hash is not None: + # Monkey patch the _update_crc method to also check for the hash from + # RECORD + running_hash = hashlib.new(algorithm) + update_crc_orig, ef._update_crc = ef._update_crc, _update_crc + + return ef + + def write_files(self, base_dir: str) -> None: + log.info("creating %r and adding %r to it", self.filename, base_dir) + deferred: list[tuple[str, str]] = [] + for root, dirnames, filenames in os.walk(base_dir): + # Sort the directory names so that `os.walk` will walk them in a + # defined order on the next iteration. + dirnames.sort() + for name in sorted(filenames): + path = os.path.normpath(os.path.join(root, name)) + if os.path.isfile(path): + arcname = os.path.relpath(path, base_dir).replace(os.path.sep, "/") + if arcname == self.record_path: + pass + elif root.endswith(".dist-info"): + deferred.append((path, arcname)) + else: + self.write(path, arcname) + + deferred.sort() + for path, arcname in deferred: + self.write(path, arcname) + + def write( + self, + filename: str, + arcname: str | None = None, + compress_type: int | None = None, + ) -> None: + with open(filename, "rb") as f: + st = os.fstat(f.fileno()) + data = f.read() + + zinfo = ZipInfo( + arcname or filename, date_time=get_zipinfo_datetime(st.st_mtime) + ) + zinfo.external_attr = (stat.S_IMODE(st.st_mode) | stat.S_IFMT(st.st_mode)) << 16 + zinfo.compress_type = compress_type or self.compression + self.writestr(zinfo, data, compress_type) + + def writestr( + self, + zinfo_or_arcname: str | ZipInfo, + data: SizedBuffer | str, + compress_type: int | None = None, + ) -> None: + if isinstance(zinfo_or_arcname, str): + zinfo_or_arcname = ZipInfo( + zinfo_or_arcname, date_time=get_zipinfo_datetime() + ) + zinfo_or_arcname.compress_type = self.compression + zinfo_or_arcname.external_attr = (0o664 | stat.S_IFREG) << 16 + + if isinstance(data, str): + data = data.encode("utf-8") + + ZipFile.writestr(self, zinfo_or_arcname, data, compress_type) + fname = ( + zinfo_or_arcname.filename + if isinstance(zinfo_or_arcname, ZipInfo) + else zinfo_or_arcname + ) + log.info("adding %r", fname) + if fname != self.record_path: + hash_ = self._default_algorithm(data) + self._file_hashes[fname] = ( + hash_.name, + urlsafe_b64encode(hash_.digest()).decode("ascii"), + ) + self._file_sizes[fname] = len(data) + + def close(self) -> None: + # Write RECORD + if self.fp is not None and self.mode == "w" and self._file_hashes: + data = StringIO() + writer = csv.writer(data, delimiter=",", quotechar='"', lineterminator="\n") + writer.writerows( + ( + (fname, algorithm + "=" + hash_, self._file_sizes[fname]) + for fname, (algorithm, hash_) in self._file_hashes.items() + ) + ) + writer.writerow((format(self.record_path), "", "")) + self.writestr(self.record_path, data.getvalue()) + + ZipFile.close(self) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash-3.7.0.dist-info/INSTALLER b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash-3.7.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash-3.7.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash-3.7.0.dist-info/METADATA b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash-3.7.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..b8d0e31f3f129d8fa2b269a98aff8f87a3c12472 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash-3.7.0.dist-info/METADATA @@ -0,0 +1,549 @@ +Metadata-Version: 2.4 +Name: xxhash +Version: 3.7.0 +Summary: Python binding for xxHash +Home-page: https://github.com/ifduyue/python-xxhash +Author: Yue Du +Author-email: ifduyue@gmail.com +License: BSD +Classifier: Development Status :: 5 - Production/Stable +Classifier: License :: OSI Approved :: BSD License +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Free Threading :: 1 - Unstable +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +License-File: LICENSE +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: requires-python +Dynamic: summary + +python-xxhash +============= + +.. image:: https://github.com/ifduyue/python-xxhash/actions/workflows/test.yml/badge.svg + :target: https://github.com/ifduyue/python-xxhash/actions/workflows/test.yml + :alt: Github Actions Status + +.. image:: https://img.shields.io/pypi/v/xxhash.svg + :target: https://pypi.org/project/xxhash/ + :alt: Latest Version + +.. image:: https://img.shields.io/pypi/pyversions/xxhash.svg + :target: https://pypi.org/project/xxhash/ + :alt: Supported Python versions + +.. image:: https://img.shields.io/pypi/l/xxhash.svg + :target: https://pypi.org/project/xxhash/ + :alt: License + + +.. _HMAC: http://en.wikipedia.org/wiki/Hash-based_message_authentication_code +.. _xxHash: https://github.com/Cyan4973/xxHash +.. _Cyan4973: https://github.com/Cyan4973 + + +xxhash is a Python binding for the xxHash_ library by `Yann Collet`__. + +__ Cyan4973_ + +Installation +------------ + +.. code-block:: bash + + $ pip install xxhash + +You can also install using conda: + +.. code-block:: bash + + $ conda install -c conda-forge python-xxhash + + +Installing From Source +~~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: bash + + $ pip install --no-binary xxhash xxhash + +Prerequisites +++++++++++++++ + +On Debian/Ubuntu: + +.. code-block:: bash + + $ apt-get install python-dev gcc + +On CentOS/Fedora: + +.. code-block:: bash + + $ yum install python-devel gcc redhat-rpm-config + +Linking to libxxhash.so +~~~~~~~~~~~~~~~~~~~~~~~~ + +By default python-xxhash will use bundled xxHash, +we can change this by specifying ENV var ``XXHASH_LINK_SO``: + +.. code-block:: bash + + $ XXHASH_LINK_SO=1 pip install --no-binary xxhash xxhash + +Usage +-------- + +Module version and its backend xxHash library version can be retrieved using +the module properties ``VERSION`` AND ``XXHASH_VERSION`` respectively. + +.. code-block:: python + + >>> import xxhash + >>> xxhash.VERSION + '2.0.0' + >>> xxhash.XXHASH_VERSION + '0.8.0' + +This module is hashlib-compliant, which means you can use it in the same way as ``hashlib.md5``. + + | update() -- update the current digest with an additional string + | digest() -- return the current digest value + | hexdigest() -- return the current digest as a string of hexadecimal digits + | intdigest() -- return the current digest as an integer + | copy() -- return a copy of the current xxhash object + | reset() -- reset state + +md5 digest returns bytes, but the original xxh32 and xxh64 C APIs return integers. +While this module is made hashlib-compliant, ``intdigest()`` is also provided to +get the integer digest. + +Constructors for hash algorithms provided by this module are ``xxh32()`` and ``xxh64()``. + +For example, to obtain the digest of the byte string ``b'Nobody inspects the spammish repetition'``: + +.. code-block:: python + + >>> import xxhash + >>> x = xxhash.xxh32() + >>> x.update(b'Nobody inspects') + >>> x.update(b' the spammish repetition') + >>> x.digest() + b'\xe2);/' + >>> x.digest_size + 4 + >>> x.block_size + 16 + +More condensed: + +.. code-block:: python + + >>> xxhash.xxh32(b'Nobody inspects the spammish repetition').hexdigest() + 'e2293b2f' + >>> xxhash.xxh32(b'Nobody inspects the spammish repetition').digest() == x.digest() + True + +An optional seed (default is 0) can be used to alter the result predictably: + +.. code-block:: python + + >>> import xxhash + >>> xxhash.xxh64('xxhash').hexdigest() + '32dd38952c4bc720' + >>> xxhash.xxh64('xxhash', seed=20141025).hexdigest() + 'b559b98d844e0635' + >>> x = xxhash.xxh64(seed=20141025) + >>> x.update('xxhash') + >>> x.hexdigest() + 'b559b98d844e0635' + >>> x.intdigest() + 13067679811253438005 + +Be careful that xxh32 takes an unsigned 32-bit integer as seed, while xxh64 +takes an unsigned 64-bit integer. Although unsigned integer overflow is +defined behavior, it's better not to make it happen: + +.. code-block:: python + + >>> xxhash.xxh32('I want an unsigned 32-bit seed!', seed=0).hexdigest() + 'f7a35af8' + >>> xxhash.xxh32('I want an unsigned 32-bit seed!', seed=2**32).hexdigest() + 'f7a35af8' + >>> xxhash.xxh32('I want an unsigned 32-bit seed!', seed=1).hexdigest() + 'd8d4b4ba' + >>> xxhash.xxh32('I want an unsigned 32-bit seed!', seed=2**32+1).hexdigest() + 'd8d4b4ba' + >>> + >>> xxhash.xxh64('I want an unsigned 64-bit seed!', seed=0).hexdigest() + 'd4cb0a70a2b8c7c1' + >>> xxhash.xxh64('I want an unsigned 64-bit seed!', seed=2**64).hexdigest() + 'd4cb0a70a2b8c7c1' + >>> xxhash.xxh64('I want an unsigned 64-bit seed!', seed=1).hexdigest() + 'ce5087f12470d961' + >>> xxhash.xxh64('I want an unsigned 64-bit seed!', seed=2**64+1).hexdigest() + 'ce5087f12470d961' + + +``digest()`` returns bytes of the **big-endian** representation of the integer +digest: + +.. code-block:: python + + >>> import xxhash + >>> h = xxhash.xxh64() + >>> h.digest() + b'\xefF\xdb7Q\xd8\xe9\x99' + >>> h.intdigest().to_bytes(8, 'big') + b'\xefF\xdb7Q\xd8\xe9\x99' + >>> h.hexdigest() + 'ef46db3751d8e999' + >>> format(h.intdigest(), '016x') + 'ef46db3751d8e999' + >>> h.intdigest() + 17241709254077376921 + >>> int(h.hexdigest(), 16) + 17241709254077376921 + +Besides xxh32/xxh64 mentioned above, oneshot functions are also provided, +so we can avoid allocating XXH32/64 state on heap: + + | xxh32_digest(bytes, seed=0) + | xxh32_intdigest(bytes, seed=0) + | xxh32_hexdigest(bytes, seed=0) + | xxh64_digest(bytes, seed=0) + | xxh64_intdigest(bytes, seed=0) + | xxh64_hexdigest(bytes, seed=0) + +.. code-block:: python + + >>> import xxhash + >>> xxhash.xxh64('a').digest() == xxhash.xxh64_digest('a') + True + >>> xxhash.xxh64('a').intdigest() == xxhash.xxh64_intdigest('a') + True + >>> xxhash.xxh64('a').hexdigest() == xxhash.xxh64_hexdigest('a') + True + >>> xxhash.xxh64_hexdigest('xxhash', seed=20141025) + 'b559b98d844e0635' + >>> xxhash.xxh64_intdigest('xxhash', seed=20141025) + 13067679811253438005L + >>> xxhash.xxh64_digest('xxhash', seed=20141025) + '\xb5Y\xb9\x8d\x84N\x065' + +.. code-block:: python + + In [1]: import xxhash + + In [2]: %timeit xxhash.xxh64_hexdigest('xxhash') + 268 ns ± 24.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) + + In [3]: %timeit xxhash.xxh64('xxhash').hexdigest() + 416 ns ± 17.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) + + +XXH3 hashes are available since v2.0.0 (xxHash v0.8.0), they are: + +Streaming classes: + + | xxh3_64 + | xxh3_128 + +Oneshot functions: + + | xxh3_64_digest(bytes, seed=0) + | xxh3_64_intdigest(bytes, seed=0) + | xxh3_64_hexdigest(bytes, seed=0) + | xxh3_128_digest(bytes, seed=0) + | xxh3_128_intdigest(bytes, seed=0) + | xxh3_128_hexdigest(bytes, seed=0) + +And aliases: + + | xxh128 = xxh3_128 + | xxh128_digest = xxh3_128_digest + | xxh128_intdigest = xxh3_128_intdigest + | xxh128_hexdigest = xxh3_128_hexdigest + +Caveats +------- + +SEED OVERFLOW +~~~~~~~~~~~~~~ + +xxh32 takes an unsigned 32-bit integer as seed, and xxh64 takes +an unsigned 64-bit integer as seed. Make sure that the seed is greater than +or equal to ``0``. + +ENDIANNESS +~~~~~~~~~~~ + +As of python-xxhash 0.3.0, ``digest()`` returns bytes of the +**big-endian** representation of the integer digest. It used +to be little-endian. + +DONT USE XXHASH IN HMAC +~~~~~~~~~~~~~~~~~~~~~~~ +Though you can use xxhash as an HMAC_ hash function, but it's +highly recommended not to. + +xxhash is **NOT** a cryptographic hash function, it is a +non-cryptographic hash algorithm aimed at speed and quality. +Do not put xxhash in any position where cryptographic hash +functions are required. + + +Copyright and License +--------------------- + +Copyright (c) 2014-2025 Yue Du - https://github.com/ifduyue + +Licensed under `BSD 2-Clause License `_ + +CHANGELOG +----------- + +v3.7.0 2025-04-25 +~~~~~~~~~~~~~~~~~ + +- Drop support for Python 3.7 +- Build armv7l manylinux/musllinux wheels +- Build riscv64 manylinux/musllinux wheels +- Build android and ios wheels + +v3.6.0 2025-10-02 +~~~~~~~~~~~~~~~~~ + +- Build wheels for Python 3.14 +- Python free-threading support +- Typing: Use Buffer type stubs +- Deprecate xxhash.VERSION_TUPLE, it will be removed in the next major release + +v3.5.0 2024-08-17 +~~~~~~~~~~~~~~~~~ + +- Build wheels for Python 3.13 + +v3.4.1 2023-10-05 +~~~~~~~~~~~~~~~~~ + +- Build wheels for Python 3.12 +- Remove setuptools_scm + +v3.4.0 2023-10-05 +~~~~~~~~~~~~~~~~~ + +*Yanked* due to wheels building problem. + +v3.3.0 2023-07-29 +~~~~~~~~~~~~~~~~~ + +- Upgrade xxHash to v0.8.2 +- Drop support for Python 3.6 + +v3.2.0 2022-12-28 +~~~~~~~~~~~~~~~~~ + +This is the last version to support Python 3.6 + +- Build Python 3.11 wheels. +- Remove setup.py test_suites, call unittest directly + +v3.1.0 2022-10-19 +~~~~~~~~~~~~~~~~~ + +- Type annotations. +- Enabled muslinux wheels building. + +v3.0.0 2022-02-25 +~~~~~~~~~~~~~~~~~ + +- New set `algorithms_available` lists all implemented algorithms in `xxhash` + package. +- Upgrade xxHash to v0.8.1. +- Drop support for EOL Python versions, require python >= 3.6 from now on. +- Migrate to github actions and build arm64 wheels for macOS. +- Always release GIL. + + +v2.0.2 2021-04-15 +~~~~~~~~~~~~~~~~~ + +- Fix Travis CI OSX dpl python2.7 get-pip.py error + +v2.0.1 2021-04-15 +~~~~~~~~~~~~~~~~~ + +- Only to trigger Python 3.9 wheels building. + +v2.0.0 2020-08-03 +~~~~~~~~~~~~~~~~~ + +- **Require xxHash version >= v0.8.0** +- Upgrade xxHash to v0.8.0 +- XXH3 hashes: `xxh3_64`, `xxh3_128`, and their oneshot functions + +v1.4.4 2020-06-20 +~~~~~~~~~~~~~~~~~ + +- Upgrade xxHash to v0.7.3 +- Stop using PEP393 deprecated APIs +- Use XXH(32|64)_canonicalFromHash to replace u2bytes and ull2bytes + +v1.4.3 2019-11-12 +~~~~~~~~~~~~~~~~~ + +- Upgrade xxHash to v0.7.2 +- Python 3.8 wheels + +v1.4.2 2019-10-13 +~~~~~~~~~~~~~~~~~ + +- Fixed: setup.py fails when reading README.rst and the default encoding is not UTF-8 + +v1.4.1 2019-08-27 +~~~~~~~~~~~~~~~~~ + +- Fixed: xxh3.h in missing from source tarball + +v1.4.0 2019-08-25 +~~~~~~~~~~~~~~~~~ + +- Upgrade xxHash to v0.7.1 + +v1.3.0 2018-10-21 +~~~~~~~~~~~~~~~~~ + +- Wheels are now built automatically +- Split CFFI variant into a separate package `ifduyue/python-xxhash-cffi `_ + +v1.2.0 2018-07-13 +~~~~~~~~~~~~~~~~~ + +- Add oneshot functions xxh{32,64}_{,int,hex}digest + +v1.1.0 2018-07-05 +~~~~~~~~~~~~~~~~~ + +- Allow input larger than 2GB +- Release the GIL on sufficiently large input +- Drop support for Python 3.2 + +v1.0.1 2017-03-02 +~~~~~~~~~~~~~~~~~~ + +- Free state actively, instead of delegating it to ffi.gc + +v1.0.0 2017-02-10 +~~~~~~~~~~~~~~~~~~ + +- Fixed copy() segfault +- Added CFFI variant + +v0.6.3 2017-02-10 +~~~~~~~~~~~~~~~~~~ + +- Fixed copy() segfault + +v0.6.2 2017-02-10 +~~~~~~~~~~~~~~~~~~ + +- Upgrade xxHash to v0.6.2 + +v0.6.1 2016-06-26 +~~~~~~~~~~~~~~~~~~ + +- Upgrade xxHash to v0.6.1 + +v0.5.0 2016-03-02 +~~~~~~~~~~~~~~~~~~ + +- Upgrade xxHash to v0.5.0 + +v0.4.3 2015-08-21 +~~~~~~~~~~~~~~~~~~ + +- Upgrade xxHash to r42 + +v0.4.1 2015-08-16 +~~~~~~~~~~~~~~~~~~ + +- Upgrade xxHash to r41 + +v0.4.0 2015-08-05 +~~~~~~~~~~~~~~~~~~ + +- Added method reset +- Upgrade xxHash to r40 + +v0.3.2 2015-01-27 +~~~~~~~~~~~~~~~~~~ + +- Fixed some typos in docstrings + +v0.3.1 2015-01-24 +~~~~~~~~~~~~~~~~~~ + +- Upgrade xxHash to r39 + +v0.3.0 2014-11-11 +~~~~~~~~~~~~~~~~~~ + +- Change digest() from little-endian representation to big-endian representation of the integer digest. + This change breaks compatibility (digest() results are different). + +v0.2.0 2014-10-25 +~~~~~~~~~~~~~~~~~~ + +- Make this package hashlib-compliant + +v0.1.3 2014-10-23 +~~~~~~~~~~~~~~~~~~ + +- Update xxHash to r37 + +v0.1.2 2014-10-19 +~~~~~~~~~~~~~~~~~~ + +- Improve: Check XXHnn_init() return value. +- Update xxHash to r36 + +v0.1.1 2014-08-07 +~~~~~~~~~~~~~~~~~~ + +- Improve: Can now be built with Visual C++ Compiler. + +v0.1.0 2014-08-05 +~~~~~~~~~~~~~~~~~~ + +- New: XXH32 and XXH64 type, which support partially update. +- Fix: build under Python 3.4 + +v0.0.2 2014-08-03 +~~~~~~~~~~~~~~~~~~ + +- NEW: Support Python 3 + +v0.0.1 2014-07-30 +~~~~~~~~~~~~~~~~~~ + +- NEW: xxh32 and xxh64 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash-3.7.0.dist-info/RECORD b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash-3.7.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..074c4d3a6dc5f4bd79ce144e38601ac084eeb79f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash-3.7.0.dist-info/RECORD @@ -0,0 +1,13 @@ +xxhash-3.7.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +xxhash-3.7.0.dist-info/METADATA,sha256=XAIM03AhSZ5rbtx24T8o38jVzTifLg0VKdlIgv8891g,13862 +xxhash-3.7.0.dist-info/RECORD,, +xxhash-3.7.0.dist-info/WHEEL,sha256=XHXMKJU3yoVh1ZanBXTJ5bDGb67oEYtF1S6bd8a4izI,101 +xxhash-3.7.0.dist-info/licenses/LICENSE,sha256=s8YgrcmogSzAw8f8CVZ_qamTDTVG3pVd-5VbFoz5iaw,1313 +xxhash-3.7.0.dist-info/top_level.txt,sha256=1PPSBP-gnjG59E5bigzMTzmT6BVWjHwnpzMiisPWZ5I,15 +xxhash/__init__.py,sha256=mPEdihxDMU0rjLWum3FrU9Ua2jQ-rzfewYgIg-J-Jlc,1147 +xxhash/__init__.pyi,sha256=wtUIx1kTqei5PRPbaSfCrax9v9E3GoGHa5UN5s_1Jyc,1899 +xxhash/__pycache__/__init__.cpython-311.pyc,, +xxhash/__pycache__/version.cpython-311.pyc,, +xxhash/_xxhash.cp311-win_amd64.pyd,sha256=gUQdH8bHqoW8bAlKnJZ920FHh9_LJkoisK9nJh_iwQQ,59904 +xxhash/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +xxhash/version.py,sha256=nbNI0VY7fa_Mq7ODnnBYqkOdobEPw7k_jf3c6zgDVvI,101 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash-3.7.0.dist-info/WHEEL b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash-3.7.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..75a83ab128f69c4cd27d9a5be479a52a2597d3d1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash-3.7.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.1) +Root-Is-Purelib: false +Tag: cp311-cp311-win_amd64 + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash-3.7.0.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash-3.7.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0103aae504db7ed40539656bf0997f32d698e335 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash-3.7.0.dist-info/licenses/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2014-2024, Yue Du +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. + +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/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash-3.7.0.dist-info/top_level.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash-3.7.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..46a6ce2f1ac8b49207db6601355076641e92f163 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash-3.7.0.dist-info/top_level.txt @@ -0,0 +1,2 @@ +_xxhash +xxhash diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..043c486ddf9d2770d7fbee4bff1c26985ac6cd7e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash/__init__.py @@ -0,0 +1,63 @@ +from ._xxhash import ( + xxh32, + xxh32_digest, + xxh32_intdigest, + xxh32_hexdigest, + xxh64, + xxh64_digest, + xxh64_intdigest, + xxh64_hexdigest, + xxh3_64, + xxh3_64_digest, + xxh3_64_intdigest, + xxh3_64_hexdigest, + xxh3_128, + xxh3_128_digest, + xxh3_128_intdigest, + xxh3_128_hexdigest, + XXHASH_VERSION, +) + +from .version import VERSION, VERSION_TUPLE + + +xxh128 = xxh3_128 +xxh128_hexdigest = xxh3_128_hexdigest +xxh128_intdigest = xxh3_128_intdigest +xxh128_digest = xxh3_128_digest + +algorithms_available = set([ + "xxh32", + "xxh64", + "xxh3_64", + "xxh128", + "xxh3_128", +]) + + +__all__ = [ + "xxh32", + "xxh32_digest", + "xxh32_intdigest", + "xxh32_hexdigest", + "xxh64", + "xxh64_digest", + "xxh64_intdigest", + "xxh64_hexdigest", + "xxh3_64", + "xxh3_64_digest", + "xxh3_64_intdigest", + "xxh3_64_hexdigest", + "xxh3_128", + "xxh3_128_digest", + "xxh3_128_intdigest", + "xxh3_128_hexdigest", + "xxh128", + "xxh128_digest", + "xxh128_intdigest", + "xxh128_hexdigest", + "VERSION", + "VERSION_TUPLE", + "XXHASH_VERSION", + "algorithms_available", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash/__init__.pyi b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a566d0852090bb3a737513e5a46422d04e24c556 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash/__init__.pyi @@ -0,0 +1,65 @@ +import array +from typing import Union +from typing_extensions import final, Buffer + +# __buffer__ protocol makes this redundant on python 3.12+ +Buffer.register(array.ArrayType) +_InputType = Union[str, Buffer] + +VERSION: str +XXHASH_VERSION: str +#: Deprecated, will be removed in the next major release +VERSION_TUPLE: tuple[int, ...] + +algorithms_available: set[str] + +class _Hasher: + def __init__(self, input: _InputType = ..., seed: int = ...) -> None: ... + def update(self, input: _InputType) -> None: ... + def digest(self) -> bytes: ... + def hexdigest(self) -> str: ... + def intdigest(self) -> int: ... + def copy(self) -> _Hasher: ... + def reset(self) -> None: ... + @property + def digestsize(self) -> int: ... + @property + def digest_size(self) -> int: ... + @property + def block_size(self) -> int: ... + @property + def name(self) -> str: ... + @property + def seed(self) -> int: ... + +@final +class xxh32(_Hasher): ... + +@final +class xxh3_64(_Hasher): ... + +@final +class xxh3_128(_Hasher): ... + +xxh64 = xxh3_64 +xxh128 = xxh3_128 + +def xxh32_digest(args: _InputType, seed: int = ...) -> bytes: ... +def xxh32_hexdigest(args: _InputType, seed: int = ...) -> str: ... +def xxh32_intdigest(args: _InputType, seed: int = ...) -> int: ... + +def xxh3_64_digest(args: _InputType, seed: int = ...) -> bytes: ... +def xxh3_64_hexdigest(args: _InputType, seed: int = ...) -> str: ... +def xxh3_64_intdigest(args: _InputType, seed: int = ...) -> int: ... + +def xxh3_128_digest(args: _InputType, seed: int = ...) -> bytes: ... +def xxh3_128_hexdigest(args: _InputType, seed: int = ...) -> str: ... +def xxh3_128_intdigest(args: _InputType, seed: int = ...) -> int: ... + +xxh64_digest = xxh3_64_digest +xxh64_hexdigest = xxh3_64_hexdigest +xxh64_intdigest = xxh3_64_intdigest + +xxh128_digest = xxh3_128_digest +xxh128_hexdigest = xxh3_128_hexdigest +xxh128_intdigest = xxh3_128_intdigest diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b7df6d8e8c0b07c01b30de21b13b366f631746e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash/__pycache__/version.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash/__pycache__/version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00db64bdef3ad11d59a8b0b3900d056957c87670 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash/__pycache__/version.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash/_xxhash.cp311-win_amd64.pyd b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash/_xxhash.cp311-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..f6ba18862e2f037f951493a455bd2ef18dba87fd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash/_xxhash.cp311-win_amd64.pyd differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash/py.typed b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash/version.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash/version.py new file mode 100644 index 0000000000000000000000000000000000000000..90366c1dd2c96f103d73be9f730a64af5924799d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/xxhash/version.py @@ -0,0 +1,3 @@ +VERSION = "3.7.0" +#: Deprecated, will be removed in the next major release +VERSION_TUPLE = (3, 7, 0) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d58f0891737def7f38e5d86dde2dbf9be0c13dce --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__init__.py @@ -0,0 +1,390 @@ + +from .error import * + +from .tokens import * +from .events import * +from .nodes import * + +from .loader import * +from .dumper import * + +__version__ = '6.0.3' +try: + from .cyaml import * + __with_libyaml__ = True +except ImportError: + __with_libyaml__ = False + +import io + +#------------------------------------------------------------------------------ +# XXX "Warnings control" is now deprecated. Leaving in the API function to not +# break code that uses it. +#------------------------------------------------------------------------------ +def warnings(settings=None): + if settings is None: + return {} + +#------------------------------------------------------------------------------ +def scan(stream, Loader=Loader): + """ + Scan a YAML stream and produce scanning tokens. + """ + loader = Loader(stream) + try: + while loader.check_token(): + yield loader.get_token() + finally: + loader.dispose() + +def parse(stream, Loader=Loader): + """ + Parse a YAML stream and produce parsing events. + """ + loader = Loader(stream) + try: + while loader.check_event(): + yield loader.get_event() + finally: + loader.dispose() + +def compose(stream, Loader=Loader): + """ + Parse the first YAML document in a stream + and produce the corresponding representation tree. + """ + loader = Loader(stream) + try: + return loader.get_single_node() + finally: + loader.dispose() + +def compose_all(stream, Loader=Loader): + """ + Parse all YAML documents in a stream + and produce corresponding representation trees. + """ + loader = Loader(stream) + try: + while loader.check_node(): + yield loader.get_node() + finally: + loader.dispose() + +def load(stream, Loader): + """ + Parse the first YAML document in a stream + and produce the corresponding Python object. + """ + loader = Loader(stream) + try: + return loader.get_single_data() + finally: + loader.dispose() + +def load_all(stream, Loader): + """ + Parse all YAML documents in a stream + and produce corresponding Python objects. + """ + loader = Loader(stream) + try: + while loader.check_data(): + yield loader.get_data() + finally: + loader.dispose() + +def full_load(stream): + """ + Parse the first YAML document in a stream + and produce the corresponding Python object. + + Resolve all tags except those known to be + unsafe on untrusted input. + """ + return load(stream, FullLoader) + +def full_load_all(stream): + """ + Parse all YAML documents in a stream + and produce corresponding Python objects. + + Resolve all tags except those known to be + unsafe on untrusted input. + """ + return load_all(stream, FullLoader) + +def safe_load(stream): + """ + Parse the first YAML document in a stream + and produce the corresponding Python object. + + Resolve only basic YAML tags. This is known + to be safe for untrusted input. + """ + return load(stream, SafeLoader) + +def safe_load_all(stream): + """ + Parse all YAML documents in a stream + and produce corresponding Python objects. + + Resolve only basic YAML tags. This is known + to be safe for untrusted input. + """ + return load_all(stream, SafeLoader) + +def unsafe_load(stream): + """ + Parse the first YAML document in a stream + and produce the corresponding Python object. + + Resolve all tags, even those known to be + unsafe on untrusted input. + """ + return load(stream, UnsafeLoader) + +def unsafe_load_all(stream): + """ + Parse all YAML documents in a stream + and produce corresponding Python objects. + + Resolve all tags, even those known to be + unsafe on untrusted input. + """ + return load_all(stream, UnsafeLoader) + +def emit(events, stream=None, Dumper=Dumper, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None): + """ + Emit YAML parsing events into a stream. + If stream is None, return the produced string instead. + """ + getvalue = None + if stream is None: + stream = io.StringIO() + getvalue = stream.getvalue + dumper = Dumper(stream, canonical=canonical, indent=indent, width=width, + allow_unicode=allow_unicode, line_break=line_break) + try: + for event in events: + dumper.emit(event) + finally: + dumper.dispose() + if getvalue: + return getvalue() + +def serialize_all(nodes, stream=None, Dumper=Dumper, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None, + encoding=None, explicit_start=None, explicit_end=None, + version=None, tags=None): + """ + Serialize a sequence of representation trees into a YAML stream. + If stream is None, return the produced string instead. + """ + getvalue = None + if stream is None: + if encoding is None: + stream = io.StringIO() + else: + stream = io.BytesIO() + getvalue = stream.getvalue + dumper = Dumper(stream, canonical=canonical, indent=indent, width=width, + allow_unicode=allow_unicode, line_break=line_break, + encoding=encoding, version=version, tags=tags, + explicit_start=explicit_start, explicit_end=explicit_end) + try: + dumper.open() + for node in nodes: + dumper.serialize(node) + dumper.close() + finally: + dumper.dispose() + if getvalue: + return getvalue() + +def serialize(node, stream=None, Dumper=Dumper, **kwds): + """ + Serialize a representation tree into a YAML stream. + If stream is None, return the produced string instead. + """ + return serialize_all([node], stream, Dumper=Dumper, **kwds) + +def dump_all(documents, stream=None, Dumper=Dumper, + default_style=None, default_flow_style=False, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None, + encoding=None, explicit_start=None, explicit_end=None, + version=None, tags=None, sort_keys=True): + """ + Serialize a sequence of Python objects into a YAML stream. + If stream is None, return the produced string instead. + """ + getvalue = None + if stream is None: + if encoding is None: + stream = io.StringIO() + else: + stream = io.BytesIO() + getvalue = stream.getvalue + dumper = Dumper(stream, default_style=default_style, + default_flow_style=default_flow_style, + canonical=canonical, indent=indent, width=width, + allow_unicode=allow_unicode, line_break=line_break, + encoding=encoding, version=version, tags=tags, + explicit_start=explicit_start, explicit_end=explicit_end, sort_keys=sort_keys) + try: + dumper.open() + for data in documents: + dumper.represent(data) + dumper.close() + finally: + dumper.dispose() + if getvalue: + return getvalue() + +def dump(data, stream=None, Dumper=Dumper, **kwds): + """ + Serialize a Python object into a YAML stream. + If stream is None, return the produced string instead. + """ + return dump_all([data], stream, Dumper=Dumper, **kwds) + +def safe_dump_all(documents, stream=None, **kwds): + """ + Serialize a sequence of Python objects into a YAML stream. + Produce only basic YAML tags. + If stream is None, return the produced string instead. + """ + return dump_all(documents, stream, Dumper=SafeDumper, **kwds) + +def safe_dump(data, stream=None, **kwds): + """ + Serialize a Python object into a YAML stream. + Produce only basic YAML tags. + If stream is None, return the produced string instead. + """ + return dump_all([data], stream, Dumper=SafeDumper, **kwds) + +def add_implicit_resolver(tag, regexp, first=None, + Loader=None, Dumper=Dumper): + """ + Add an implicit scalar detector. + If an implicit scalar value matches the given regexp, + the corresponding tag is assigned to the scalar. + first is a sequence of possible initial characters or None. + """ + if Loader is None: + loader.Loader.add_implicit_resolver(tag, regexp, first) + loader.FullLoader.add_implicit_resolver(tag, regexp, first) + loader.UnsafeLoader.add_implicit_resolver(tag, regexp, first) + else: + Loader.add_implicit_resolver(tag, regexp, first) + Dumper.add_implicit_resolver(tag, regexp, first) + +def add_path_resolver(tag, path, kind=None, Loader=None, Dumper=Dumper): + """ + Add a path based resolver for the given tag. + A path is a list of keys that forms a path + to a node in the representation tree. + Keys can be string values, integers, or None. + """ + if Loader is None: + loader.Loader.add_path_resolver(tag, path, kind) + loader.FullLoader.add_path_resolver(tag, path, kind) + loader.UnsafeLoader.add_path_resolver(tag, path, kind) + else: + Loader.add_path_resolver(tag, path, kind) + Dumper.add_path_resolver(tag, path, kind) + +def add_constructor(tag, constructor, Loader=None): + """ + Add a constructor for the given tag. + Constructor is a function that accepts a Loader instance + and a node object and produces the corresponding Python object. + """ + if Loader is None: + loader.Loader.add_constructor(tag, constructor) + loader.FullLoader.add_constructor(tag, constructor) + loader.UnsafeLoader.add_constructor(tag, constructor) + else: + Loader.add_constructor(tag, constructor) + +def add_multi_constructor(tag_prefix, multi_constructor, Loader=None): + """ + Add a multi-constructor for the given tag prefix. + Multi-constructor is called for a node if its tag starts with tag_prefix. + Multi-constructor accepts a Loader instance, a tag suffix, + and a node object and produces the corresponding Python object. + """ + if Loader is None: + loader.Loader.add_multi_constructor(tag_prefix, multi_constructor) + loader.FullLoader.add_multi_constructor(tag_prefix, multi_constructor) + loader.UnsafeLoader.add_multi_constructor(tag_prefix, multi_constructor) + else: + Loader.add_multi_constructor(tag_prefix, multi_constructor) + +def add_representer(data_type, representer, Dumper=Dumper): + """ + Add a representer for the given type. + Representer is a function accepting a Dumper instance + and an instance of the given data type + and producing the corresponding representation node. + """ + Dumper.add_representer(data_type, representer) + +def add_multi_representer(data_type, multi_representer, Dumper=Dumper): + """ + Add a representer for the given type. + Multi-representer is a function accepting a Dumper instance + and an instance of the given data type or subtype + and producing the corresponding representation node. + """ + Dumper.add_multi_representer(data_type, multi_representer) + +class YAMLObjectMetaclass(type): + """ + The metaclass for YAMLObject. + """ + def __init__(cls, name, bases, kwds): + super(YAMLObjectMetaclass, cls).__init__(name, bases, kwds) + if 'yaml_tag' in kwds and kwds['yaml_tag'] is not None: + if isinstance(cls.yaml_loader, list): + for loader in cls.yaml_loader: + loader.add_constructor(cls.yaml_tag, cls.from_yaml) + else: + cls.yaml_loader.add_constructor(cls.yaml_tag, cls.from_yaml) + + cls.yaml_dumper.add_representer(cls, cls.to_yaml) + +class YAMLObject(metaclass=YAMLObjectMetaclass): + """ + An object that can dump itself to a YAML stream + and load itself from a YAML stream. + """ + + __slots__ = () # no direct instantiation, so allow immutable subclasses + + yaml_loader = [Loader, FullLoader, UnsafeLoader] + yaml_dumper = Dumper + + yaml_tag = None + yaml_flow_style = None + + @classmethod + def from_yaml(cls, loader, node): + """ + Convert a representation node to a Python object. + """ + return loader.construct_yaml_object(node, cls) + + @classmethod + def to_yaml(cls, dumper, data): + """ + Convert a Python object to a representation node. + """ + return dumper.represent_yaml_object(cls.yaml_tag, data, cls, + flow_style=cls.yaml_flow_style) + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..132e63d0d60160ef85b03354922c723701db47c6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/composer.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/composer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fad603734bdc5c9ac8a7437f8fe44b22ac875d23 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/composer.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/constructor.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/constructor.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8af0cf4a21e98b5a80b7437f9d389804ce1ba97f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/constructor.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/cyaml.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/cyaml.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19e7d1a74cc40b94f04b4f26b86d1e4f28a92a94 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/cyaml.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/dumper.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/dumper.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a34b591d9e44e22cf6c06f9bb7e472198bacaed1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/dumper.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/emitter.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/emitter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eafef99a507c37f3cc1d16c88717951a846b1f12 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/emitter.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/error.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/error.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..950ba43231b809a1fc3e5880c3939c84b583e40b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/error.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/events.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/events.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..466732ed4550e84704e267c3abc35786f61a8985 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/events.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/loader.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/loader.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95c0a6d0116a6d224de08e01d7ed08b6778ff041 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/loader.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/nodes.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/nodes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f437eb4c7f474ea8c32a67c92ba68c99a806329 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/nodes.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/parser.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/parser.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a4f8521b0116c6c673942656049cf963cb22f51 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/parser.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/reader.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/reader.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a85d5a623ecc2a8a8836d2d491a05184efbc5997 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/reader.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/representer.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/representer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc75adaf35378a2d998858faefb280be175428bb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/representer.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/resolver.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/resolver.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f0351529afcce955d0d2a80cb3ae737ee7b5e61 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/resolver.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/scanner.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/scanner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9972f96092aed0cf5c53271be51629df40a819f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/scanner.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/serializer.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/serializer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f6fa9c87d64579b52e70a5983cb5985168bc61e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/serializer.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/tokens.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/tokens.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1bcdde7e768ced5d64d4b33f92ed8d894d2c6f1c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/__pycache__/tokens.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/composer.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/composer.py new file mode 100644 index 0000000000000000000000000000000000000000..6d15cb40e3b4198819c91c6f8d8b32807fcf53b2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/composer.py @@ -0,0 +1,139 @@ + +__all__ = ['Composer', 'ComposerError'] + +from .error import MarkedYAMLError +from .events import * +from .nodes import * + +class ComposerError(MarkedYAMLError): + pass + +class Composer: + + def __init__(self): + self.anchors = {} + + def check_node(self): + # Drop the STREAM-START event. + if self.check_event(StreamStartEvent): + self.get_event() + + # If there are more documents available? + return not self.check_event(StreamEndEvent) + + def get_node(self): + # Get the root node of the next document. + if not self.check_event(StreamEndEvent): + return self.compose_document() + + def get_single_node(self): + # Drop the STREAM-START event. + self.get_event() + + # Compose a document if the stream is not empty. + document = None + if not self.check_event(StreamEndEvent): + document = self.compose_document() + + # Ensure that the stream contains no more documents. + if not self.check_event(StreamEndEvent): + event = self.get_event() + raise ComposerError("expected a single document in the stream", + document.start_mark, "but found another document", + event.start_mark) + + # Drop the STREAM-END event. + self.get_event() + + return document + + def compose_document(self): + # Drop the DOCUMENT-START event. + self.get_event() + + # Compose the root node. + node = self.compose_node(None, None) + + # Drop the DOCUMENT-END event. + self.get_event() + + self.anchors = {} + return node + + def compose_node(self, parent, index): + if self.check_event(AliasEvent): + event = self.get_event() + anchor = event.anchor + if anchor not in self.anchors: + raise ComposerError(None, None, "found undefined alias %r" + % anchor, event.start_mark) + return self.anchors[anchor] + event = self.peek_event() + anchor = event.anchor + if anchor is not None: + if anchor in self.anchors: + raise ComposerError("found duplicate anchor %r; first occurrence" + % anchor, self.anchors[anchor].start_mark, + "second occurrence", event.start_mark) + self.descend_resolver(parent, index) + if self.check_event(ScalarEvent): + node = self.compose_scalar_node(anchor) + elif self.check_event(SequenceStartEvent): + node = self.compose_sequence_node(anchor) + elif self.check_event(MappingStartEvent): + node = self.compose_mapping_node(anchor) + self.ascend_resolver() + return node + + def compose_scalar_node(self, anchor): + event = self.get_event() + tag = event.tag + if tag is None or tag == '!': + tag = self.resolve(ScalarNode, event.value, event.implicit) + node = ScalarNode(tag, event.value, + event.start_mark, event.end_mark, style=event.style) + if anchor is not None: + self.anchors[anchor] = node + return node + + def compose_sequence_node(self, anchor): + start_event = self.get_event() + tag = start_event.tag + if tag is None or tag == '!': + tag = self.resolve(SequenceNode, None, start_event.implicit) + node = SequenceNode(tag, [], + start_event.start_mark, None, + flow_style=start_event.flow_style) + if anchor is not None: + self.anchors[anchor] = node + index = 0 + while not self.check_event(SequenceEndEvent): + node.value.append(self.compose_node(node, index)) + index += 1 + end_event = self.get_event() + node.end_mark = end_event.end_mark + return node + + def compose_mapping_node(self, anchor): + start_event = self.get_event() + tag = start_event.tag + if tag is None or tag == '!': + tag = self.resolve(MappingNode, None, start_event.implicit) + node = MappingNode(tag, [], + start_event.start_mark, None, + flow_style=start_event.flow_style) + if anchor is not None: + self.anchors[anchor] = node + while not self.check_event(MappingEndEvent): + #key_event = self.peek_event() + item_key = self.compose_node(node, None) + #if item_key in node.value: + # raise ComposerError("while composing a mapping", start_event.start_mark, + # "found duplicate key", key_event.start_mark) + item_value = self.compose_node(node, item_key) + #node.value[item_key] = item_value + node.value.append((item_key, item_value)) + end_event = self.get_event() + node.end_mark = end_event.end_mark + return node + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/constructor.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/constructor.py new file mode 100644 index 0000000000000000000000000000000000000000..619acd3070a4845c653fcf22a626e05158035bc2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/constructor.py @@ -0,0 +1,748 @@ + +__all__ = [ + 'BaseConstructor', + 'SafeConstructor', + 'FullConstructor', + 'UnsafeConstructor', + 'Constructor', + 'ConstructorError' +] + +from .error import * +from .nodes import * + +import collections.abc, datetime, base64, binascii, re, sys, types + +class ConstructorError(MarkedYAMLError): + pass + +class BaseConstructor: + + yaml_constructors = {} + yaml_multi_constructors = {} + + def __init__(self): + self.constructed_objects = {} + self.recursive_objects = {} + self.state_generators = [] + self.deep_construct = False + + def check_data(self): + # If there are more documents available? + return self.check_node() + + def check_state_key(self, key): + """Block special attributes/methods from being set in a newly created + object, to prevent user-controlled methods from being called during + deserialization""" + if self.get_state_keys_blacklist_regexp().match(key): + raise ConstructorError(None, None, + "blacklisted key '%s' in instance state found" % (key,), None) + + def get_data(self): + # Construct and return the next document. + if self.check_node(): + return self.construct_document(self.get_node()) + + def get_single_data(self): + # Ensure that the stream contains a single document and construct it. + node = self.get_single_node() + if node is not None: + return self.construct_document(node) + return None + + def construct_document(self, node): + data = self.construct_object(node) + while self.state_generators: + state_generators = self.state_generators + self.state_generators = [] + for generator in state_generators: + for dummy in generator: + pass + self.constructed_objects = {} + self.recursive_objects = {} + self.deep_construct = False + return data + + def construct_object(self, node, deep=False): + if node in self.constructed_objects: + return self.constructed_objects[node] + if deep: + old_deep = self.deep_construct + self.deep_construct = True + if node in self.recursive_objects: + raise ConstructorError(None, None, + "found unconstructable recursive node", node.start_mark) + self.recursive_objects[node] = None + constructor = None + tag_suffix = None + if node.tag in self.yaml_constructors: + constructor = self.yaml_constructors[node.tag] + else: + for tag_prefix in self.yaml_multi_constructors: + if tag_prefix is not None and node.tag.startswith(tag_prefix): + tag_suffix = node.tag[len(tag_prefix):] + constructor = self.yaml_multi_constructors[tag_prefix] + break + else: + if None in self.yaml_multi_constructors: + tag_suffix = node.tag + constructor = self.yaml_multi_constructors[None] + elif None in self.yaml_constructors: + constructor = self.yaml_constructors[None] + elif isinstance(node, ScalarNode): + constructor = self.__class__.construct_scalar + elif isinstance(node, SequenceNode): + constructor = self.__class__.construct_sequence + elif isinstance(node, MappingNode): + constructor = self.__class__.construct_mapping + if tag_suffix is None: + data = constructor(self, node) + else: + data = constructor(self, tag_suffix, node) + if isinstance(data, types.GeneratorType): + generator = data + data = next(generator) + if self.deep_construct: + for dummy in generator: + pass + else: + self.state_generators.append(generator) + self.constructed_objects[node] = data + del self.recursive_objects[node] + if deep: + self.deep_construct = old_deep + return data + + def construct_scalar(self, node): + if not isinstance(node, ScalarNode): + raise ConstructorError(None, None, + "expected a scalar node, but found %s" % node.id, + node.start_mark) + return node.value + + def construct_sequence(self, node, deep=False): + if not isinstance(node, SequenceNode): + raise ConstructorError(None, None, + "expected a sequence node, but found %s" % node.id, + node.start_mark) + return [self.construct_object(child, deep=deep) + for child in node.value] + + def construct_mapping(self, node, deep=False): + if not isinstance(node, MappingNode): + raise ConstructorError(None, None, + "expected a mapping node, but found %s" % node.id, + node.start_mark) + mapping = {} + for key_node, value_node in node.value: + key = self.construct_object(key_node, deep=deep) + if not isinstance(key, collections.abc.Hashable): + raise ConstructorError("while constructing a mapping", node.start_mark, + "found unhashable key", key_node.start_mark) + value = self.construct_object(value_node, deep=deep) + mapping[key] = value + return mapping + + def construct_pairs(self, node, deep=False): + if not isinstance(node, MappingNode): + raise ConstructorError(None, None, + "expected a mapping node, but found %s" % node.id, + node.start_mark) + pairs = [] + for key_node, value_node in node.value: + key = self.construct_object(key_node, deep=deep) + value = self.construct_object(value_node, deep=deep) + pairs.append((key, value)) + return pairs + + @classmethod + def add_constructor(cls, tag, constructor): + if not 'yaml_constructors' in cls.__dict__: + cls.yaml_constructors = cls.yaml_constructors.copy() + cls.yaml_constructors[tag] = constructor + + @classmethod + def add_multi_constructor(cls, tag_prefix, multi_constructor): + if not 'yaml_multi_constructors' in cls.__dict__: + cls.yaml_multi_constructors = cls.yaml_multi_constructors.copy() + cls.yaml_multi_constructors[tag_prefix] = multi_constructor + +class SafeConstructor(BaseConstructor): + + def construct_scalar(self, node): + if isinstance(node, MappingNode): + for key_node, value_node in node.value: + if key_node.tag == 'tag:yaml.org,2002:value': + return self.construct_scalar(value_node) + return super().construct_scalar(node) + + def flatten_mapping(self, node): + merge = [] + index = 0 + while index < len(node.value): + key_node, value_node = node.value[index] + if key_node.tag == 'tag:yaml.org,2002:merge': + del node.value[index] + if isinstance(value_node, MappingNode): + self.flatten_mapping(value_node) + merge.extend(value_node.value) + elif isinstance(value_node, SequenceNode): + submerge = [] + for subnode in value_node.value: + if not isinstance(subnode, MappingNode): + raise ConstructorError("while constructing a mapping", + node.start_mark, + "expected a mapping for merging, but found %s" + % subnode.id, subnode.start_mark) + self.flatten_mapping(subnode) + submerge.append(subnode.value) + submerge.reverse() + for value in submerge: + merge.extend(value) + else: + raise ConstructorError("while constructing a mapping", node.start_mark, + "expected a mapping or list of mappings for merging, but found %s" + % value_node.id, value_node.start_mark) + elif key_node.tag == 'tag:yaml.org,2002:value': + key_node.tag = 'tag:yaml.org,2002:str' + index += 1 + else: + index += 1 + if merge: + node.value = merge + node.value + + def construct_mapping(self, node, deep=False): + if isinstance(node, MappingNode): + self.flatten_mapping(node) + return super().construct_mapping(node, deep=deep) + + def construct_yaml_null(self, node): + self.construct_scalar(node) + return None + + bool_values = { + 'yes': True, + 'no': False, + 'true': True, + 'false': False, + 'on': True, + 'off': False, + } + + def construct_yaml_bool(self, node): + value = self.construct_scalar(node) + return self.bool_values[value.lower()] + + def construct_yaml_int(self, node): + value = self.construct_scalar(node) + value = value.replace('_', '') + sign = +1 + if value[0] == '-': + sign = -1 + if value[0] in '+-': + value = value[1:] + if value == '0': + return 0 + elif value.startswith('0b'): + return sign*int(value[2:], 2) + elif value.startswith('0x'): + return sign*int(value[2:], 16) + elif value[0] == '0': + return sign*int(value, 8) + elif ':' in value: + digits = [int(part) for part in value.split(':')] + digits.reverse() + base = 1 + value = 0 + for digit in digits: + value += digit*base + base *= 60 + return sign*value + else: + return sign*int(value) + + inf_value = 1e300 + while inf_value != inf_value*inf_value: + inf_value *= inf_value + nan_value = -inf_value/inf_value # Trying to make a quiet NaN (like C99). + + def construct_yaml_float(self, node): + value = self.construct_scalar(node) + value = value.replace('_', '').lower() + sign = +1 + if value[0] == '-': + sign = -1 + if value[0] in '+-': + value = value[1:] + if value == '.inf': + return sign*self.inf_value + elif value == '.nan': + return self.nan_value + elif ':' in value: + digits = [float(part) for part in value.split(':')] + digits.reverse() + base = 1 + value = 0.0 + for digit in digits: + value += digit*base + base *= 60 + return sign*value + else: + return sign*float(value) + + def construct_yaml_binary(self, node): + try: + value = self.construct_scalar(node).encode('ascii') + except UnicodeEncodeError as exc: + raise ConstructorError(None, None, + "failed to convert base64 data into ascii: %s" % exc, + node.start_mark) + try: + if hasattr(base64, 'decodebytes'): + return base64.decodebytes(value) + else: + return base64.decodestring(value) + except binascii.Error as exc: + raise ConstructorError(None, None, + "failed to decode base64 data: %s" % exc, node.start_mark) + + timestamp_regexp = re.compile( + r'''^(?P[0-9][0-9][0-9][0-9]) + -(?P[0-9][0-9]?) + -(?P[0-9][0-9]?) + (?:(?:[Tt]|[ \t]+) + (?P[0-9][0-9]?) + :(?P[0-9][0-9]) + :(?P[0-9][0-9]) + (?:\.(?P[0-9]*))? + (?:[ \t]*(?PZ|(?P[-+])(?P[0-9][0-9]?) + (?::(?P[0-9][0-9]))?))?)?$''', re.X) + + def construct_yaml_timestamp(self, node): + value = self.construct_scalar(node) + match = self.timestamp_regexp.match(node.value) + values = match.groupdict() + year = int(values['year']) + month = int(values['month']) + day = int(values['day']) + if not values['hour']: + return datetime.date(year, month, day) + hour = int(values['hour']) + minute = int(values['minute']) + second = int(values['second']) + fraction = 0 + tzinfo = None + if values['fraction']: + fraction = values['fraction'][:6] + while len(fraction) < 6: + fraction += '0' + fraction = int(fraction) + if values['tz_sign']: + tz_hour = int(values['tz_hour']) + tz_minute = int(values['tz_minute'] or 0) + delta = datetime.timedelta(hours=tz_hour, minutes=tz_minute) + if values['tz_sign'] == '-': + delta = -delta + tzinfo = datetime.timezone(delta) + elif values['tz']: + tzinfo = datetime.timezone.utc + return datetime.datetime(year, month, day, hour, minute, second, fraction, + tzinfo=tzinfo) + + def construct_yaml_omap(self, node): + # Note: we do not check for duplicate keys, because it's too + # CPU-expensive. + omap = [] + yield omap + if not isinstance(node, SequenceNode): + raise ConstructorError("while constructing an ordered map", node.start_mark, + "expected a sequence, but found %s" % node.id, node.start_mark) + for subnode in node.value: + if not isinstance(subnode, MappingNode): + raise ConstructorError("while constructing an ordered map", node.start_mark, + "expected a mapping of length 1, but found %s" % subnode.id, + subnode.start_mark) + if len(subnode.value) != 1: + raise ConstructorError("while constructing an ordered map", node.start_mark, + "expected a single mapping item, but found %d items" % len(subnode.value), + subnode.start_mark) + key_node, value_node = subnode.value[0] + key = self.construct_object(key_node) + value = self.construct_object(value_node) + omap.append((key, value)) + + def construct_yaml_pairs(self, node): + # Note: the same code as `construct_yaml_omap`. + pairs = [] + yield pairs + if not isinstance(node, SequenceNode): + raise ConstructorError("while constructing pairs", node.start_mark, + "expected a sequence, but found %s" % node.id, node.start_mark) + for subnode in node.value: + if not isinstance(subnode, MappingNode): + raise ConstructorError("while constructing pairs", node.start_mark, + "expected a mapping of length 1, but found %s" % subnode.id, + subnode.start_mark) + if len(subnode.value) != 1: + raise ConstructorError("while constructing pairs", node.start_mark, + "expected a single mapping item, but found %d items" % len(subnode.value), + subnode.start_mark) + key_node, value_node = subnode.value[0] + key = self.construct_object(key_node) + value = self.construct_object(value_node) + pairs.append((key, value)) + + def construct_yaml_set(self, node): + data = set() + yield data + value = self.construct_mapping(node) + data.update(value) + + def construct_yaml_str(self, node): + return self.construct_scalar(node) + + def construct_yaml_seq(self, node): + data = [] + yield data + data.extend(self.construct_sequence(node)) + + def construct_yaml_map(self, node): + data = {} + yield data + value = self.construct_mapping(node) + data.update(value) + + def construct_yaml_object(self, node, cls): + data = cls.__new__(cls) + yield data + if hasattr(data, '__setstate__'): + state = self.construct_mapping(node, deep=True) + data.__setstate__(state) + else: + state = self.construct_mapping(node) + data.__dict__.update(state) + + def construct_undefined(self, node): + raise ConstructorError(None, None, + "could not determine a constructor for the tag %r" % node.tag, + node.start_mark) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:null', + SafeConstructor.construct_yaml_null) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:bool', + SafeConstructor.construct_yaml_bool) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:int', + SafeConstructor.construct_yaml_int) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:float', + SafeConstructor.construct_yaml_float) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:binary', + SafeConstructor.construct_yaml_binary) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:timestamp', + SafeConstructor.construct_yaml_timestamp) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:omap', + SafeConstructor.construct_yaml_omap) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:pairs', + SafeConstructor.construct_yaml_pairs) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:set', + SafeConstructor.construct_yaml_set) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:str', + SafeConstructor.construct_yaml_str) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:seq', + SafeConstructor.construct_yaml_seq) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:map', + SafeConstructor.construct_yaml_map) + +SafeConstructor.add_constructor(None, + SafeConstructor.construct_undefined) + +class FullConstructor(SafeConstructor): + # 'extend' is blacklisted because it is used by + # construct_python_object_apply to add `listitems` to a newly generate + # python instance + def get_state_keys_blacklist(self): + return ['^extend$', '^__.*__$'] + + def get_state_keys_blacklist_regexp(self): + if not hasattr(self, 'state_keys_blacklist_regexp'): + self.state_keys_blacklist_regexp = re.compile('(' + '|'.join(self.get_state_keys_blacklist()) + ')') + return self.state_keys_blacklist_regexp + + def construct_python_str(self, node): + return self.construct_scalar(node) + + def construct_python_unicode(self, node): + return self.construct_scalar(node) + + def construct_python_bytes(self, node): + try: + value = self.construct_scalar(node).encode('ascii') + except UnicodeEncodeError as exc: + raise ConstructorError(None, None, + "failed to convert base64 data into ascii: %s" % exc, + node.start_mark) + try: + if hasattr(base64, 'decodebytes'): + return base64.decodebytes(value) + else: + return base64.decodestring(value) + except binascii.Error as exc: + raise ConstructorError(None, None, + "failed to decode base64 data: %s" % exc, node.start_mark) + + def construct_python_long(self, node): + return self.construct_yaml_int(node) + + def construct_python_complex(self, node): + return complex(self.construct_scalar(node)) + + def construct_python_tuple(self, node): + return tuple(self.construct_sequence(node)) + + def find_python_module(self, name, mark, unsafe=False): + if not name: + raise ConstructorError("while constructing a Python module", mark, + "expected non-empty name appended to the tag", mark) + if unsafe: + try: + __import__(name) + except ImportError as exc: + raise ConstructorError("while constructing a Python module", mark, + "cannot find module %r (%s)" % (name, exc), mark) + if name not in sys.modules: + raise ConstructorError("while constructing a Python module", mark, + "module %r is not imported" % name, mark) + return sys.modules[name] + + def find_python_name(self, name, mark, unsafe=False): + if not name: + raise ConstructorError("while constructing a Python object", mark, + "expected non-empty name appended to the tag", mark) + if '.' in name: + module_name, object_name = name.rsplit('.', 1) + else: + module_name = 'builtins' + object_name = name + if unsafe: + try: + __import__(module_name) + except ImportError as exc: + raise ConstructorError("while constructing a Python object", mark, + "cannot find module %r (%s)" % (module_name, exc), mark) + if module_name not in sys.modules: + raise ConstructorError("while constructing a Python object", mark, + "module %r is not imported" % module_name, mark) + module = sys.modules[module_name] + if not hasattr(module, object_name): + raise ConstructorError("while constructing a Python object", mark, + "cannot find %r in the module %r" + % (object_name, module.__name__), mark) + return getattr(module, object_name) + + def construct_python_name(self, suffix, node): + value = self.construct_scalar(node) + if value: + raise ConstructorError("while constructing a Python name", node.start_mark, + "expected the empty value, but found %r" % value, node.start_mark) + return self.find_python_name(suffix, node.start_mark) + + def construct_python_module(self, suffix, node): + value = self.construct_scalar(node) + if value: + raise ConstructorError("while constructing a Python module", node.start_mark, + "expected the empty value, but found %r" % value, node.start_mark) + return self.find_python_module(suffix, node.start_mark) + + def make_python_instance(self, suffix, node, + args=None, kwds=None, newobj=False, unsafe=False): + if not args: + args = [] + if not kwds: + kwds = {} + cls = self.find_python_name(suffix, node.start_mark) + if not (unsafe or isinstance(cls, type)): + raise ConstructorError("while constructing a Python instance", node.start_mark, + "expected a class, but found %r" % type(cls), + node.start_mark) + if newobj and isinstance(cls, type): + return cls.__new__(cls, *args, **kwds) + else: + return cls(*args, **kwds) + + def set_python_instance_state(self, instance, state, unsafe=False): + if hasattr(instance, '__setstate__'): + instance.__setstate__(state) + else: + slotstate = {} + if isinstance(state, tuple) and len(state) == 2: + state, slotstate = state + if hasattr(instance, '__dict__'): + if not unsafe and state: + for key in state.keys(): + self.check_state_key(key) + instance.__dict__.update(state) + elif state: + slotstate.update(state) + for key, value in slotstate.items(): + if not unsafe: + self.check_state_key(key) + setattr(instance, key, value) + + def construct_python_object(self, suffix, node): + # Format: + # !!python/object:module.name { ... state ... } + instance = self.make_python_instance(suffix, node, newobj=True) + yield instance + deep = hasattr(instance, '__setstate__') + state = self.construct_mapping(node, deep=deep) + self.set_python_instance_state(instance, state) + + def construct_python_object_apply(self, suffix, node, newobj=False): + # Format: + # !!python/object/apply # (or !!python/object/new) + # args: [ ... arguments ... ] + # kwds: { ... keywords ... } + # state: ... state ... + # listitems: [ ... listitems ... ] + # dictitems: { ... dictitems ... } + # or short format: + # !!python/object/apply [ ... arguments ... ] + # The difference between !!python/object/apply and !!python/object/new + # is how an object is created, check make_python_instance for details. + if isinstance(node, SequenceNode): + args = self.construct_sequence(node, deep=True) + kwds = {} + state = {} + listitems = [] + dictitems = {} + else: + value = self.construct_mapping(node, deep=True) + args = value.get('args', []) + kwds = value.get('kwds', {}) + state = value.get('state', {}) + listitems = value.get('listitems', []) + dictitems = value.get('dictitems', {}) + instance = self.make_python_instance(suffix, node, args, kwds, newobj) + if state: + self.set_python_instance_state(instance, state) + if listitems: + instance.extend(listitems) + if dictitems: + for key in dictitems: + instance[key] = dictitems[key] + return instance + + def construct_python_object_new(self, suffix, node): + return self.construct_python_object_apply(suffix, node, newobj=True) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/none', + FullConstructor.construct_yaml_null) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/bool', + FullConstructor.construct_yaml_bool) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/str', + FullConstructor.construct_python_str) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/unicode', + FullConstructor.construct_python_unicode) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/bytes', + FullConstructor.construct_python_bytes) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/int', + FullConstructor.construct_yaml_int) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/long', + FullConstructor.construct_python_long) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/float', + FullConstructor.construct_yaml_float) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/complex', + FullConstructor.construct_python_complex) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/list', + FullConstructor.construct_yaml_seq) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/tuple', + FullConstructor.construct_python_tuple) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/dict', + FullConstructor.construct_yaml_map) + +FullConstructor.add_multi_constructor( + 'tag:yaml.org,2002:python/name:', + FullConstructor.construct_python_name) + +class UnsafeConstructor(FullConstructor): + + def find_python_module(self, name, mark): + return super(UnsafeConstructor, self).find_python_module(name, mark, unsafe=True) + + def find_python_name(self, name, mark): + return super(UnsafeConstructor, self).find_python_name(name, mark, unsafe=True) + + def make_python_instance(self, suffix, node, args=None, kwds=None, newobj=False): + return super(UnsafeConstructor, self).make_python_instance( + suffix, node, args, kwds, newobj, unsafe=True) + + def set_python_instance_state(self, instance, state): + return super(UnsafeConstructor, self).set_python_instance_state( + instance, state, unsafe=True) + +UnsafeConstructor.add_multi_constructor( + 'tag:yaml.org,2002:python/module:', + UnsafeConstructor.construct_python_module) + +UnsafeConstructor.add_multi_constructor( + 'tag:yaml.org,2002:python/object:', + UnsafeConstructor.construct_python_object) + +UnsafeConstructor.add_multi_constructor( + 'tag:yaml.org,2002:python/object/new:', + UnsafeConstructor.construct_python_object_new) + +UnsafeConstructor.add_multi_constructor( + 'tag:yaml.org,2002:python/object/apply:', + UnsafeConstructor.construct_python_object_apply) + +# Constructor is same as UnsafeConstructor. Need to leave this in place in case +# people have extended it directly. +class Constructor(UnsafeConstructor): + pass diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/cyaml.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/cyaml.py new file mode 100644 index 0000000000000000000000000000000000000000..0c21345879b298bb8668201bebe7d289586b17f9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/cyaml.py @@ -0,0 +1,101 @@ + +__all__ = [ + 'CBaseLoader', 'CSafeLoader', 'CFullLoader', 'CUnsafeLoader', 'CLoader', + 'CBaseDumper', 'CSafeDumper', 'CDumper' +] + +from yaml._yaml import CParser, CEmitter + +from .constructor import * + +from .serializer import * +from .representer import * + +from .resolver import * + +class CBaseLoader(CParser, BaseConstructor, BaseResolver): + + def __init__(self, stream): + CParser.__init__(self, stream) + BaseConstructor.__init__(self) + BaseResolver.__init__(self) + +class CSafeLoader(CParser, SafeConstructor, Resolver): + + def __init__(self, stream): + CParser.__init__(self, stream) + SafeConstructor.__init__(self) + Resolver.__init__(self) + +class CFullLoader(CParser, FullConstructor, Resolver): + + def __init__(self, stream): + CParser.__init__(self, stream) + FullConstructor.__init__(self) + Resolver.__init__(self) + +class CUnsafeLoader(CParser, UnsafeConstructor, Resolver): + + def __init__(self, stream): + CParser.__init__(self, stream) + UnsafeConstructor.__init__(self) + Resolver.__init__(self) + +class CLoader(CParser, Constructor, Resolver): + + def __init__(self, stream): + CParser.__init__(self, stream) + Constructor.__init__(self) + Resolver.__init__(self) + +class CBaseDumper(CEmitter, BaseRepresenter, BaseResolver): + + def __init__(self, stream, + default_style=None, default_flow_style=False, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None, + encoding=None, explicit_start=None, explicit_end=None, + version=None, tags=None, sort_keys=True): + CEmitter.__init__(self, stream, canonical=canonical, + indent=indent, width=width, encoding=encoding, + allow_unicode=allow_unicode, line_break=line_break, + explicit_start=explicit_start, explicit_end=explicit_end, + version=version, tags=tags) + Representer.__init__(self, default_style=default_style, + default_flow_style=default_flow_style, sort_keys=sort_keys) + Resolver.__init__(self) + +class CSafeDumper(CEmitter, SafeRepresenter, Resolver): + + def __init__(self, stream, + default_style=None, default_flow_style=False, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None, + encoding=None, explicit_start=None, explicit_end=None, + version=None, tags=None, sort_keys=True): + CEmitter.__init__(self, stream, canonical=canonical, + indent=indent, width=width, encoding=encoding, + allow_unicode=allow_unicode, line_break=line_break, + explicit_start=explicit_start, explicit_end=explicit_end, + version=version, tags=tags) + SafeRepresenter.__init__(self, default_style=default_style, + default_flow_style=default_flow_style, sort_keys=sort_keys) + Resolver.__init__(self) + +class CDumper(CEmitter, Serializer, Representer, Resolver): + + def __init__(self, stream, + default_style=None, default_flow_style=False, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None, + encoding=None, explicit_start=None, explicit_end=None, + version=None, tags=None, sort_keys=True): + CEmitter.__init__(self, stream, canonical=canonical, + indent=indent, width=width, encoding=encoding, + allow_unicode=allow_unicode, line_break=line_break, + explicit_start=explicit_start, explicit_end=explicit_end, + version=version, tags=tags) + Representer.__init__(self, default_style=default_style, + default_flow_style=default_flow_style, sort_keys=sort_keys) + Resolver.__init__(self) + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/dumper.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/dumper.py new file mode 100644 index 0000000000000000000000000000000000000000..6aadba551f3836b02f4752277f4b3027073defad --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/dumper.py @@ -0,0 +1,62 @@ + +__all__ = ['BaseDumper', 'SafeDumper', 'Dumper'] + +from .emitter import * +from .serializer import * +from .representer import * +from .resolver import * + +class BaseDumper(Emitter, Serializer, BaseRepresenter, BaseResolver): + + def __init__(self, stream, + default_style=None, default_flow_style=False, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None, + encoding=None, explicit_start=None, explicit_end=None, + version=None, tags=None, sort_keys=True): + Emitter.__init__(self, stream, canonical=canonical, + indent=indent, width=width, + allow_unicode=allow_unicode, line_break=line_break) + Serializer.__init__(self, encoding=encoding, + explicit_start=explicit_start, explicit_end=explicit_end, + version=version, tags=tags) + Representer.__init__(self, default_style=default_style, + default_flow_style=default_flow_style, sort_keys=sort_keys) + Resolver.__init__(self) + +class SafeDumper(Emitter, Serializer, SafeRepresenter, Resolver): + + def __init__(self, stream, + default_style=None, default_flow_style=False, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None, + encoding=None, explicit_start=None, explicit_end=None, + version=None, tags=None, sort_keys=True): + Emitter.__init__(self, stream, canonical=canonical, + indent=indent, width=width, + allow_unicode=allow_unicode, line_break=line_break) + Serializer.__init__(self, encoding=encoding, + explicit_start=explicit_start, explicit_end=explicit_end, + version=version, tags=tags) + SafeRepresenter.__init__(self, default_style=default_style, + default_flow_style=default_flow_style, sort_keys=sort_keys) + Resolver.__init__(self) + +class Dumper(Emitter, Serializer, Representer, Resolver): + + def __init__(self, stream, + default_style=None, default_flow_style=False, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None, + encoding=None, explicit_start=None, explicit_end=None, + version=None, tags=None, sort_keys=True): + Emitter.__init__(self, stream, canonical=canonical, + indent=indent, width=width, + allow_unicode=allow_unicode, line_break=line_break) + Serializer.__init__(self, encoding=encoding, + explicit_start=explicit_start, explicit_end=explicit_end, + version=version, tags=tags) + Representer.__init__(self, default_style=default_style, + default_flow_style=default_flow_style, sort_keys=sort_keys) + Resolver.__init__(self) + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/emitter.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/emitter.py new file mode 100644 index 0000000000000000000000000000000000000000..a664d011162af69184df2f8e59ab7feec818f7c7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/emitter.py @@ -0,0 +1,1137 @@ + +# Emitter expects events obeying the following grammar: +# stream ::= STREAM-START document* STREAM-END +# document ::= DOCUMENT-START node DOCUMENT-END +# node ::= SCALAR | sequence | mapping +# sequence ::= SEQUENCE-START node* SEQUENCE-END +# mapping ::= MAPPING-START (node node)* MAPPING-END + +__all__ = ['Emitter', 'EmitterError'] + +from .error import YAMLError +from .events import * + +class EmitterError(YAMLError): + pass + +class ScalarAnalysis: + def __init__(self, scalar, empty, multiline, + allow_flow_plain, allow_block_plain, + allow_single_quoted, allow_double_quoted, + allow_block): + self.scalar = scalar + self.empty = empty + self.multiline = multiline + self.allow_flow_plain = allow_flow_plain + self.allow_block_plain = allow_block_plain + self.allow_single_quoted = allow_single_quoted + self.allow_double_quoted = allow_double_quoted + self.allow_block = allow_block + +class Emitter: + + DEFAULT_TAG_PREFIXES = { + '!' : '!', + 'tag:yaml.org,2002:' : '!!', + } + + def __init__(self, stream, canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None): + + # The stream should have the methods `write` and possibly `flush`. + self.stream = stream + + # Encoding can be overridden by STREAM-START. + self.encoding = None + + # Emitter is a state machine with a stack of states to handle nested + # structures. + self.states = [] + self.state = self.expect_stream_start + + # Current event and the event queue. + self.events = [] + self.event = None + + # The current indentation level and the stack of previous indents. + self.indents = [] + self.indent = None + + # Flow level. + self.flow_level = 0 + + # Contexts. + self.root_context = False + self.sequence_context = False + self.mapping_context = False + self.simple_key_context = False + + # Characteristics of the last emitted character: + # - current position. + # - is it a whitespace? + # - is it an indention character + # (indentation space, '-', '?', or ':')? + self.line = 0 + self.column = 0 + self.whitespace = True + self.indention = True + + # Whether the document requires an explicit document indicator + self.open_ended = False + + # Formatting details. + self.canonical = canonical + self.allow_unicode = allow_unicode + self.best_indent = 2 + if indent and 1 < indent < 10: + self.best_indent = indent + self.best_width = 80 + if width and width > self.best_indent*2: + self.best_width = width + self.best_line_break = '\n' + if line_break in ['\r', '\n', '\r\n']: + self.best_line_break = line_break + + # Tag prefixes. + self.tag_prefixes = None + + # Prepared anchor and tag. + self.prepared_anchor = None + self.prepared_tag = None + + # Scalar analysis and style. + self.analysis = None + self.style = None + + def dispose(self): + # Reset the state attributes (to clear self-references) + self.states = [] + self.state = None + + def emit(self, event): + self.events.append(event) + while not self.need_more_events(): + self.event = self.events.pop(0) + self.state() + self.event = None + + # In some cases, we wait for a few next events before emitting. + + def need_more_events(self): + if not self.events: + return True + event = self.events[0] + if isinstance(event, DocumentStartEvent): + return self.need_events(1) + elif isinstance(event, SequenceStartEvent): + return self.need_events(2) + elif isinstance(event, MappingStartEvent): + return self.need_events(3) + else: + return False + + def need_events(self, count): + level = 0 + for event in self.events[1:]: + if isinstance(event, (DocumentStartEvent, CollectionStartEvent)): + level += 1 + elif isinstance(event, (DocumentEndEvent, CollectionEndEvent)): + level -= 1 + elif isinstance(event, StreamEndEvent): + level = -1 + if level < 0: + return False + return (len(self.events) < count+1) + + def increase_indent(self, flow=False, indentless=False): + self.indents.append(self.indent) + if self.indent is None: + if flow: + self.indent = self.best_indent + else: + self.indent = 0 + elif not indentless: + self.indent += self.best_indent + + # States. + + # Stream handlers. + + def expect_stream_start(self): + if isinstance(self.event, StreamStartEvent): + if self.event.encoding and not hasattr(self.stream, 'encoding'): + self.encoding = self.event.encoding + self.write_stream_start() + self.state = self.expect_first_document_start + else: + raise EmitterError("expected StreamStartEvent, but got %s" + % self.event) + + def expect_nothing(self): + raise EmitterError("expected nothing, but got %s" % self.event) + + # Document handlers. + + def expect_first_document_start(self): + return self.expect_document_start(first=True) + + def expect_document_start(self, first=False): + if isinstance(self.event, DocumentStartEvent): + if (self.event.version or self.event.tags) and self.open_ended: + self.write_indicator('...', True) + self.write_indent() + if self.event.version: + version_text = self.prepare_version(self.event.version) + self.write_version_directive(version_text) + self.tag_prefixes = self.DEFAULT_TAG_PREFIXES.copy() + if self.event.tags: + handles = sorted(self.event.tags.keys()) + for handle in handles: + prefix = self.event.tags[handle] + self.tag_prefixes[prefix] = handle + handle_text = self.prepare_tag_handle(handle) + prefix_text = self.prepare_tag_prefix(prefix) + self.write_tag_directive(handle_text, prefix_text) + implicit = (first and not self.event.explicit and not self.canonical + and not self.event.version and not self.event.tags + and not self.check_empty_document()) + if not implicit: + self.write_indent() + self.write_indicator('---', True) + if self.canonical: + self.write_indent() + self.state = self.expect_document_root + elif isinstance(self.event, StreamEndEvent): + if self.open_ended: + self.write_indicator('...', True) + self.write_indent() + self.write_stream_end() + self.state = self.expect_nothing + else: + raise EmitterError("expected DocumentStartEvent, but got %s" + % self.event) + + def expect_document_end(self): + if isinstance(self.event, DocumentEndEvent): + self.write_indent() + if self.event.explicit: + self.write_indicator('...', True) + self.write_indent() + self.flush_stream() + self.state = self.expect_document_start + else: + raise EmitterError("expected DocumentEndEvent, but got %s" + % self.event) + + def expect_document_root(self): + self.states.append(self.expect_document_end) + self.expect_node(root=True) + + # Node handlers. + + def expect_node(self, root=False, sequence=False, mapping=False, + simple_key=False): + self.root_context = root + self.sequence_context = sequence + self.mapping_context = mapping + self.simple_key_context = simple_key + if isinstance(self.event, AliasEvent): + self.expect_alias() + elif isinstance(self.event, (ScalarEvent, CollectionStartEvent)): + self.process_anchor('&') + self.process_tag() + if isinstance(self.event, ScalarEvent): + self.expect_scalar() + elif isinstance(self.event, SequenceStartEvent): + if self.flow_level or self.canonical or self.event.flow_style \ + or self.check_empty_sequence(): + self.expect_flow_sequence() + else: + self.expect_block_sequence() + elif isinstance(self.event, MappingStartEvent): + if self.flow_level or self.canonical or self.event.flow_style \ + or self.check_empty_mapping(): + self.expect_flow_mapping() + else: + self.expect_block_mapping() + else: + raise EmitterError("expected NodeEvent, but got %s" % self.event) + + def expect_alias(self): + if self.event.anchor is None: + raise EmitterError("anchor is not specified for alias") + self.process_anchor('*') + self.state = self.states.pop() + + def expect_scalar(self): + self.increase_indent(flow=True) + self.process_scalar() + self.indent = self.indents.pop() + self.state = self.states.pop() + + # Flow sequence handlers. + + def expect_flow_sequence(self): + self.write_indicator('[', True, whitespace=True) + self.flow_level += 1 + self.increase_indent(flow=True) + self.state = self.expect_first_flow_sequence_item + + def expect_first_flow_sequence_item(self): + if isinstance(self.event, SequenceEndEvent): + self.indent = self.indents.pop() + self.flow_level -= 1 + self.write_indicator(']', False) + self.state = self.states.pop() + else: + if self.canonical or self.column > self.best_width: + self.write_indent() + self.states.append(self.expect_flow_sequence_item) + self.expect_node(sequence=True) + + def expect_flow_sequence_item(self): + if isinstance(self.event, SequenceEndEvent): + self.indent = self.indents.pop() + self.flow_level -= 1 + if self.canonical: + self.write_indicator(',', False) + self.write_indent() + self.write_indicator(']', False) + self.state = self.states.pop() + else: + self.write_indicator(',', False) + if self.canonical or self.column > self.best_width: + self.write_indent() + self.states.append(self.expect_flow_sequence_item) + self.expect_node(sequence=True) + + # Flow mapping handlers. + + def expect_flow_mapping(self): + self.write_indicator('{', True, whitespace=True) + self.flow_level += 1 + self.increase_indent(flow=True) + self.state = self.expect_first_flow_mapping_key + + def expect_first_flow_mapping_key(self): + if isinstance(self.event, MappingEndEvent): + self.indent = self.indents.pop() + self.flow_level -= 1 + self.write_indicator('}', False) + self.state = self.states.pop() + else: + if self.canonical or self.column > self.best_width: + self.write_indent() + if not self.canonical and self.check_simple_key(): + self.states.append(self.expect_flow_mapping_simple_value) + self.expect_node(mapping=True, simple_key=True) + else: + self.write_indicator('?', True) + self.states.append(self.expect_flow_mapping_value) + self.expect_node(mapping=True) + + def expect_flow_mapping_key(self): + if isinstance(self.event, MappingEndEvent): + self.indent = self.indents.pop() + self.flow_level -= 1 + if self.canonical: + self.write_indicator(',', False) + self.write_indent() + self.write_indicator('}', False) + self.state = self.states.pop() + else: + self.write_indicator(',', False) + if self.canonical or self.column > self.best_width: + self.write_indent() + if not self.canonical and self.check_simple_key(): + self.states.append(self.expect_flow_mapping_simple_value) + self.expect_node(mapping=True, simple_key=True) + else: + self.write_indicator('?', True) + self.states.append(self.expect_flow_mapping_value) + self.expect_node(mapping=True) + + def expect_flow_mapping_simple_value(self): + self.write_indicator(':', False) + self.states.append(self.expect_flow_mapping_key) + self.expect_node(mapping=True) + + def expect_flow_mapping_value(self): + if self.canonical or self.column > self.best_width: + self.write_indent() + self.write_indicator(':', True) + self.states.append(self.expect_flow_mapping_key) + self.expect_node(mapping=True) + + # Block sequence handlers. + + def expect_block_sequence(self): + indentless = (self.mapping_context and not self.indention) + self.increase_indent(flow=False, indentless=indentless) + self.state = self.expect_first_block_sequence_item + + def expect_first_block_sequence_item(self): + return self.expect_block_sequence_item(first=True) + + def expect_block_sequence_item(self, first=False): + if not first and isinstance(self.event, SequenceEndEvent): + self.indent = self.indents.pop() + self.state = self.states.pop() + else: + self.write_indent() + self.write_indicator('-', True, indention=True) + self.states.append(self.expect_block_sequence_item) + self.expect_node(sequence=True) + + # Block mapping handlers. + + def expect_block_mapping(self): + self.increase_indent(flow=False) + self.state = self.expect_first_block_mapping_key + + def expect_first_block_mapping_key(self): + return self.expect_block_mapping_key(first=True) + + def expect_block_mapping_key(self, first=False): + if not first and isinstance(self.event, MappingEndEvent): + self.indent = self.indents.pop() + self.state = self.states.pop() + else: + self.write_indent() + if self.check_simple_key(): + self.states.append(self.expect_block_mapping_simple_value) + self.expect_node(mapping=True, simple_key=True) + else: + self.write_indicator('?', True, indention=True) + self.states.append(self.expect_block_mapping_value) + self.expect_node(mapping=True) + + def expect_block_mapping_simple_value(self): + self.write_indicator(':', False) + self.states.append(self.expect_block_mapping_key) + self.expect_node(mapping=True) + + def expect_block_mapping_value(self): + self.write_indent() + self.write_indicator(':', True, indention=True) + self.states.append(self.expect_block_mapping_key) + self.expect_node(mapping=True) + + # Checkers. + + def check_empty_sequence(self): + return (isinstance(self.event, SequenceStartEvent) and self.events + and isinstance(self.events[0], SequenceEndEvent)) + + def check_empty_mapping(self): + return (isinstance(self.event, MappingStartEvent) and self.events + and isinstance(self.events[0], MappingEndEvent)) + + def check_empty_document(self): + if not isinstance(self.event, DocumentStartEvent) or not self.events: + return False + event = self.events[0] + return (isinstance(event, ScalarEvent) and event.anchor is None + and event.tag is None and event.implicit and event.value == '') + + def check_simple_key(self): + length = 0 + if isinstance(self.event, NodeEvent) and self.event.anchor is not None: + if self.prepared_anchor is None: + self.prepared_anchor = self.prepare_anchor(self.event.anchor) + length += len(self.prepared_anchor) + if isinstance(self.event, (ScalarEvent, CollectionStartEvent)) \ + and self.event.tag is not None: + if self.prepared_tag is None: + self.prepared_tag = self.prepare_tag(self.event.tag) + length += len(self.prepared_tag) + if isinstance(self.event, ScalarEvent): + if self.analysis is None: + self.analysis = self.analyze_scalar(self.event.value) + length += len(self.analysis.scalar) + return (length < 128 and (isinstance(self.event, AliasEvent) + or (isinstance(self.event, ScalarEvent) + and not self.analysis.empty and not self.analysis.multiline) + or self.check_empty_sequence() or self.check_empty_mapping())) + + # Anchor, Tag, and Scalar processors. + + def process_anchor(self, indicator): + if self.event.anchor is None: + self.prepared_anchor = None + return + if self.prepared_anchor is None: + self.prepared_anchor = self.prepare_anchor(self.event.anchor) + if self.prepared_anchor: + self.write_indicator(indicator+self.prepared_anchor, True) + self.prepared_anchor = None + + def process_tag(self): + tag = self.event.tag + if isinstance(self.event, ScalarEvent): + if self.style is None: + self.style = self.choose_scalar_style() + if ((not self.canonical or tag is None) and + ((self.style == '' and self.event.implicit[0]) + or (self.style != '' and self.event.implicit[1]))): + self.prepared_tag = None + return + if self.event.implicit[0] and tag is None: + tag = '!' + self.prepared_tag = None + else: + if (not self.canonical or tag is None) and self.event.implicit: + self.prepared_tag = None + return + if tag is None: + raise EmitterError("tag is not specified") + if self.prepared_tag is None: + self.prepared_tag = self.prepare_tag(tag) + if self.prepared_tag: + self.write_indicator(self.prepared_tag, True) + self.prepared_tag = None + + def choose_scalar_style(self): + if self.analysis is None: + self.analysis = self.analyze_scalar(self.event.value) + if self.event.style == '"' or self.canonical: + return '"' + if not self.event.style and self.event.implicit[0]: + if (not (self.simple_key_context and + (self.analysis.empty or self.analysis.multiline)) + and (self.flow_level and self.analysis.allow_flow_plain + or (not self.flow_level and self.analysis.allow_block_plain))): + return '' + if self.event.style and self.event.style in '|>': + if (not self.flow_level and not self.simple_key_context + and self.analysis.allow_block): + return self.event.style + if not self.event.style or self.event.style == '\'': + if (self.analysis.allow_single_quoted and + not (self.simple_key_context and self.analysis.multiline)): + return '\'' + return '"' + + def process_scalar(self): + if self.analysis is None: + self.analysis = self.analyze_scalar(self.event.value) + if self.style is None: + self.style = self.choose_scalar_style() + split = (not self.simple_key_context) + #if self.analysis.multiline and split \ + # and (not self.style or self.style in '\'\"'): + # self.write_indent() + if self.style == '"': + self.write_double_quoted(self.analysis.scalar, split) + elif self.style == '\'': + self.write_single_quoted(self.analysis.scalar, split) + elif self.style == '>': + self.write_folded(self.analysis.scalar) + elif self.style == '|': + self.write_literal(self.analysis.scalar) + else: + self.write_plain(self.analysis.scalar, split) + self.analysis = None + self.style = None + + # Analyzers. + + def prepare_version(self, version): + major, minor = version + if major != 1: + raise EmitterError("unsupported YAML version: %d.%d" % (major, minor)) + return '%d.%d' % (major, minor) + + def prepare_tag_handle(self, handle): + if not handle: + raise EmitterError("tag handle must not be empty") + if handle[0] != '!' or handle[-1] != '!': + raise EmitterError("tag handle must start and end with '!': %r" % handle) + for ch in handle[1:-1]: + if not ('0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-_'): + raise EmitterError("invalid character %r in the tag handle: %r" + % (ch, handle)) + return handle + + def prepare_tag_prefix(self, prefix): + if not prefix: + raise EmitterError("tag prefix must not be empty") + chunks = [] + start = end = 0 + if prefix[0] == '!': + end = 1 + while end < len(prefix): + ch = prefix[end] + if '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-;/?!:@&=+$,_.~*\'()[]': + end += 1 + else: + if start < end: + chunks.append(prefix[start:end]) + start = end = end+1 + data = ch.encode('utf-8') + for ch in data: + chunks.append('%%%02X' % ord(ch)) + if start < end: + chunks.append(prefix[start:end]) + return ''.join(chunks) + + def prepare_tag(self, tag): + if not tag: + raise EmitterError("tag must not be empty") + if tag == '!': + return tag + handle = None + suffix = tag + prefixes = sorted(self.tag_prefixes.keys()) + for prefix in prefixes: + if tag.startswith(prefix) \ + and (prefix == '!' or len(prefix) < len(tag)): + handle = self.tag_prefixes[prefix] + suffix = tag[len(prefix):] + chunks = [] + start = end = 0 + while end < len(suffix): + ch = suffix[end] + if '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-;/?:@&=+$,_.~*\'()[]' \ + or (ch == '!' and handle != '!'): + end += 1 + else: + if start < end: + chunks.append(suffix[start:end]) + start = end = end+1 + data = ch.encode('utf-8') + for ch in data: + chunks.append('%%%02X' % ch) + if start < end: + chunks.append(suffix[start:end]) + suffix_text = ''.join(chunks) + if handle: + return '%s%s' % (handle, suffix_text) + else: + return '!<%s>' % suffix_text + + def prepare_anchor(self, anchor): + if not anchor: + raise EmitterError("anchor must not be empty") + for ch in anchor: + if not ('0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-_'): + raise EmitterError("invalid character %r in the anchor: %r" + % (ch, anchor)) + return anchor + + def analyze_scalar(self, scalar): + + # Empty scalar is a special case. + if not scalar: + return ScalarAnalysis(scalar=scalar, empty=True, multiline=False, + allow_flow_plain=False, allow_block_plain=True, + allow_single_quoted=True, allow_double_quoted=True, + allow_block=False) + + # Indicators and special characters. + block_indicators = False + flow_indicators = False + line_breaks = False + special_characters = False + + # Important whitespace combinations. + leading_space = False + leading_break = False + trailing_space = False + trailing_break = False + break_space = False + space_break = False + + # Check document indicators. + if scalar.startswith('---') or scalar.startswith('...'): + block_indicators = True + flow_indicators = True + + # First character or preceded by a whitespace. + preceded_by_whitespace = True + + # Last character or followed by a whitespace. + followed_by_whitespace = (len(scalar) == 1 or + scalar[1] in '\0 \t\r\n\x85\u2028\u2029') + + # The previous character is a space. + previous_space = False + + # The previous character is a break. + previous_break = False + + index = 0 + while index < len(scalar): + ch = scalar[index] + + # Check for indicators. + if index == 0: + # Leading indicators are special characters. + if ch in '#,[]{}&*!|>\'\"%@`': + flow_indicators = True + block_indicators = True + if ch in '?:': + flow_indicators = True + if followed_by_whitespace: + block_indicators = True + if ch == '-' and followed_by_whitespace: + flow_indicators = True + block_indicators = True + else: + # Some indicators cannot appear within a scalar as well. + if ch in ',?[]{}': + flow_indicators = True + if ch == ':': + flow_indicators = True + if followed_by_whitespace: + block_indicators = True + if ch == '#' and preceded_by_whitespace: + flow_indicators = True + block_indicators = True + + # Check for line breaks, special, and unicode characters. + if ch in '\n\x85\u2028\u2029': + line_breaks = True + if not (ch == '\n' or '\x20' <= ch <= '\x7E'): + if (ch == '\x85' or '\xA0' <= ch <= '\uD7FF' + or '\uE000' <= ch <= '\uFFFD' + or '\U00010000' <= ch < '\U0010ffff') and ch != '\uFEFF': + unicode_characters = True + if not self.allow_unicode: + special_characters = True + else: + special_characters = True + + # Detect important whitespace combinations. + if ch == ' ': + if index == 0: + leading_space = True + if index == len(scalar)-1: + trailing_space = True + if previous_break: + break_space = True + previous_space = True + previous_break = False + elif ch in '\n\x85\u2028\u2029': + if index == 0: + leading_break = True + if index == len(scalar)-1: + trailing_break = True + if previous_space: + space_break = True + previous_space = False + previous_break = True + else: + previous_space = False + previous_break = False + + # Prepare for the next character. + index += 1 + preceded_by_whitespace = (ch in '\0 \t\r\n\x85\u2028\u2029') + followed_by_whitespace = (index+1 >= len(scalar) or + scalar[index+1] in '\0 \t\r\n\x85\u2028\u2029') + + # Let's decide what styles are allowed. + allow_flow_plain = True + allow_block_plain = True + allow_single_quoted = True + allow_double_quoted = True + allow_block = True + + # Leading and trailing whitespaces are bad for plain scalars. + if (leading_space or leading_break + or trailing_space or trailing_break): + allow_flow_plain = allow_block_plain = False + + # We do not permit trailing spaces for block scalars. + if trailing_space: + allow_block = False + + # Spaces at the beginning of a new line are only acceptable for block + # scalars. + if break_space: + allow_flow_plain = allow_block_plain = allow_single_quoted = False + + # Spaces followed by breaks, as well as special character are only + # allowed for double quoted scalars. + if space_break or special_characters: + allow_flow_plain = allow_block_plain = \ + allow_single_quoted = allow_block = False + + # Although the plain scalar writer supports breaks, we never emit + # multiline plain scalars. + if line_breaks: + allow_flow_plain = allow_block_plain = False + + # Flow indicators are forbidden for flow plain scalars. + if flow_indicators: + allow_flow_plain = False + + # Block indicators are forbidden for block plain scalars. + if block_indicators: + allow_block_plain = False + + return ScalarAnalysis(scalar=scalar, + empty=False, multiline=line_breaks, + allow_flow_plain=allow_flow_plain, + allow_block_plain=allow_block_plain, + allow_single_quoted=allow_single_quoted, + allow_double_quoted=allow_double_quoted, + allow_block=allow_block) + + # Writers. + + def flush_stream(self): + if hasattr(self.stream, 'flush'): + self.stream.flush() + + def write_stream_start(self): + # Write BOM if needed. + if self.encoding and self.encoding.startswith('utf-16'): + self.stream.write('\uFEFF'.encode(self.encoding)) + + def write_stream_end(self): + self.flush_stream() + + def write_indicator(self, indicator, need_whitespace, + whitespace=False, indention=False): + if self.whitespace or not need_whitespace: + data = indicator + else: + data = ' '+indicator + self.whitespace = whitespace + self.indention = self.indention and indention + self.column += len(data) + self.open_ended = False + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + + def write_indent(self): + indent = self.indent or 0 + if not self.indention or self.column > indent \ + or (self.column == indent and not self.whitespace): + self.write_line_break() + if self.column < indent: + self.whitespace = True + data = ' '*(indent-self.column) + self.column = indent + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + + def write_line_break(self, data=None): + if data is None: + data = self.best_line_break + self.whitespace = True + self.indention = True + self.line += 1 + self.column = 0 + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + + def write_version_directive(self, version_text): + data = '%%YAML %s' % version_text + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + self.write_line_break() + + def write_tag_directive(self, handle_text, prefix_text): + data = '%%TAG %s %s' % (handle_text, prefix_text) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + self.write_line_break() + + # Scalar streams. + + def write_single_quoted(self, text, split=True): + self.write_indicator('\'', True) + spaces = False + breaks = False + start = end = 0 + while end <= len(text): + ch = None + if end < len(text): + ch = text[end] + if spaces: + if ch is None or ch != ' ': + if start+1 == end and self.column > self.best_width and split \ + and start != 0 and end != len(text): + self.write_indent() + else: + data = text[start:end] + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + start = end + elif breaks: + if ch is None or ch not in '\n\x85\u2028\u2029': + if text[start] == '\n': + self.write_line_break() + for br in text[start:end]: + if br == '\n': + self.write_line_break() + else: + self.write_line_break(br) + self.write_indent() + start = end + else: + if ch is None or ch in ' \n\x85\u2028\u2029' or ch == '\'': + if start < end: + data = text[start:end] + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + start = end + if ch == '\'': + data = '\'\'' + self.column += 2 + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + start = end + 1 + if ch is not None: + spaces = (ch == ' ') + breaks = (ch in '\n\x85\u2028\u2029') + end += 1 + self.write_indicator('\'', False) + + ESCAPE_REPLACEMENTS = { + '\0': '0', + '\x07': 'a', + '\x08': 'b', + '\x09': 't', + '\x0A': 'n', + '\x0B': 'v', + '\x0C': 'f', + '\x0D': 'r', + '\x1B': 'e', + '\"': '\"', + '\\': '\\', + '\x85': 'N', + '\xA0': '_', + '\u2028': 'L', + '\u2029': 'P', + } + + def write_double_quoted(self, text, split=True): + self.write_indicator('"', True) + start = end = 0 + while end <= len(text): + ch = None + if end < len(text): + ch = text[end] + if ch is None or ch in '"\\\x85\u2028\u2029\uFEFF' \ + or not ('\x20' <= ch <= '\x7E' + or (self.allow_unicode + and ('\xA0' <= ch <= '\uD7FF' + or '\uE000' <= ch <= '\uFFFD'))): + if start < end: + data = text[start:end] + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + start = end + if ch is not None: + if ch in self.ESCAPE_REPLACEMENTS: + data = '\\'+self.ESCAPE_REPLACEMENTS[ch] + elif ch <= '\xFF': + data = '\\x%02X' % ord(ch) + elif ch <= '\uFFFF': + data = '\\u%04X' % ord(ch) + else: + data = '\\U%08X' % ord(ch) + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + start = end+1 + if 0 < end < len(text)-1 and (ch == ' ' or start >= end) \ + and self.column+(end-start) > self.best_width and split: + data = text[start:end]+'\\' + if start < end: + start = end + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + self.write_indent() + self.whitespace = False + self.indention = False + if text[start] == ' ': + data = '\\' + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + end += 1 + self.write_indicator('"', False) + + def determine_block_hints(self, text): + hints = '' + if text: + if text[0] in ' \n\x85\u2028\u2029': + hints += str(self.best_indent) + if text[-1] not in '\n\x85\u2028\u2029': + hints += '-' + elif len(text) == 1 or text[-2] in '\n\x85\u2028\u2029': + hints += '+' + return hints + + def write_folded(self, text): + hints = self.determine_block_hints(text) + self.write_indicator('>'+hints, True) + if hints[-1:] == '+': + self.open_ended = True + self.write_line_break() + leading_space = True + spaces = False + breaks = True + start = end = 0 + while end <= len(text): + ch = None + if end < len(text): + ch = text[end] + if breaks: + if ch is None or ch not in '\n\x85\u2028\u2029': + if not leading_space and ch is not None and ch != ' ' \ + and text[start] == '\n': + self.write_line_break() + leading_space = (ch == ' ') + for br in text[start:end]: + if br == '\n': + self.write_line_break() + else: + self.write_line_break(br) + if ch is not None: + self.write_indent() + start = end + elif spaces: + if ch != ' ': + if start+1 == end and self.column > self.best_width: + self.write_indent() + else: + data = text[start:end] + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + start = end + else: + if ch is None or ch in ' \n\x85\u2028\u2029': + data = text[start:end] + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + if ch is None: + self.write_line_break() + start = end + if ch is not None: + breaks = (ch in '\n\x85\u2028\u2029') + spaces = (ch == ' ') + end += 1 + + def write_literal(self, text): + hints = self.determine_block_hints(text) + self.write_indicator('|'+hints, True) + if hints[-1:] == '+': + self.open_ended = True + self.write_line_break() + breaks = True + start = end = 0 + while end <= len(text): + ch = None + if end < len(text): + ch = text[end] + if breaks: + if ch is None or ch not in '\n\x85\u2028\u2029': + for br in text[start:end]: + if br == '\n': + self.write_line_break() + else: + self.write_line_break(br) + if ch is not None: + self.write_indent() + start = end + else: + if ch is None or ch in '\n\x85\u2028\u2029': + data = text[start:end] + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + if ch is None: + self.write_line_break() + start = end + if ch is not None: + breaks = (ch in '\n\x85\u2028\u2029') + end += 1 + + def write_plain(self, text, split=True): + if self.root_context: + self.open_ended = True + if not text: + return + if not self.whitespace: + data = ' ' + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + self.whitespace = False + self.indention = False + spaces = False + breaks = False + start = end = 0 + while end <= len(text): + ch = None + if end < len(text): + ch = text[end] + if spaces: + if ch != ' ': + if start+1 == end and self.column > self.best_width and split: + self.write_indent() + self.whitespace = False + self.indention = False + else: + data = text[start:end] + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + start = end + elif breaks: + if ch not in '\n\x85\u2028\u2029': + if text[start] == '\n': + self.write_line_break() + for br in text[start:end]: + if br == '\n': + self.write_line_break() + else: + self.write_line_break(br) + self.write_indent() + self.whitespace = False + self.indention = False + start = end + else: + if ch is None or ch in ' \n\x85\u2028\u2029': + data = text[start:end] + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + start = end + if ch is not None: + spaces = (ch == ' ') + breaks = (ch in '\n\x85\u2028\u2029') + end += 1 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/error.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/error.py new file mode 100644 index 0000000000000000000000000000000000000000..b796b4dc519512c4825ff539a2e6aa20f4d370d0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/error.py @@ -0,0 +1,75 @@ + +__all__ = ['Mark', 'YAMLError', 'MarkedYAMLError'] + +class Mark: + + def __init__(self, name, index, line, column, buffer, pointer): + self.name = name + self.index = index + self.line = line + self.column = column + self.buffer = buffer + self.pointer = pointer + + def get_snippet(self, indent=4, max_length=75): + if self.buffer is None: + return None + head = '' + start = self.pointer + while start > 0 and self.buffer[start-1] not in '\0\r\n\x85\u2028\u2029': + start -= 1 + if self.pointer-start > max_length/2-1: + head = ' ... ' + start += 5 + break + tail = '' + end = self.pointer + while end < len(self.buffer) and self.buffer[end] not in '\0\r\n\x85\u2028\u2029': + end += 1 + if end-self.pointer > max_length/2-1: + tail = ' ... ' + end -= 5 + break + snippet = self.buffer[start:end] + return ' '*indent + head + snippet + tail + '\n' \ + + ' '*(indent+self.pointer-start+len(head)) + '^' + + def __str__(self): + snippet = self.get_snippet() + where = " in \"%s\", line %d, column %d" \ + % (self.name, self.line+1, self.column+1) + if snippet is not None: + where += ":\n"+snippet + return where + +class YAMLError(Exception): + pass + +class MarkedYAMLError(YAMLError): + + def __init__(self, context=None, context_mark=None, + problem=None, problem_mark=None, note=None): + self.context = context + self.context_mark = context_mark + self.problem = problem + self.problem_mark = problem_mark + self.note = note + + def __str__(self): + lines = [] + if self.context is not None: + lines.append(self.context) + if self.context_mark is not None \ + and (self.problem is None or self.problem_mark is None + or self.context_mark.name != self.problem_mark.name + or self.context_mark.line != self.problem_mark.line + or self.context_mark.column != self.problem_mark.column): + lines.append(str(self.context_mark)) + if self.problem is not None: + lines.append(self.problem) + if self.problem_mark is not None: + lines.append(str(self.problem_mark)) + if self.note is not None: + lines.append(self.note) + return '\n'.join(lines) + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/events.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/events.py new file mode 100644 index 0000000000000000000000000000000000000000..f79ad389cb6c9517e391dcd25534866bc9ccd36a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/events.py @@ -0,0 +1,86 @@ + +# Abstract classes. + +class Event(object): + def __init__(self, start_mark=None, end_mark=None): + self.start_mark = start_mark + self.end_mark = end_mark + def __repr__(self): + attributes = [key for key in ['anchor', 'tag', 'implicit', 'value'] + if hasattr(self, key)] + arguments = ', '.join(['%s=%r' % (key, getattr(self, key)) + for key in attributes]) + return '%s(%s)' % (self.__class__.__name__, arguments) + +class NodeEvent(Event): + def __init__(self, anchor, start_mark=None, end_mark=None): + self.anchor = anchor + self.start_mark = start_mark + self.end_mark = end_mark + +class CollectionStartEvent(NodeEvent): + def __init__(self, anchor, tag, implicit, start_mark=None, end_mark=None, + flow_style=None): + self.anchor = anchor + self.tag = tag + self.implicit = implicit + self.start_mark = start_mark + self.end_mark = end_mark + self.flow_style = flow_style + +class CollectionEndEvent(Event): + pass + +# Implementations. + +class StreamStartEvent(Event): + def __init__(self, start_mark=None, end_mark=None, encoding=None): + self.start_mark = start_mark + self.end_mark = end_mark + self.encoding = encoding + +class StreamEndEvent(Event): + pass + +class DocumentStartEvent(Event): + def __init__(self, start_mark=None, end_mark=None, + explicit=None, version=None, tags=None): + self.start_mark = start_mark + self.end_mark = end_mark + self.explicit = explicit + self.version = version + self.tags = tags + +class DocumentEndEvent(Event): + def __init__(self, start_mark=None, end_mark=None, + explicit=None): + self.start_mark = start_mark + self.end_mark = end_mark + self.explicit = explicit + +class AliasEvent(NodeEvent): + pass + +class ScalarEvent(NodeEvent): + def __init__(self, anchor, tag, implicit, value, + start_mark=None, end_mark=None, style=None): + self.anchor = anchor + self.tag = tag + self.implicit = implicit + self.value = value + self.start_mark = start_mark + self.end_mark = end_mark + self.style = style + +class SequenceStartEvent(CollectionStartEvent): + pass + +class SequenceEndEvent(CollectionEndEvent): + pass + +class MappingStartEvent(CollectionStartEvent): + pass + +class MappingEndEvent(CollectionEndEvent): + pass + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/loader.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/loader.py new file mode 100644 index 0000000000000000000000000000000000000000..e90c11224c38e559cdf0cb205f0692ebd4fb8681 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/loader.py @@ -0,0 +1,63 @@ + +__all__ = ['BaseLoader', 'FullLoader', 'SafeLoader', 'Loader', 'UnsafeLoader'] + +from .reader import * +from .scanner import * +from .parser import * +from .composer import * +from .constructor import * +from .resolver import * + +class BaseLoader(Reader, Scanner, Parser, Composer, BaseConstructor, BaseResolver): + + def __init__(self, stream): + Reader.__init__(self, stream) + Scanner.__init__(self) + Parser.__init__(self) + Composer.__init__(self) + BaseConstructor.__init__(self) + BaseResolver.__init__(self) + +class FullLoader(Reader, Scanner, Parser, Composer, FullConstructor, Resolver): + + def __init__(self, stream): + Reader.__init__(self, stream) + Scanner.__init__(self) + Parser.__init__(self) + Composer.__init__(self) + FullConstructor.__init__(self) + Resolver.__init__(self) + +class SafeLoader(Reader, Scanner, Parser, Composer, SafeConstructor, Resolver): + + def __init__(self, stream): + Reader.__init__(self, stream) + Scanner.__init__(self) + Parser.__init__(self) + Composer.__init__(self) + SafeConstructor.__init__(self) + Resolver.__init__(self) + +class Loader(Reader, Scanner, Parser, Composer, Constructor, Resolver): + + def __init__(self, stream): + Reader.__init__(self, stream) + Scanner.__init__(self) + Parser.__init__(self) + Composer.__init__(self) + Constructor.__init__(self) + Resolver.__init__(self) + +# UnsafeLoader is the same as Loader (which is and was always unsafe on +# untrusted input). Use of either Loader or UnsafeLoader should be rare, since +# FullLoad should be able to load almost all YAML safely. Loader is left intact +# to ensure backwards compatibility. +class UnsafeLoader(Reader, Scanner, Parser, Composer, Constructor, Resolver): + + def __init__(self, stream): + Reader.__init__(self, stream) + Scanner.__init__(self) + Parser.__init__(self) + Composer.__init__(self) + Constructor.__init__(self) + Resolver.__init__(self) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/nodes.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..c4f070c41e1fb1bc01af27d69329e92dded38908 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/nodes.py @@ -0,0 +1,49 @@ + +class Node(object): + def __init__(self, tag, value, start_mark, end_mark): + self.tag = tag + self.value = value + self.start_mark = start_mark + self.end_mark = end_mark + def __repr__(self): + value = self.value + #if isinstance(value, list): + # if len(value) == 0: + # value = '' + # elif len(value) == 1: + # value = '<1 item>' + # else: + # value = '<%d items>' % len(value) + #else: + # if len(value) > 75: + # value = repr(value[:70]+u' ... ') + # else: + # value = repr(value) + value = repr(value) + return '%s(tag=%r, value=%s)' % (self.__class__.__name__, self.tag, value) + +class ScalarNode(Node): + id = 'scalar' + def __init__(self, tag, value, + start_mark=None, end_mark=None, style=None): + self.tag = tag + self.value = value + self.start_mark = start_mark + self.end_mark = end_mark + self.style = style + +class CollectionNode(Node): + def __init__(self, tag, value, + start_mark=None, end_mark=None, flow_style=None): + self.tag = tag + self.value = value + self.start_mark = start_mark + self.end_mark = end_mark + self.flow_style = flow_style + +class SequenceNode(CollectionNode): + id = 'sequence' + +class MappingNode(CollectionNode): + id = 'mapping' + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/parser.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/parser.py new file mode 100644 index 0000000000000000000000000000000000000000..13a5995d292045d0f865a99abf692bd35dc87814 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/parser.py @@ -0,0 +1,589 @@ + +# The following YAML grammar is LL(1) and is parsed by a recursive descent +# parser. +# +# stream ::= STREAM-START implicit_document? explicit_document* STREAM-END +# implicit_document ::= block_node DOCUMENT-END* +# explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +# block_node_or_indentless_sequence ::= +# ALIAS +# | properties (block_content | indentless_block_sequence)? +# | block_content +# | indentless_block_sequence +# block_node ::= ALIAS +# | properties block_content? +# | block_content +# flow_node ::= ALIAS +# | properties flow_content? +# | flow_content +# properties ::= TAG ANCHOR? | ANCHOR TAG? +# block_content ::= block_collection | flow_collection | SCALAR +# flow_content ::= flow_collection | SCALAR +# block_collection ::= block_sequence | block_mapping +# flow_collection ::= flow_sequence | flow_mapping +# block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END +# indentless_sequence ::= (BLOCK-ENTRY block_node?)+ +# block_mapping ::= BLOCK-MAPPING_START +# ((KEY block_node_or_indentless_sequence?)? +# (VALUE block_node_or_indentless_sequence?)?)* +# BLOCK-END +# flow_sequence ::= FLOW-SEQUENCE-START +# (flow_sequence_entry FLOW-ENTRY)* +# flow_sequence_entry? +# FLOW-SEQUENCE-END +# flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +# flow_mapping ::= FLOW-MAPPING-START +# (flow_mapping_entry FLOW-ENTRY)* +# flow_mapping_entry? +# FLOW-MAPPING-END +# flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +# +# FIRST sets: +# +# stream: { STREAM-START } +# explicit_document: { DIRECTIVE DOCUMENT-START } +# implicit_document: FIRST(block_node) +# block_node: { ALIAS TAG ANCHOR SCALAR BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START } +# flow_node: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START } +# block_content: { BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START SCALAR } +# flow_content: { FLOW-SEQUENCE-START FLOW-MAPPING-START SCALAR } +# block_collection: { BLOCK-SEQUENCE-START BLOCK-MAPPING-START } +# flow_collection: { FLOW-SEQUENCE-START FLOW-MAPPING-START } +# block_sequence: { BLOCK-SEQUENCE-START } +# block_mapping: { BLOCK-MAPPING-START } +# block_node_or_indentless_sequence: { ALIAS ANCHOR TAG SCALAR BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START BLOCK-ENTRY } +# indentless_sequence: { ENTRY } +# flow_collection: { FLOW-SEQUENCE-START FLOW-MAPPING-START } +# flow_sequence: { FLOW-SEQUENCE-START } +# flow_mapping: { FLOW-MAPPING-START } +# flow_sequence_entry: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START KEY } +# flow_mapping_entry: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START KEY } + +__all__ = ['Parser', 'ParserError'] + +from .error import MarkedYAMLError +from .tokens import * +from .events import * +from .scanner import * + +class ParserError(MarkedYAMLError): + pass + +class Parser: + # Since writing a recursive-descendant parser is a straightforward task, we + # do not give many comments here. + + DEFAULT_TAGS = { + '!': '!', + '!!': 'tag:yaml.org,2002:', + } + + def __init__(self): + self.current_event = None + self.yaml_version = None + self.tag_handles = {} + self.states = [] + self.marks = [] + self.state = self.parse_stream_start + + def dispose(self): + # Reset the state attributes (to clear self-references) + self.states = [] + self.state = None + + def check_event(self, *choices): + # Check the type of the next event. + if self.current_event is None: + if self.state: + self.current_event = self.state() + if self.current_event is not None: + if not choices: + return True + for choice in choices: + if isinstance(self.current_event, choice): + return True + return False + + def peek_event(self): + # Get the next event. + if self.current_event is None: + if self.state: + self.current_event = self.state() + return self.current_event + + def get_event(self): + # Get the next event and proceed further. + if self.current_event is None: + if self.state: + self.current_event = self.state() + value = self.current_event + self.current_event = None + return value + + # stream ::= STREAM-START implicit_document? explicit_document* STREAM-END + # implicit_document ::= block_node DOCUMENT-END* + # explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* + + def parse_stream_start(self): + + # Parse the stream start. + token = self.get_token() + event = StreamStartEvent(token.start_mark, token.end_mark, + encoding=token.encoding) + + # Prepare the next state. + self.state = self.parse_implicit_document_start + + return event + + def parse_implicit_document_start(self): + + # Parse an implicit document. + if not self.check_token(DirectiveToken, DocumentStartToken, + StreamEndToken): + self.tag_handles = self.DEFAULT_TAGS + token = self.peek_token() + start_mark = end_mark = token.start_mark + event = DocumentStartEvent(start_mark, end_mark, + explicit=False) + + # Prepare the next state. + self.states.append(self.parse_document_end) + self.state = self.parse_block_node + + return event + + else: + return self.parse_document_start() + + def parse_document_start(self): + + # Parse any extra document end indicators. + while self.check_token(DocumentEndToken): + self.get_token() + + # Parse an explicit document. + if not self.check_token(StreamEndToken): + token = self.peek_token() + start_mark = token.start_mark + version, tags = self.process_directives() + if not self.check_token(DocumentStartToken): + raise ParserError(None, None, + "expected '', but found %r" + % self.peek_token().id, + self.peek_token().start_mark) + token = self.get_token() + end_mark = token.end_mark + event = DocumentStartEvent(start_mark, end_mark, + explicit=True, version=version, tags=tags) + self.states.append(self.parse_document_end) + self.state = self.parse_document_content + else: + # Parse the end of the stream. + token = self.get_token() + event = StreamEndEvent(token.start_mark, token.end_mark) + assert not self.states + assert not self.marks + self.state = None + return event + + def parse_document_end(self): + + # Parse the document end. + token = self.peek_token() + start_mark = end_mark = token.start_mark + explicit = False + if self.check_token(DocumentEndToken): + token = self.get_token() + end_mark = token.end_mark + explicit = True + event = DocumentEndEvent(start_mark, end_mark, + explicit=explicit) + + # Prepare the next state. + self.state = self.parse_document_start + + return event + + def parse_document_content(self): + if self.check_token(DirectiveToken, + DocumentStartToken, DocumentEndToken, StreamEndToken): + event = self.process_empty_scalar(self.peek_token().start_mark) + self.state = self.states.pop() + return event + else: + return self.parse_block_node() + + def process_directives(self): + self.yaml_version = None + self.tag_handles = {} + while self.check_token(DirectiveToken): + token = self.get_token() + if token.name == 'YAML': + if self.yaml_version is not None: + raise ParserError(None, None, + "found duplicate YAML directive", token.start_mark) + major, minor = token.value + if major != 1: + raise ParserError(None, None, + "found incompatible YAML document (version 1.* is required)", + token.start_mark) + self.yaml_version = token.value + elif token.name == 'TAG': + handle, prefix = token.value + if handle in self.tag_handles: + raise ParserError(None, None, + "duplicate tag handle %r" % handle, + token.start_mark) + self.tag_handles[handle] = prefix + if self.tag_handles: + value = self.yaml_version, self.tag_handles.copy() + else: + value = self.yaml_version, None + for key in self.DEFAULT_TAGS: + if key not in self.tag_handles: + self.tag_handles[key] = self.DEFAULT_TAGS[key] + return value + + # block_node_or_indentless_sequence ::= ALIAS + # | properties (block_content | indentless_block_sequence)? + # | block_content + # | indentless_block_sequence + # block_node ::= ALIAS + # | properties block_content? + # | block_content + # flow_node ::= ALIAS + # | properties flow_content? + # | flow_content + # properties ::= TAG ANCHOR? | ANCHOR TAG? + # block_content ::= block_collection | flow_collection | SCALAR + # flow_content ::= flow_collection | SCALAR + # block_collection ::= block_sequence | block_mapping + # flow_collection ::= flow_sequence | flow_mapping + + def parse_block_node(self): + return self.parse_node(block=True) + + def parse_flow_node(self): + return self.parse_node() + + def parse_block_node_or_indentless_sequence(self): + return self.parse_node(block=True, indentless_sequence=True) + + def parse_node(self, block=False, indentless_sequence=False): + if self.check_token(AliasToken): + token = self.get_token() + event = AliasEvent(token.value, token.start_mark, token.end_mark) + self.state = self.states.pop() + else: + anchor = None + tag = None + start_mark = end_mark = tag_mark = None + if self.check_token(AnchorToken): + token = self.get_token() + start_mark = token.start_mark + end_mark = token.end_mark + anchor = token.value + if self.check_token(TagToken): + token = self.get_token() + tag_mark = token.start_mark + end_mark = token.end_mark + tag = token.value + elif self.check_token(TagToken): + token = self.get_token() + start_mark = tag_mark = token.start_mark + end_mark = token.end_mark + tag = token.value + if self.check_token(AnchorToken): + token = self.get_token() + end_mark = token.end_mark + anchor = token.value + if tag is not None: + handle, suffix = tag + if handle is not None: + if handle not in self.tag_handles: + raise ParserError("while parsing a node", start_mark, + "found undefined tag handle %r" % handle, + tag_mark) + tag = self.tag_handles[handle]+suffix + else: + tag = suffix + #if tag == '!': + # raise ParserError("while parsing a node", start_mark, + # "found non-specific tag '!'", tag_mark, + # "Please check 'http://pyyaml.org/wiki/YAMLNonSpecificTag' and share your opinion.") + if start_mark is None: + start_mark = end_mark = self.peek_token().start_mark + event = None + implicit = (tag is None or tag == '!') + if indentless_sequence and self.check_token(BlockEntryToken): + end_mark = self.peek_token().end_mark + event = SequenceStartEvent(anchor, tag, implicit, + start_mark, end_mark) + self.state = self.parse_indentless_sequence_entry + else: + if self.check_token(ScalarToken): + token = self.get_token() + end_mark = token.end_mark + if (token.plain and tag is None) or tag == '!': + implicit = (True, False) + elif tag is None: + implicit = (False, True) + else: + implicit = (False, False) + event = ScalarEvent(anchor, tag, implicit, token.value, + start_mark, end_mark, style=token.style) + self.state = self.states.pop() + elif self.check_token(FlowSequenceStartToken): + end_mark = self.peek_token().end_mark + event = SequenceStartEvent(anchor, tag, implicit, + start_mark, end_mark, flow_style=True) + self.state = self.parse_flow_sequence_first_entry + elif self.check_token(FlowMappingStartToken): + end_mark = self.peek_token().end_mark + event = MappingStartEvent(anchor, tag, implicit, + start_mark, end_mark, flow_style=True) + self.state = self.parse_flow_mapping_first_key + elif block and self.check_token(BlockSequenceStartToken): + end_mark = self.peek_token().start_mark + event = SequenceStartEvent(anchor, tag, implicit, + start_mark, end_mark, flow_style=False) + self.state = self.parse_block_sequence_first_entry + elif block and self.check_token(BlockMappingStartToken): + end_mark = self.peek_token().start_mark + event = MappingStartEvent(anchor, tag, implicit, + start_mark, end_mark, flow_style=False) + self.state = self.parse_block_mapping_first_key + elif anchor is not None or tag is not None: + # Empty scalars are allowed even if a tag or an anchor is + # specified. + event = ScalarEvent(anchor, tag, (implicit, False), '', + start_mark, end_mark) + self.state = self.states.pop() + else: + if block: + node = 'block' + else: + node = 'flow' + token = self.peek_token() + raise ParserError("while parsing a %s node" % node, start_mark, + "expected the node content, but found %r" % token.id, + token.start_mark) + return event + + # block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END + + def parse_block_sequence_first_entry(self): + token = self.get_token() + self.marks.append(token.start_mark) + return self.parse_block_sequence_entry() + + def parse_block_sequence_entry(self): + if self.check_token(BlockEntryToken): + token = self.get_token() + if not self.check_token(BlockEntryToken, BlockEndToken): + self.states.append(self.parse_block_sequence_entry) + return self.parse_block_node() + else: + self.state = self.parse_block_sequence_entry + return self.process_empty_scalar(token.end_mark) + if not self.check_token(BlockEndToken): + token = self.peek_token() + raise ParserError("while parsing a block collection", self.marks[-1], + "expected , but found %r" % token.id, token.start_mark) + token = self.get_token() + event = SequenceEndEvent(token.start_mark, token.end_mark) + self.state = self.states.pop() + self.marks.pop() + return event + + # indentless_sequence ::= (BLOCK-ENTRY block_node?)+ + + def parse_indentless_sequence_entry(self): + if self.check_token(BlockEntryToken): + token = self.get_token() + if not self.check_token(BlockEntryToken, + KeyToken, ValueToken, BlockEndToken): + self.states.append(self.parse_indentless_sequence_entry) + return self.parse_block_node() + else: + self.state = self.parse_indentless_sequence_entry + return self.process_empty_scalar(token.end_mark) + token = self.peek_token() + event = SequenceEndEvent(token.start_mark, token.start_mark) + self.state = self.states.pop() + return event + + # block_mapping ::= BLOCK-MAPPING_START + # ((KEY block_node_or_indentless_sequence?)? + # (VALUE block_node_or_indentless_sequence?)?)* + # BLOCK-END + + def parse_block_mapping_first_key(self): + token = self.get_token() + self.marks.append(token.start_mark) + return self.parse_block_mapping_key() + + def parse_block_mapping_key(self): + if self.check_token(KeyToken): + token = self.get_token() + if not self.check_token(KeyToken, ValueToken, BlockEndToken): + self.states.append(self.parse_block_mapping_value) + return self.parse_block_node_or_indentless_sequence() + else: + self.state = self.parse_block_mapping_value + return self.process_empty_scalar(token.end_mark) + if not self.check_token(BlockEndToken): + token = self.peek_token() + raise ParserError("while parsing a block mapping", self.marks[-1], + "expected , but found %r" % token.id, token.start_mark) + token = self.get_token() + event = MappingEndEvent(token.start_mark, token.end_mark) + self.state = self.states.pop() + self.marks.pop() + return event + + def parse_block_mapping_value(self): + if self.check_token(ValueToken): + token = self.get_token() + if not self.check_token(KeyToken, ValueToken, BlockEndToken): + self.states.append(self.parse_block_mapping_key) + return self.parse_block_node_or_indentless_sequence() + else: + self.state = self.parse_block_mapping_key + return self.process_empty_scalar(token.end_mark) + else: + self.state = self.parse_block_mapping_key + token = self.peek_token() + return self.process_empty_scalar(token.start_mark) + + # flow_sequence ::= FLOW-SEQUENCE-START + # (flow_sequence_entry FLOW-ENTRY)* + # flow_sequence_entry? + # FLOW-SEQUENCE-END + # flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + # + # Note that while production rules for both flow_sequence_entry and + # flow_mapping_entry are equal, their interpretations are different. + # For `flow_sequence_entry`, the part `KEY flow_node? (VALUE flow_node?)?` + # generate an inline mapping (set syntax). + + def parse_flow_sequence_first_entry(self): + token = self.get_token() + self.marks.append(token.start_mark) + return self.parse_flow_sequence_entry(first=True) + + def parse_flow_sequence_entry(self, first=False): + if not self.check_token(FlowSequenceEndToken): + if not first: + if self.check_token(FlowEntryToken): + self.get_token() + else: + token = self.peek_token() + raise ParserError("while parsing a flow sequence", self.marks[-1], + "expected ',' or ']', but got %r" % token.id, token.start_mark) + + if self.check_token(KeyToken): + token = self.peek_token() + event = MappingStartEvent(None, None, True, + token.start_mark, token.end_mark, + flow_style=True) + self.state = self.parse_flow_sequence_entry_mapping_key + return event + elif not self.check_token(FlowSequenceEndToken): + self.states.append(self.parse_flow_sequence_entry) + return self.parse_flow_node() + token = self.get_token() + event = SequenceEndEvent(token.start_mark, token.end_mark) + self.state = self.states.pop() + self.marks.pop() + return event + + def parse_flow_sequence_entry_mapping_key(self): + token = self.get_token() + if not self.check_token(ValueToken, + FlowEntryToken, FlowSequenceEndToken): + self.states.append(self.parse_flow_sequence_entry_mapping_value) + return self.parse_flow_node() + else: + self.state = self.parse_flow_sequence_entry_mapping_value + return self.process_empty_scalar(token.end_mark) + + def parse_flow_sequence_entry_mapping_value(self): + if self.check_token(ValueToken): + token = self.get_token() + if not self.check_token(FlowEntryToken, FlowSequenceEndToken): + self.states.append(self.parse_flow_sequence_entry_mapping_end) + return self.parse_flow_node() + else: + self.state = self.parse_flow_sequence_entry_mapping_end + return self.process_empty_scalar(token.end_mark) + else: + self.state = self.parse_flow_sequence_entry_mapping_end + token = self.peek_token() + return self.process_empty_scalar(token.start_mark) + + def parse_flow_sequence_entry_mapping_end(self): + self.state = self.parse_flow_sequence_entry + token = self.peek_token() + return MappingEndEvent(token.start_mark, token.start_mark) + + # flow_mapping ::= FLOW-MAPPING-START + # (flow_mapping_entry FLOW-ENTRY)* + # flow_mapping_entry? + # FLOW-MAPPING-END + # flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + + def parse_flow_mapping_first_key(self): + token = self.get_token() + self.marks.append(token.start_mark) + return self.parse_flow_mapping_key(first=True) + + def parse_flow_mapping_key(self, first=False): + if not self.check_token(FlowMappingEndToken): + if not first: + if self.check_token(FlowEntryToken): + self.get_token() + else: + token = self.peek_token() + raise ParserError("while parsing a flow mapping", self.marks[-1], + "expected ',' or '}', but got %r" % token.id, token.start_mark) + if self.check_token(KeyToken): + token = self.get_token() + if not self.check_token(ValueToken, + FlowEntryToken, FlowMappingEndToken): + self.states.append(self.parse_flow_mapping_value) + return self.parse_flow_node() + else: + self.state = self.parse_flow_mapping_value + return self.process_empty_scalar(token.end_mark) + elif not self.check_token(FlowMappingEndToken): + self.states.append(self.parse_flow_mapping_empty_value) + return self.parse_flow_node() + token = self.get_token() + event = MappingEndEvent(token.start_mark, token.end_mark) + self.state = self.states.pop() + self.marks.pop() + return event + + def parse_flow_mapping_value(self): + if self.check_token(ValueToken): + token = self.get_token() + if not self.check_token(FlowEntryToken, FlowMappingEndToken): + self.states.append(self.parse_flow_mapping_key) + return self.parse_flow_node() + else: + self.state = self.parse_flow_mapping_key + return self.process_empty_scalar(token.end_mark) + else: + self.state = self.parse_flow_mapping_key + token = self.peek_token() + return self.process_empty_scalar(token.start_mark) + + def parse_flow_mapping_empty_value(self): + self.state = self.parse_flow_mapping_key + return self.process_empty_scalar(self.peek_token().start_mark) + + def process_empty_scalar(self, mark): + return ScalarEvent(None, None, (True, False), '', mark, mark) + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/reader.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/reader.py new file mode 100644 index 0000000000000000000000000000000000000000..774b0219b5932a0ee1c27e637371de5ba8d9cb16 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/reader.py @@ -0,0 +1,185 @@ +# This module contains abstractions for the input stream. You don't have to +# looks further, there are no pretty code. +# +# We define two classes here. +# +# Mark(source, line, column) +# It's just a record and its only use is producing nice error messages. +# Parser does not use it for any other purposes. +# +# Reader(source, data) +# Reader determines the encoding of `data` and converts it to unicode. +# Reader provides the following methods and attributes: +# reader.peek(length=1) - return the next `length` characters +# reader.forward(length=1) - move the current position to `length` characters. +# reader.index - the number of the current character. +# reader.line, stream.column - the line and the column of the current character. + +__all__ = ['Reader', 'ReaderError'] + +from .error import YAMLError, Mark + +import codecs, re + +class ReaderError(YAMLError): + + def __init__(self, name, position, character, encoding, reason): + self.name = name + self.character = character + self.position = position + self.encoding = encoding + self.reason = reason + + def __str__(self): + if isinstance(self.character, bytes): + return "'%s' codec can't decode byte #x%02x: %s\n" \ + " in \"%s\", position %d" \ + % (self.encoding, ord(self.character), self.reason, + self.name, self.position) + else: + return "unacceptable character #x%04x: %s\n" \ + " in \"%s\", position %d" \ + % (self.character, self.reason, + self.name, self.position) + +class Reader(object): + # Reader: + # - determines the data encoding and converts it to a unicode string, + # - checks if characters are in allowed range, + # - adds '\0' to the end. + + # Reader accepts + # - a `bytes` object, + # - a `str` object, + # - a file-like object with its `read` method returning `str`, + # - a file-like object with its `read` method returning `unicode`. + + # Yeah, it's ugly and slow. + + def __init__(self, stream): + self.name = None + self.stream = None + self.stream_pointer = 0 + self.eof = True + self.buffer = '' + self.pointer = 0 + self.raw_buffer = None + self.raw_decode = None + self.encoding = None + self.index = 0 + self.line = 0 + self.column = 0 + if isinstance(stream, str): + self.name = "" + self.check_printable(stream) + self.buffer = stream+'\0' + elif isinstance(stream, bytes): + self.name = "" + self.raw_buffer = stream + self.determine_encoding() + else: + self.stream = stream + self.name = getattr(stream, 'name', "") + self.eof = False + self.raw_buffer = None + self.determine_encoding() + + def peek(self, index=0): + try: + return self.buffer[self.pointer+index] + except IndexError: + self.update(index+1) + return self.buffer[self.pointer+index] + + def prefix(self, length=1): + if self.pointer+length >= len(self.buffer): + self.update(length) + return self.buffer[self.pointer:self.pointer+length] + + def forward(self, length=1): + if self.pointer+length+1 >= len(self.buffer): + self.update(length+1) + while length: + ch = self.buffer[self.pointer] + self.pointer += 1 + self.index += 1 + if ch in '\n\x85\u2028\u2029' \ + or (ch == '\r' and self.buffer[self.pointer] != '\n'): + self.line += 1 + self.column = 0 + elif ch != '\uFEFF': + self.column += 1 + length -= 1 + + def get_mark(self): + if self.stream is None: + return Mark(self.name, self.index, self.line, self.column, + self.buffer, self.pointer) + else: + return Mark(self.name, self.index, self.line, self.column, + None, None) + + def determine_encoding(self): + while not self.eof and (self.raw_buffer is None or len(self.raw_buffer) < 2): + self.update_raw() + if isinstance(self.raw_buffer, bytes): + if self.raw_buffer.startswith(codecs.BOM_UTF16_LE): + self.raw_decode = codecs.utf_16_le_decode + self.encoding = 'utf-16-le' + elif self.raw_buffer.startswith(codecs.BOM_UTF16_BE): + self.raw_decode = codecs.utf_16_be_decode + self.encoding = 'utf-16-be' + else: + self.raw_decode = codecs.utf_8_decode + self.encoding = 'utf-8' + self.update(1) + + NON_PRINTABLE = re.compile('[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD\U00010000-\U0010ffff]') + def check_printable(self, data): + match = self.NON_PRINTABLE.search(data) + if match: + character = match.group() + position = self.index+(len(self.buffer)-self.pointer)+match.start() + raise ReaderError(self.name, position, ord(character), + 'unicode', "special characters are not allowed") + + def update(self, length): + if self.raw_buffer is None: + return + self.buffer = self.buffer[self.pointer:] + self.pointer = 0 + while len(self.buffer) < length: + if not self.eof: + self.update_raw() + if self.raw_decode is not None: + try: + data, converted = self.raw_decode(self.raw_buffer, + 'strict', self.eof) + except UnicodeDecodeError as exc: + character = self.raw_buffer[exc.start] + if self.stream is not None: + position = self.stream_pointer-len(self.raw_buffer)+exc.start + else: + position = exc.start + raise ReaderError(self.name, position, character, + exc.encoding, exc.reason) + else: + data = self.raw_buffer + converted = len(data) + self.check_printable(data) + self.buffer += data + self.raw_buffer = self.raw_buffer[converted:] + if self.eof: + self.buffer += '\0' + self.raw_buffer = None + break + + def update_raw(self, size=4096): + data = self.stream.read(size) + if self.raw_buffer is None: + self.raw_buffer = data + else: + self.raw_buffer += data + self.stream_pointer += len(data) + if not data: + self.eof = True diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/representer.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/representer.py new file mode 100644 index 0000000000000000000000000000000000000000..808ca06dfbd60c9a23eb079151b74a82ef688749 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/representer.py @@ -0,0 +1,389 @@ + +__all__ = ['BaseRepresenter', 'SafeRepresenter', 'Representer', + 'RepresenterError'] + +from .error import * +from .nodes import * + +import datetime, copyreg, types, base64, collections + +class RepresenterError(YAMLError): + pass + +class BaseRepresenter: + + yaml_representers = {} + yaml_multi_representers = {} + + def __init__(self, default_style=None, default_flow_style=False, sort_keys=True): + self.default_style = default_style + self.sort_keys = sort_keys + self.default_flow_style = default_flow_style + self.represented_objects = {} + self.object_keeper = [] + self.alias_key = None + + def represent(self, data): + node = self.represent_data(data) + self.serialize(node) + self.represented_objects = {} + self.object_keeper = [] + self.alias_key = None + + def represent_data(self, data): + if self.ignore_aliases(data): + self.alias_key = None + else: + self.alias_key = id(data) + if self.alias_key is not None: + if self.alias_key in self.represented_objects: + node = self.represented_objects[self.alias_key] + #if node is None: + # raise RepresenterError("recursive objects are not allowed: %r" % data) + return node + #self.represented_objects[alias_key] = None + self.object_keeper.append(data) + data_types = type(data).__mro__ + if data_types[0] in self.yaml_representers: + node = self.yaml_representers[data_types[0]](self, data) + else: + for data_type in data_types: + if data_type in self.yaml_multi_representers: + node = self.yaml_multi_representers[data_type](self, data) + break + else: + if None in self.yaml_multi_representers: + node = self.yaml_multi_representers[None](self, data) + elif None in self.yaml_representers: + node = self.yaml_representers[None](self, data) + else: + node = ScalarNode(None, str(data)) + #if alias_key is not None: + # self.represented_objects[alias_key] = node + return node + + @classmethod + def add_representer(cls, data_type, representer): + if not 'yaml_representers' in cls.__dict__: + cls.yaml_representers = cls.yaml_representers.copy() + cls.yaml_representers[data_type] = representer + + @classmethod + def add_multi_representer(cls, data_type, representer): + if not 'yaml_multi_representers' in cls.__dict__: + cls.yaml_multi_representers = cls.yaml_multi_representers.copy() + cls.yaml_multi_representers[data_type] = representer + + def represent_scalar(self, tag, value, style=None): + if style is None: + style = self.default_style + node = ScalarNode(tag, value, style=style) + if self.alias_key is not None: + self.represented_objects[self.alias_key] = node + return node + + def represent_sequence(self, tag, sequence, flow_style=None): + value = [] + node = SequenceNode(tag, value, flow_style=flow_style) + if self.alias_key is not None: + self.represented_objects[self.alias_key] = node + best_style = True + for item in sequence: + node_item = self.represent_data(item) + if not (isinstance(node_item, ScalarNode) and not node_item.style): + best_style = False + value.append(node_item) + if flow_style is None: + if self.default_flow_style is not None: + node.flow_style = self.default_flow_style + else: + node.flow_style = best_style + return node + + def represent_mapping(self, tag, mapping, flow_style=None): + value = [] + node = MappingNode(tag, value, flow_style=flow_style) + if self.alias_key is not None: + self.represented_objects[self.alias_key] = node + best_style = True + if hasattr(mapping, 'items'): + mapping = list(mapping.items()) + if self.sort_keys: + try: + mapping = sorted(mapping) + except TypeError: + pass + for item_key, item_value in mapping: + node_key = self.represent_data(item_key) + node_value = self.represent_data(item_value) + if not (isinstance(node_key, ScalarNode) and not node_key.style): + best_style = False + if not (isinstance(node_value, ScalarNode) and not node_value.style): + best_style = False + value.append((node_key, node_value)) + if flow_style is None: + if self.default_flow_style is not None: + node.flow_style = self.default_flow_style + else: + node.flow_style = best_style + return node + + def ignore_aliases(self, data): + return False + +class SafeRepresenter(BaseRepresenter): + + def ignore_aliases(self, data): + if data is None: + return True + if isinstance(data, tuple) and data == (): + return True + if isinstance(data, (str, bytes, bool, int, float)): + return True + + def represent_none(self, data): + return self.represent_scalar('tag:yaml.org,2002:null', 'null') + + def represent_str(self, data): + return self.represent_scalar('tag:yaml.org,2002:str', data) + + def represent_binary(self, data): + if hasattr(base64, 'encodebytes'): + data = base64.encodebytes(data).decode('ascii') + else: + data = base64.encodestring(data).decode('ascii') + return self.represent_scalar('tag:yaml.org,2002:binary', data, style='|') + + def represent_bool(self, data): + if data: + value = 'true' + else: + value = 'false' + return self.represent_scalar('tag:yaml.org,2002:bool', value) + + def represent_int(self, data): + return self.represent_scalar('tag:yaml.org,2002:int', str(data)) + + inf_value = 1e300 + while repr(inf_value) != repr(inf_value*inf_value): + inf_value *= inf_value + + def represent_float(self, data): + if data != data or (data == 0.0 and data == 1.0): + value = '.nan' + elif data == self.inf_value: + value = '.inf' + elif data == -self.inf_value: + value = '-.inf' + else: + value = repr(data).lower() + # Note that in some cases `repr(data)` represents a float number + # without the decimal parts. For instance: + # >>> repr(1e17) + # '1e17' + # Unfortunately, this is not a valid float representation according + # to the definition of the `!!float` tag. We fix this by adding + # '.0' before the 'e' symbol. + if '.' not in value and 'e' in value: + value = value.replace('e', '.0e', 1) + return self.represent_scalar('tag:yaml.org,2002:float', value) + + def represent_list(self, data): + #pairs = (len(data) > 0 and isinstance(data, list)) + #if pairs: + # for item in data: + # if not isinstance(item, tuple) or len(item) != 2: + # pairs = False + # break + #if not pairs: + return self.represent_sequence('tag:yaml.org,2002:seq', data) + #value = [] + #for item_key, item_value in data: + # value.append(self.represent_mapping(u'tag:yaml.org,2002:map', + # [(item_key, item_value)])) + #return SequenceNode(u'tag:yaml.org,2002:pairs', value) + + def represent_dict(self, data): + return self.represent_mapping('tag:yaml.org,2002:map', data) + + def represent_set(self, data): + value = {} + for key in data: + value[key] = None + return self.represent_mapping('tag:yaml.org,2002:set', value) + + def represent_date(self, data): + value = data.isoformat() + return self.represent_scalar('tag:yaml.org,2002:timestamp', value) + + def represent_datetime(self, data): + value = data.isoformat(' ') + return self.represent_scalar('tag:yaml.org,2002:timestamp', value) + + def represent_yaml_object(self, tag, data, cls, flow_style=None): + if hasattr(data, '__getstate__'): + state = data.__getstate__() + else: + state = data.__dict__.copy() + return self.represent_mapping(tag, state, flow_style=flow_style) + + def represent_undefined(self, data): + raise RepresenterError("cannot represent an object", data) + +SafeRepresenter.add_representer(type(None), + SafeRepresenter.represent_none) + +SafeRepresenter.add_representer(str, + SafeRepresenter.represent_str) + +SafeRepresenter.add_representer(bytes, + SafeRepresenter.represent_binary) + +SafeRepresenter.add_representer(bool, + SafeRepresenter.represent_bool) + +SafeRepresenter.add_representer(int, + SafeRepresenter.represent_int) + +SafeRepresenter.add_representer(float, + SafeRepresenter.represent_float) + +SafeRepresenter.add_representer(list, + SafeRepresenter.represent_list) + +SafeRepresenter.add_representer(tuple, + SafeRepresenter.represent_list) + +SafeRepresenter.add_representer(dict, + SafeRepresenter.represent_dict) + +SafeRepresenter.add_representer(set, + SafeRepresenter.represent_set) + +SafeRepresenter.add_representer(datetime.date, + SafeRepresenter.represent_date) + +SafeRepresenter.add_representer(datetime.datetime, + SafeRepresenter.represent_datetime) + +SafeRepresenter.add_representer(None, + SafeRepresenter.represent_undefined) + +class Representer(SafeRepresenter): + + def represent_complex(self, data): + if data.imag == 0.0: + data = '%r' % data.real + elif data.real == 0.0: + data = '%rj' % data.imag + elif data.imag > 0: + data = '%r+%rj' % (data.real, data.imag) + else: + data = '%r%rj' % (data.real, data.imag) + return self.represent_scalar('tag:yaml.org,2002:python/complex', data) + + def represent_tuple(self, data): + return self.represent_sequence('tag:yaml.org,2002:python/tuple', data) + + def represent_name(self, data): + name = '%s.%s' % (data.__module__, data.__name__) + return self.represent_scalar('tag:yaml.org,2002:python/name:'+name, '') + + def represent_module(self, data): + return self.represent_scalar( + 'tag:yaml.org,2002:python/module:'+data.__name__, '') + + def represent_object(self, data): + # We use __reduce__ API to save the data. data.__reduce__ returns + # a tuple of length 2-5: + # (function, args, state, listitems, dictitems) + + # For reconstructing, we calls function(*args), then set its state, + # listitems, and dictitems if they are not None. + + # A special case is when function.__name__ == '__newobj__'. In this + # case we create the object with args[0].__new__(*args). + + # Another special case is when __reduce__ returns a string - we don't + # support it. + + # We produce a !!python/object, !!python/object/new or + # !!python/object/apply node. + + cls = type(data) + if cls in copyreg.dispatch_table: + reduce = copyreg.dispatch_table[cls](data) + elif hasattr(data, '__reduce_ex__'): + reduce = data.__reduce_ex__(2) + elif hasattr(data, '__reduce__'): + reduce = data.__reduce__() + else: + raise RepresenterError("cannot represent an object", data) + reduce = (list(reduce)+[None]*5)[:5] + function, args, state, listitems, dictitems = reduce + args = list(args) + if state is None: + state = {} + if listitems is not None: + listitems = list(listitems) + if dictitems is not None: + dictitems = dict(dictitems) + if function.__name__ == '__newobj__': + function = args[0] + args = args[1:] + tag = 'tag:yaml.org,2002:python/object/new:' + newobj = True + else: + tag = 'tag:yaml.org,2002:python/object/apply:' + newobj = False + function_name = '%s.%s' % (function.__module__, function.__name__) + if not args and not listitems and not dictitems \ + and isinstance(state, dict) and newobj: + return self.represent_mapping( + 'tag:yaml.org,2002:python/object:'+function_name, state) + if not listitems and not dictitems \ + and isinstance(state, dict) and not state: + return self.represent_sequence(tag+function_name, args) + value = {} + if args: + value['args'] = args + if state or not isinstance(state, dict): + value['state'] = state + if listitems: + value['listitems'] = listitems + if dictitems: + value['dictitems'] = dictitems + return self.represent_mapping(tag+function_name, value) + + def represent_ordered_dict(self, data): + # Provide uniform representation across different Python versions. + data_type = type(data) + tag = 'tag:yaml.org,2002:python/object/apply:%s.%s' \ + % (data_type.__module__, data_type.__name__) + items = [[key, value] for key, value in data.items()] + return self.represent_sequence(tag, [items]) + +Representer.add_representer(complex, + Representer.represent_complex) + +Representer.add_representer(tuple, + Representer.represent_tuple) + +Representer.add_multi_representer(type, + Representer.represent_name) + +Representer.add_representer(collections.OrderedDict, + Representer.represent_ordered_dict) + +Representer.add_representer(types.FunctionType, + Representer.represent_name) + +Representer.add_representer(types.BuiltinFunctionType, + Representer.represent_name) + +Representer.add_representer(types.ModuleType, + Representer.represent_module) + +Representer.add_multi_representer(object, + Representer.represent_object) + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/resolver.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..3522bdaaf6358110b608f4e6503b9d314c82d887 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/resolver.py @@ -0,0 +1,227 @@ + +__all__ = ['BaseResolver', 'Resolver'] + +from .error import * +from .nodes import * + +import re + +class ResolverError(YAMLError): + pass + +class BaseResolver: + + DEFAULT_SCALAR_TAG = 'tag:yaml.org,2002:str' + DEFAULT_SEQUENCE_TAG = 'tag:yaml.org,2002:seq' + DEFAULT_MAPPING_TAG = 'tag:yaml.org,2002:map' + + yaml_implicit_resolvers = {} + yaml_path_resolvers = {} + + def __init__(self): + self.resolver_exact_paths = [] + self.resolver_prefix_paths = [] + + @classmethod + def add_implicit_resolver(cls, tag, regexp, first): + if not 'yaml_implicit_resolvers' in cls.__dict__: + implicit_resolvers = {} + for key in cls.yaml_implicit_resolvers: + implicit_resolvers[key] = cls.yaml_implicit_resolvers[key][:] + cls.yaml_implicit_resolvers = implicit_resolvers + if first is None: + first = [None] + for ch in first: + cls.yaml_implicit_resolvers.setdefault(ch, []).append((tag, regexp)) + + @classmethod + def add_path_resolver(cls, tag, path, kind=None): + # Note: `add_path_resolver` is experimental. The API could be changed. + # `new_path` is a pattern that is matched against the path from the + # root to the node that is being considered. `node_path` elements are + # tuples `(node_check, index_check)`. `node_check` is a node class: + # `ScalarNode`, `SequenceNode`, `MappingNode` or `None`. `None` + # matches any kind of a node. `index_check` could be `None`, a boolean + # value, a string value, or a number. `None` and `False` match against + # any _value_ of sequence and mapping nodes. `True` matches against + # any _key_ of a mapping node. A string `index_check` matches against + # a mapping value that corresponds to a scalar key which content is + # equal to the `index_check` value. An integer `index_check` matches + # against a sequence value with the index equal to `index_check`. + if not 'yaml_path_resolvers' in cls.__dict__: + cls.yaml_path_resolvers = cls.yaml_path_resolvers.copy() + new_path = [] + for element in path: + if isinstance(element, (list, tuple)): + if len(element) == 2: + node_check, index_check = element + elif len(element) == 1: + node_check = element[0] + index_check = True + else: + raise ResolverError("Invalid path element: %s" % element) + else: + node_check = None + index_check = element + if node_check is str: + node_check = ScalarNode + elif node_check is list: + node_check = SequenceNode + elif node_check is dict: + node_check = MappingNode + elif node_check not in [ScalarNode, SequenceNode, MappingNode] \ + and not isinstance(node_check, str) \ + and node_check is not None: + raise ResolverError("Invalid node checker: %s" % node_check) + if not isinstance(index_check, (str, int)) \ + and index_check is not None: + raise ResolverError("Invalid index checker: %s" % index_check) + new_path.append((node_check, index_check)) + if kind is str: + kind = ScalarNode + elif kind is list: + kind = SequenceNode + elif kind is dict: + kind = MappingNode + elif kind not in [ScalarNode, SequenceNode, MappingNode] \ + and kind is not None: + raise ResolverError("Invalid node kind: %s" % kind) + cls.yaml_path_resolvers[tuple(new_path), kind] = tag + + def descend_resolver(self, current_node, current_index): + if not self.yaml_path_resolvers: + return + exact_paths = {} + prefix_paths = [] + if current_node: + depth = len(self.resolver_prefix_paths) + for path, kind in self.resolver_prefix_paths[-1]: + if self.check_resolver_prefix(depth, path, kind, + current_node, current_index): + if len(path) > depth: + prefix_paths.append((path, kind)) + else: + exact_paths[kind] = self.yaml_path_resolvers[path, kind] + else: + for path, kind in self.yaml_path_resolvers: + if not path: + exact_paths[kind] = self.yaml_path_resolvers[path, kind] + else: + prefix_paths.append((path, kind)) + self.resolver_exact_paths.append(exact_paths) + self.resolver_prefix_paths.append(prefix_paths) + + def ascend_resolver(self): + if not self.yaml_path_resolvers: + return + self.resolver_exact_paths.pop() + self.resolver_prefix_paths.pop() + + def check_resolver_prefix(self, depth, path, kind, + current_node, current_index): + node_check, index_check = path[depth-1] + if isinstance(node_check, str): + if current_node.tag != node_check: + return + elif node_check is not None: + if not isinstance(current_node, node_check): + return + if index_check is True and current_index is not None: + return + if (index_check is False or index_check is None) \ + and current_index is None: + return + if isinstance(index_check, str): + if not (isinstance(current_index, ScalarNode) + and index_check == current_index.value): + return + elif isinstance(index_check, int) and not isinstance(index_check, bool): + if index_check != current_index: + return + return True + + def resolve(self, kind, value, implicit): + if kind is ScalarNode and implicit[0]: + if value == '': + resolvers = self.yaml_implicit_resolvers.get('', []) + else: + resolvers = self.yaml_implicit_resolvers.get(value[0], []) + wildcard_resolvers = self.yaml_implicit_resolvers.get(None, []) + for tag, regexp in resolvers + wildcard_resolvers: + if regexp.match(value): + return tag + implicit = implicit[1] + if self.yaml_path_resolvers: + exact_paths = self.resolver_exact_paths[-1] + if kind in exact_paths: + return exact_paths[kind] + if None in exact_paths: + return exact_paths[None] + if kind is ScalarNode: + return self.DEFAULT_SCALAR_TAG + elif kind is SequenceNode: + return self.DEFAULT_SEQUENCE_TAG + elif kind is MappingNode: + return self.DEFAULT_MAPPING_TAG + +class Resolver(BaseResolver): + pass + +Resolver.add_implicit_resolver( + 'tag:yaml.org,2002:bool', + re.compile(r'''^(?:yes|Yes|YES|no|No|NO + |true|True|TRUE|false|False|FALSE + |on|On|ON|off|Off|OFF)$''', re.X), + list('yYnNtTfFoO')) + +Resolver.add_implicit_resolver( + 'tag:yaml.org,2002:float', + re.compile(r'''^(?:[-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+][0-9]+)? + |\.[0-9][0-9_]*(?:[eE][-+][0-9]+)? + |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]* + |[-+]?\.(?:inf|Inf|INF) + |\.(?:nan|NaN|NAN))$''', re.X), + list('-+0123456789.')) + +Resolver.add_implicit_resolver( + 'tag:yaml.org,2002:int', + re.compile(r'''^(?:[-+]?0b[0-1_]+ + |[-+]?0[0-7_]+ + |[-+]?(?:0|[1-9][0-9_]*) + |[-+]?0x[0-9a-fA-F_]+ + |[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$''', re.X), + list('-+0123456789')) + +Resolver.add_implicit_resolver( + 'tag:yaml.org,2002:merge', + re.compile(r'^(?:<<)$'), + ['<']) + +Resolver.add_implicit_resolver( + 'tag:yaml.org,2002:null', + re.compile(r'''^(?: ~ + |null|Null|NULL + | )$''', re.X), + ['~', 'n', 'N', '']) + +Resolver.add_implicit_resolver( + 'tag:yaml.org,2002:timestamp', + re.compile(r'''^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] + |[0-9][0-9][0-9][0-9] -[0-9][0-9]? -[0-9][0-9]? + (?:[Tt]|[ \t]+)[0-9][0-9]? + :[0-9][0-9] :[0-9][0-9] (?:\.[0-9]*)? + (?:[ \t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$''', re.X), + list('0123456789')) + +Resolver.add_implicit_resolver( + 'tag:yaml.org,2002:value', + re.compile(r'^(?:=)$'), + ['=']) + +# The following resolver is only for documentation purposes. It cannot work +# because plain scalars cannot start with '!', '&', or '*'. +Resolver.add_implicit_resolver( + 'tag:yaml.org,2002:yaml', + re.compile(r'^(?:!|&|\*)$'), + list('!&*')) + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/scanner.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/scanner.py new file mode 100644 index 0000000000000000000000000000000000000000..de925b07f1eaec33c9c305a8a69f9eb7ac5983c5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/scanner.py @@ -0,0 +1,1435 @@ + +# Scanner produces tokens of the following types: +# STREAM-START +# STREAM-END +# DIRECTIVE(name, value) +# DOCUMENT-START +# DOCUMENT-END +# BLOCK-SEQUENCE-START +# BLOCK-MAPPING-START +# BLOCK-END +# FLOW-SEQUENCE-START +# FLOW-MAPPING-START +# FLOW-SEQUENCE-END +# FLOW-MAPPING-END +# BLOCK-ENTRY +# FLOW-ENTRY +# KEY +# VALUE +# ALIAS(value) +# ANCHOR(value) +# TAG(value) +# SCALAR(value, plain, style) +# +# Read comments in the Scanner code for more details. +# + +__all__ = ['Scanner', 'ScannerError'] + +from .error import MarkedYAMLError +from .tokens import * + +class ScannerError(MarkedYAMLError): + pass + +class SimpleKey: + # See below simple keys treatment. + + def __init__(self, token_number, required, index, line, column, mark): + self.token_number = token_number + self.required = required + self.index = index + self.line = line + self.column = column + self.mark = mark + +class Scanner: + + def __init__(self): + """Initialize the scanner.""" + # It is assumed that Scanner and Reader will have a common descendant. + # Reader do the dirty work of checking for BOM and converting the + # input data to Unicode. It also adds NUL to the end. + # + # Reader supports the following methods + # self.peek(i=0) # peek the next i-th character + # self.prefix(l=1) # peek the next l characters + # self.forward(l=1) # read the next l characters and move the pointer. + + # Had we reached the end of the stream? + self.done = False + + # The number of unclosed '{' and '['. `flow_level == 0` means block + # context. + self.flow_level = 0 + + # List of processed tokens that are not yet emitted. + self.tokens = [] + + # Add the STREAM-START token. + self.fetch_stream_start() + + # Number of tokens that were emitted through the `get_token` method. + self.tokens_taken = 0 + + # The current indentation level. + self.indent = -1 + + # Past indentation levels. + self.indents = [] + + # Variables related to simple keys treatment. + + # A simple key is a key that is not denoted by the '?' indicator. + # Example of simple keys: + # --- + # block simple key: value + # ? not a simple key: + # : { flow simple key: value } + # We emit the KEY token before all keys, so when we find a potential + # simple key, we try to locate the corresponding ':' indicator. + # Simple keys should be limited to a single line and 1024 characters. + + # Can a simple key start at the current position? A simple key may + # start: + # - at the beginning of the line, not counting indentation spaces + # (in block context), + # - after '{', '[', ',' (in the flow context), + # - after '?', ':', '-' (in the block context). + # In the block context, this flag also signifies if a block collection + # may start at the current position. + self.allow_simple_key = True + + # Keep track of possible simple keys. This is a dictionary. The key + # is `flow_level`; there can be no more that one possible simple key + # for each level. The value is a SimpleKey record: + # (token_number, required, index, line, column, mark) + # A simple key may start with ALIAS, ANCHOR, TAG, SCALAR(flow), + # '[', or '{' tokens. + self.possible_simple_keys = {} + + # Public methods. + + def check_token(self, *choices): + # Check if the next token is one of the given types. + while self.need_more_tokens(): + self.fetch_more_tokens() + if self.tokens: + if not choices: + return True + for choice in choices: + if isinstance(self.tokens[0], choice): + return True + return False + + def peek_token(self): + # Return the next token, but do not delete if from the queue. + # Return None if no more tokens. + while self.need_more_tokens(): + self.fetch_more_tokens() + if self.tokens: + return self.tokens[0] + else: + return None + + def get_token(self): + # Return the next token. + while self.need_more_tokens(): + self.fetch_more_tokens() + if self.tokens: + self.tokens_taken += 1 + return self.tokens.pop(0) + + # Private methods. + + def need_more_tokens(self): + if self.done: + return False + if not self.tokens: + return True + # The current token may be a potential simple key, so we + # need to look further. + self.stale_possible_simple_keys() + if self.next_possible_simple_key() == self.tokens_taken: + return True + + def fetch_more_tokens(self): + + # Eat whitespaces and comments until we reach the next token. + self.scan_to_next_token() + + # Remove obsolete possible simple keys. + self.stale_possible_simple_keys() + + # Compare the current indentation and column. It may add some tokens + # and decrease the current indentation level. + self.unwind_indent(self.column) + + # Peek the next character. + ch = self.peek() + + # Is it the end of stream? + if ch == '\0': + return self.fetch_stream_end() + + # Is it a directive? + if ch == '%' and self.check_directive(): + return self.fetch_directive() + + # Is it the document start? + if ch == '-' and self.check_document_start(): + return self.fetch_document_start() + + # Is it the document end? + if ch == '.' and self.check_document_end(): + return self.fetch_document_end() + + # TODO: support for BOM within a stream. + #if ch == '\uFEFF': + # return self.fetch_bom() <-- issue BOMToken + + # Note: the order of the following checks is NOT significant. + + # Is it the flow sequence start indicator? + if ch == '[': + return self.fetch_flow_sequence_start() + + # Is it the flow mapping start indicator? + if ch == '{': + return self.fetch_flow_mapping_start() + + # Is it the flow sequence end indicator? + if ch == ']': + return self.fetch_flow_sequence_end() + + # Is it the flow mapping end indicator? + if ch == '}': + return self.fetch_flow_mapping_end() + + # Is it the flow entry indicator? + if ch == ',': + return self.fetch_flow_entry() + + # Is it the block entry indicator? + if ch == '-' and self.check_block_entry(): + return self.fetch_block_entry() + + # Is it the key indicator? + if ch == '?' and self.check_key(): + return self.fetch_key() + + # Is it the value indicator? + if ch == ':' and self.check_value(): + return self.fetch_value() + + # Is it an alias? + if ch == '*': + return self.fetch_alias() + + # Is it an anchor? + if ch == '&': + return self.fetch_anchor() + + # Is it a tag? + if ch == '!': + return self.fetch_tag() + + # Is it a literal scalar? + if ch == '|' and not self.flow_level: + return self.fetch_literal() + + # Is it a folded scalar? + if ch == '>' and not self.flow_level: + return self.fetch_folded() + + # Is it a single quoted scalar? + if ch == '\'': + return self.fetch_single() + + # Is it a double quoted scalar? + if ch == '\"': + return self.fetch_double() + + # It must be a plain scalar then. + if self.check_plain(): + return self.fetch_plain() + + # No? It's an error. Let's produce a nice error message. + raise ScannerError("while scanning for the next token", None, + "found character %r that cannot start any token" % ch, + self.get_mark()) + + # Simple keys treatment. + + def next_possible_simple_key(self): + # Return the number of the nearest possible simple key. Actually we + # don't need to loop through the whole dictionary. We may replace it + # with the following code: + # if not self.possible_simple_keys: + # return None + # return self.possible_simple_keys[ + # min(self.possible_simple_keys.keys())].token_number + min_token_number = None + for level in self.possible_simple_keys: + key = self.possible_simple_keys[level] + if min_token_number is None or key.token_number < min_token_number: + min_token_number = key.token_number + return min_token_number + + def stale_possible_simple_keys(self): + # Remove entries that are no longer possible simple keys. According to + # the YAML specification, simple keys + # - should be limited to a single line, + # - should be no longer than 1024 characters. + # Disabling this procedure will allow simple keys of any length and + # height (may cause problems if indentation is broken though). + for level in list(self.possible_simple_keys): + key = self.possible_simple_keys[level] + if key.line != self.line \ + or self.index-key.index > 1024: + if key.required: + raise ScannerError("while scanning a simple key", key.mark, + "could not find expected ':'", self.get_mark()) + del self.possible_simple_keys[level] + + def save_possible_simple_key(self): + # The next token may start a simple key. We check if it's possible + # and save its position. This function is called for + # ALIAS, ANCHOR, TAG, SCALAR(flow), '[', and '{'. + + # Check if a simple key is required at the current position. + required = not self.flow_level and self.indent == self.column + + # The next token might be a simple key. Let's save it's number and + # position. + if self.allow_simple_key: + self.remove_possible_simple_key() + token_number = self.tokens_taken+len(self.tokens) + key = SimpleKey(token_number, required, + self.index, self.line, self.column, self.get_mark()) + self.possible_simple_keys[self.flow_level] = key + + def remove_possible_simple_key(self): + # Remove the saved possible key position at the current flow level. + if self.flow_level in self.possible_simple_keys: + key = self.possible_simple_keys[self.flow_level] + + if key.required: + raise ScannerError("while scanning a simple key", key.mark, + "could not find expected ':'", self.get_mark()) + + del self.possible_simple_keys[self.flow_level] + + # Indentation functions. + + def unwind_indent(self, column): + + ## In flow context, tokens should respect indentation. + ## Actually the condition should be `self.indent >= column` according to + ## the spec. But this condition will prohibit intuitively correct + ## constructions such as + ## key : { + ## } + #if self.flow_level and self.indent > column: + # raise ScannerError(None, None, + # "invalid indentation or unclosed '[' or '{'", + # self.get_mark()) + + # In the flow context, indentation is ignored. We make the scanner less + # restrictive then specification requires. + if self.flow_level: + return + + # In block context, we may need to issue the BLOCK-END tokens. + while self.indent > column: + mark = self.get_mark() + self.indent = self.indents.pop() + self.tokens.append(BlockEndToken(mark, mark)) + + def add_indent(self, column): + # Check if we need to increase indentation. + if self.indent < column: + self.indents.append(self.indent) + self.indent = column + return True + return False + + # Fetchers. + + def fetch_stream_start(self): + # We always add STREAM-START as the first token and STREAM-END as the + # last token. + + # Read the token. + mark = self.get_mark() + + # Add STREAM-START. + self.tokens.append(StreamStartToken(mark, mark, + encoding=self.encoding)) + + + def fetch_stream_end(self): + + # Set the current indentation to -1. + self.unwind_indent(-1) + + # Reset simple keys. + self.remove_possible_simple_key() + self.allow_simple_key = False + self.possible_simple_keys = {} + + # Read the token. + mark = self.get_mark() + + # Add STREAM-END. + self.tokens.append(StreamEndToken(mark, mark)) + + # The steam is finished. + self.done = True + + def fetch_directive(self): + + # Set the current indentation to -1. + self.unwind_indent(-1) + + # Reset simple keys. + self.remove_possible_simple_key() + self.allow_simple_key = False + + # Scan and add DIRECTIVE. + self.tokens.append(self.scan_directive()) + + def fetch_document_start(self): + self.fetch_document_indicator(DocumentStartToken) + + def fetch_document_end(self): + self.fetch_document_indicator(DocumentEndToken) + + def fetch_document_indicator(self, TokenClass): + + # Set the current indentation to -1. + self.unwind_indent(-1) + + # Reset simple keys. Note that there could not be a block collection + # after '---'. + self.remove_possible_simple_key() + self.allow_simple_key = False + + # Add DOCUMENT-START or DOCUMENT-END. + start_mark = self.get_mark() + self.forward(3) + end_mark = self.get_mark() + self.tokens.append(TokenClass(start_mark, end_mark)) + + def fetch_flow_sequence_start(self): + self.fetch_flow_collection_start(FlowSequenceStartToken) + + def fetch_flow_mapping_start(self): + self.fetch_flow_collection_start(FlowMappingStartToken) + + def fetch_flow_collection_start(self, TokenClass): + + # '[' and '{' may start a simple key. + self.save_possible_simple_key() + + # Increase the flow level. + self.flow_level += 1 + + # Simple keys are allowed after '[' and '{'. + self.allow_simple_key = True + + # Add FLOW-SEQUENCE-START or FLOW-MAPPING-START. + start_mark = self.get_mark() + self.forward() + end_mark = self.get_mark() + self.tokens.append(TokenClass(start_mark, end_mark)) + + def fetch_flow_sequence_end(self): + self.fetch_flow_collection_end(FlowSequenceEndToken) + + def fetch_flow_mapping_end(self): + self.fetch_flow_collection_end(FlowMappingEndToken) + + def fetch_flow_collection_end(self, TokenClass): + + # Reset possible simple key on the current level. + self.remove_possible_simple_key() + + # Decrease the flow level. + self.flow_level -= 1 + + # No simple keys after ']' or '}'. + self.allow_simple_key = False + + # Add FLOW-SEQUENCE-END or FLOW-MAPPING-END. + start_mark = self.get_mark() + self.forward() + end_mark = self.get_mark() + self.tokens.append(TokenClass(start_mark, end_mark)) + + def fetch_flow_entry(self): + + # Simple keys are allowed after ','. + self.allow_simple_key = True + + # Reset possible simple key on the current level. + self.remove_possible_simple_key() + + # Add FLOW-ENTRY. + start_mark = self.get_mark() + self.forward() + end_mark = self.get_mark() + self.tokens.append(FlowEntryToken(start_mark, end_mark)) + + def fetch_block_entry(self): + + # Block context needs additional checks. + if not self.flow_level: + + # Are we allowed to start a new entry? + if not self.allow_simple_key: + raise ScannerError(None, None, + "sequence entries are not allowed here", + self.get_mark()) + + # We may need to add BLOCK-SEQUENCE-START. + if self.add_indent(self.column): + mark = self.get_mark() + self.tokens.append(BlockSequenceStartToken(mark, mark)) + + # It's an error for the block entry to occur in the flow context, + # but we let the parser detect this. + else: + pass + + # Simple keys are allowed after '-'. + self.allow_simple_key = True + + # Reset possible simple key on the current level. + self.remove_possible_simple_key() + + # Add BLOCK-ENTRY. + start_mark = self.get_mark() + self.forward() + end_mark = self.get_mark() + self.tokens.append(BlockEntryToken(start_mark, end_mark)) + + def fetch_key(self): + + # Block context needs additional checks. + if not self.flow_level: + + # Are we allowed to start a key (not necessary a simple)? + if not self.allow_simple_key: + raise ScannerError(None, None, + "mapping keys are not allowed here", + self.get_mark()) + + # We may need to add BLOCK-MAPPING-START. + if self.add_indent(self.column): + mark = self.get_mark() + self.tokens.append(BlockMappingStartToken(mark, mark)) + + # Simple keys are allowed after '?' in the block context. + self.allow_simple_key = not self.flow_level + + # Reset possible simple key on the current level. + self.remove_possible_simple_key() + + # Add KEY. + start_mark = self.get_mark() + self.forward() + end_mark = self.get_mark() + self.tokens.append(KeyToken(start_mark, end_mark)) + + def fetch_value(self): + + # Do we determine a simple key? + if self.flow_level in self.possible_simple_keys: + + # Add KEY. + key = self.possible_simple_keys[self.flow_level] + del self.possible_simple_keys[self.flow_level] + self.tokens.insert(key.token_number-self.tokens_taken, + KeyToken(key.mark, key.mark)) + + # If this key starts a new block mapping, we need to add + # BLOCK-MAPPING-START. + if not self.flow_level: + if self.add_indent(key.column): + self.tokens.insert(key.token_number-self.tokens_taken, + BlockMappingStartToken(key.mark, key.mark)) + + # There cannot be two simple keys one after another. + self.allow_simple_key = False + + # It must be a part of a complex key. + else: + + # Block context needs additional checks. + # (Do we really need them? They will be caught by the parser + # anyway.) + if not self.flow_level: + + # We are allowed to start a complex value if and only if + # we can start a simple key. + if not self.allow_simple_key: + raise ScannerError(None, None, + "mapping values are not allowed here", + self.get_mark()) + + # If this value starts a new block mapping, we need to add + # BLOCK-MAPPING-START. It will be detected as an error later by + # the parser. + if not self.flow_level: + if self.add_indent(self.column): + mark = self.get_mark() + self.tokens.append(BlockMappingStartToken(mark, mark)) + + # Simple keys are allowed after ':' in the block context. + self.allow_simple_key = not self.flow_level + + # Reset possible simple key on the current level. + self.remove_possible_simple_key() + + # Add VALUE. + start_mark = self.get_mark() + self.forward() + end_mark = self.get_mark() + self.tokens.append(ValueToken(start_mark, end_mark)) + + def fetch_alias(self): + + # ALIAS could be a simple key. + self.save_possible_simple_key() + + # No simple keys after ALIAS. + self.allow_simple_key = False + + # Scan and add ALIAS. + self.tokens.append(self.scan_anchor(AliasToken)) + + def fetch_anchor(self): + + # ANCHOR could start a simple key. + self.save_possible_simple_key() + + # No simple keys after ANCHOR. + self.allow_simple_key = False + + # Scan and add ANCHOR. + self.tokens.append(self.scan_anchor(AnchorToken)) + + def fetch_tag(self): + + # TAG could start a simple key. + self.save_possible_simple_key() + + # No simple keys after TAG. + self.allow_simple_key = False + + # Scan and add TAG. + self.tokens.append(self.scan_tag()) + + def fetch_literal(self): + self.fetch_block_scalar(style='|') + + def fetch_folded(self): + self.fetch_block_scalar(style='>') + + def fetch_block_scalar(self, style): + + # A simple key may follow a block scalar. + self.allow_simple_key = True + + # Reset possible simple key on the current level. + self.remove_possible_simple_key() + + # Scan and add SCALAR. + self.tokens.append(self.scan_block_scalar(style)) + + def fetch_single(self): + self.fetch_flow_scalar(style='\'') + + def fetch_double(self): + self.fetch_flow_scalar(style='"') + + def fetch_flow_scalar(self, style): + + # A flow scalar could be a simple key. + self.save_possible_simple_key() + + # No simple keys after flow scalars. + self.allow_simple_key = False + + # Scan and add SCALAR. + self.tokens.append(self.scan_flow_scalar(style)) + + def fetch_plain(self): + + # A plain scalar could be a simple key. + self.save_possible_simple_key() + + # No simple keys after plain scalars. But note that `scan_plain` will + # change this flag if the scan is finished at the beginning of the + # line. + self.allow_simple_key = False + + # Scan and add SCALAR. May change `allow_simple_key`. + self.tokens.append(self.scan_plain()) + + # Checkers. + + def check_directive(self): + + # DIRECTIVE: ^ '%' ... + # The '%' indicator is already checked. + if self.column == 0: + return True + + def check_document_start(self): + + # DOCUMENT-START: ^ '---' (' '|'\n') + if self.column == 0: + if self.prefix(3) == '---' \ + and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': + return True + + def check_document_end(self): + + # DOCUMENT-END: ^ '...' (' '|'\n') + if self.column == 0: + if self.prefix(3) == '...' \ + and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': + return True + + def check_block_entry(self): + + # BLOCK-ENTRY: '-' (' '|'\n') + return self.peek(1) in '\0 \t\r\n\x85\u2028\u2029' + + def check_key(self): + + # KEY(flow context): '?' + if self.flow_level: + return True + + # KEY(block context): '?' (' '|'\n') + else: + return self.peek(1) in '\0 \t\r\n\x85\u2028\u2029' + + def check_value(self): + + # VALUE(flow context): ':' + if self.flow_level: + return True + + # VALUE(block context): ':' (' '|'\n') + else: + return self.peek(1) in '\0 \t\r\n\x85\u2028\u2029' + + def check_plain(self): + + # A plain scalar may start with any non-space character except: + # '-', '?', ':', ',', '[', ']', '{', '}', + # '#', '&', '*', '!', '|', '>', '\'', '\"', + # '%', '@', '`'. + # + # It may also start with + # '-', '?', ':' + # if it is followed by a non-space character. + # + # Note that we limit the last rule to the block context (except the + # '-' character) because we want the flow context to be space + # independent. + ch = self.peek() + return ch not in '\0 \t\r\n\x85\u2028\u2029-?:,[]{}#&*!|>\'\"%@`' \ + or (self.peek(1) not in '\0 \t\r\n\x85\u2028\u2029' + and (ch == '-' or (not self.flow_level and ch in '?:'))) + + # Scanners. + + def scan_to_next_token(self): + # We ignore spaces, line breaks and comments. + # If we find a line break in the block context, we set the flag + # `allow_simple_key` on. + # The byte order mark is stripped if it's the first character in the + # stream. We do not yet support BOM inside the stream as the + # specification requires. Any such mark will be considered as a part + # of the document. + # + # TODO: We need to make tab handling rules more sane. A good rule is + # Tabs cannot precede tokens + # BLOCK-SEQUENCE-START, BLOCK-MAPPING-START, BLOCK-END, + # KEY(block), VALUE(block), BLOCK-ENTRY + # So the checking code is + # if : + # self.allow_simple_keys = False + # We also need to add the check for `allow_simple_keys == True` to + # `unwind_indent` before issuing BLOCK-END. + # Scanners for block, flow, and plain scalars need to be modified. + + if self.index == 0 and self.peek() == '\uFEFF': + self.forward() + found = False + while not found: + while self.peek() == ' ': + self.forward() + if self.peek() == '#': + while self.peek() not in '\0\r\n\x85\u2028\u2029': + self.forward() + if self.scan_line_break(): + if not self.flow_level: + self.allow_simple_key = True + else: + found = True + + def scan_directive(self): + # See the specification for details. + start_mark = self.get_mark() + self.forward() + name = self.scan_directive_name(start_mark) + value = None + if name == 'YAML': + value = self.scan_yaml_directive_value(start_mark) + end_mark = self.get_mark() + elif name == 'TAG': + value = self.scan_tag_directive_value(start_mark) + end_mark = self.get_mark() + else: + end_mark = self.get_mark() + while self.peek() not in '\0\r\n\x85\u2028\u2029': + self.forward() + self.scan_directive_ignored_line(start_mark) + return DirectiveToken(name, value, start_mark, end_mark) + + def scan_directive_name(self, start_mark): + # See the specification for details. + length = 0 + ch = self.peek(length) + while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-_': + length += 1 + ch = self.peek(length) + if not length: + raise ScannerError("while scanning a directive", start_mark, + "expected alphabetic or numeric character, but found %r" + % ch, self.get_mark()) + value = self.prefix(length) + self.forward(length) + ch = self.peek() + if ch not in '\0 \r\n\x85\u2028\u2029': + raise ScannerError("while scanning a directive", start_mark, + "expected alphabetic or numeric character, but found %r" + % ch, self.get_mark()) + return value + + def scan_yaml_directive_value(self, start_mark): + # See the specification for details. + while self.peek() == ' ': + self.forward() + major = self.scan_yaml_directive_number(start_mark) + if self.peek() != '.': + raise ScannerError("while scanning a directive", start_mark, + "expected a digit or '.', but found %r" % self.peek(), + self.get_mark()) + self.forward() + minor = self.scan_yaml_directive_number(start_mark) + if self.peek() not in '\0 \r\n\x85\u2028\u2029': + raise ScannerError("while scanning a directive", start_mark, + "expected a digit or ' ', but found %r" % self.peek(), + self.get_mark()) + return (major, minor) + + def scan_yaml_directive_number(self, start_mark): + # See the specification for details. + ch = self.peek() + if not ('0' <= ch <= '9'): + raise ScannerError("while scanning a directive", start_mark, + "expected a digit, but found %r" % ch, self.get_mark()) + length = 0 + while '0' <= self.peek(length) <= '9': + length += 1 + value = int(self.prefix(length)) + self.forward(length) + return value + + def scan_tag_directive_value(self, start_mark): + # See the specification for details. + while self.peek() == ' ': + self.forward() + handle = self.scan_tag_directive_handle(start_mark) + while self.peek() == ' ': + self.forward() + prefix = self.scan_tag_directive_prefix(start_mark) + return (handle, prefix) + + def scan_tag_directive_handle(self, start_mark): + # See the specification for details. + value = self.scan_tag_handle('directive', start_mark) + ch = self.peek() + if ch != ' ': + raise ScannerError("while scanning a directive", start_mark, + "expected ' ', but found %r" % ch, self.get_mark()) + return value + + def scan_tag_directive_prefix(self, start_mark): + # See the specification for details. + value = self.scan_tag_uri('directive', start_mark) + ch = self.peek() + if ch not in '\0 \r\n\x85\u2028\u2029': + raise ScannerError("while scanning a directive", start_mark, + "expected ' ', but found %r" % ch, self.get_mark()) + return value + + def scan_directive_ignored_line(self, start_mark): + # See the specification for details. + while self.peek() == ' ': + self.forward() + if self.peek() == '#': + while self.peek() not in '\0\r\n\x85\u2028\u2029': + self.forward() + ch = self.peek() + if ch not in '\0\r\n\x85\u2028\u2029': + raise ScannerError("while scanning a directive", start_mark, + "expected a comment or a line break, but found %r" + % ch, self.get_mark()) + self.scan_line_break() + + def scan_anchor(self, TokenClass): + # The specification does not restrict characters for anchors and + # aliases. This may lead to problems, for instance, the document: + # [ *alias, value ] + # can be interpreted in two ways, as + # [ "value" ] + # and + # [ *alias , "value" ] + # Therefore we restrict aliases to numbers and ASCII letters. + start_mark = self.get_mark() + indicator = self.peek() + if indicator == '*': + name = 'alias' + else: + name = 'anchor' + self.forward() + length = 0 + ch = self.peek(length) + while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-_': + length += 1 + ch = self.peek(length) + if not length: + raise ScannerError("while scanning an %s" % name, start_mark, + "expected alphabetic or numeric character, but found %r" + % ch, self.get_mark()) + value = self.prefix(length) + self.forward(length) + ch = self.peek() + if ch not in '\0 \t\r\n\x85\u2028\u2029?:,]}%@`': + raise ScannerError("while scanning an %s" % name, start_mark, + "expected alphabetic or numeric character, but found %r" + % ch, self.get_mark()) + end_mark = self.get_mark() + return TokenClass(value, start_mark, end_mark) + + def scan_tag(self): + # See the specification for details. + start_mark = self.get_mark() + ch = self.peek(1) + if ch == '<': + handle = None + self.forward(2) + suffix = self.scan_tag_uri('tag', start_mark) + if self.peek() != '>': + raise ScannerError("while parsing a tag", start_mark, + "expected '>', but found %r" % self.peek(), + self.get_mark()) + self.forward() + elif ch in '\0 \t\r\n\x85\u2028\u2029': + handle = None + suffix = '!' + self.forward() + else: + length = 1 + use_handle = False + while ch not in '\0 \r\n\x85\u2028\u2029': + if ch == '!': + use_handle = True + break + length += 1 + ch = self.peek(length) + handle = '!' + if use_handle: + handle = self.scan_tag_handle('tag', start_mark) + else: + handle = '!' + self.forward() + suffix = self.scan_tag_uri('tag', start_mark) + ch = self.peek() + if ch not in '\0 \r\n\x85\u2028\u2029': + raise ScannerError("while scanning a tag", start_mark, + "expected ' ', but found %r" % ch, self.get_mark()) + value = (handle, suffix) + end_mark = self.get_mark() + return TagToken(value, start_mark, end_mark) + + def scan_block_scalar(self, style): + # See the specification for details. + + if style == '>': + folded = True + else: + folded = False + + chunks = [] + start_mark = self.get_mark() + + # Scan the header. + self.forward() + chomping, increment = self.scan_block_scalar_indicators(start_mark) + self.scan_block_scalar_ignored_line(start_mark) + + # Determine the indentation level and go to the first non-empty line. + min_indent = self.indent+1 + if min_indent < 1: + min_indent = 1 + if increment is None: + breaks, max_indent, end_mark = self.scan_block_scalar_indentation() + indent = max(min_indent, max_indent) + else: + indent = min_indent+increment-1 + breaks, end_mark = self.scan_block_scalar_breaks(indent) + line_break = '' + + # Scan the inner part of the block scalar. + while self.column == indent and self.peek() != '\0': + chunks.extend(breaks) + leading_non_space = self.peek() not in ' \t' + length = 0 + while self.peek(length) not in '\0\r\n\x85\u2028\u2029': + length += 1 + chunks.append(self.prefix(length)) + self.forward(length) + line_break = self.scan_line_break() + breaks, end_mark = self.scan_block_scalar_breaks(indent) + if self.column == indent and self.peek() != '\0': + + # Unfortunately, folding rules are ambiguous. + # + # This is the folding according to the specification: + + if folded and line_break == '\n' \ + and leading_non_space and self.peek() not in ' \t': + if not breaks: + chunks.append(' ') + else: + chunks.append(line_break) + + # This is Clark Evans's interpretation (also in the spec + # examples): + # + #if folded and line_break == '\n': + # if not breaks: + # if self.peek() not in ' \t': + # chunks.append(' ') + # else: + # chunks.append(line_break) + #else: + # chunks.append(line_break) + else: + break + + # Chomp the tail. + if chomping is not False: + chunks.append(line_break) + if chomping is True: + chunks.extend(breaks) + + # We are done. + return ScalarToken(''.join(chunks), False, start_mark, end_mark, + style) + + def scan_block_scalar_indicators(self, start_mark): + # See the specification for details. + chomping = None + increment = None + ch = self.peek() + if ch in '+-': + if ch == '+': + chomping = True + else: + chomping = False + self.forward() + ch = self.peek() + if ch in '0123456789': + increment = int(ch) + if increment == 0: + raise ScannerError("while scanning a block scalar", start_mark, + "expected indentation indicator in the range 1-9, but found 0", + self.get_mark()) + self.forward() + elif ch in '0123456789': + increment = int(ch) + if increment == 0: + raise ScannerError("while scanning a block scalar", start_mark, + "expected indentation indicator in the range 1-9, but found 0", + self.get_mark()) + self.forward() + ch = self.peek() + if ch in '+-': + if ch == '+': + chomping = True + else: + chomping = False + self.forward() + ch = self.peek() + if ch not in '\0 \r\n\x85\u2028\u2029': + raise ScannerError("while scanning a block scalar", start_mark, + "expected chomping or indentation indicators, but found %r" + % ch, self.get_mark()) + return chomping, increment + + def scan_block_scalar_ignored_line(self, start_mark): + # See the specification for details. + while self.peek() == ' ': + self.forward() + if self.peek() == '#': + while self.peek() not in '\0\r\n\x85\u2028\u2029': + self.forward() + ch = self.peek() + if ch not in '\0\r\n\x85\u2028\u2029': + raise ScannerError("while scanning a block scalar", start_mark, + "expected a comment or a line break, but found %r" % ch, + self.get_mark()) + self.scan_line_break() + + def scan_block_scalar_indentation(self): + # See the specification for details. + chunks = [] + max_indent = 0 + end_mark = self.get_mark() + while self.peek() in ' \r\n\x85\u2028\u2029': + if self.peek() != ' ': + chunks.append(self.scan_line_break()) + end_mark = self.get_mark() + else: + self.forward() + if self.column > max_indent: + max_indent = self.column + return chunks, max_indent, end_mark + + def scan_block_scalar_breaks(self, indent): + # See the specification for details. + chunks = [] + end_mark = self.get_mark() + while self.column < indent and self.peek() == ' ': + self.forward() + while self.peek() in '\r\n\x85\u2028\u2029': + chunks.append(self.scan_line_break()) + end_mark = self.get_mark() + while self.column < indent and self.peek() == ' ': + self.forward() + return chunks, end_mark + + def scan_flow_scalar(self, style): + # See the specification for details. + # Note that we loose indentation rules for quoted scalars. Quoted + # scalars don't need to adhere indentation because " and ' clearly + # mark the beginning and the end of them. Therefore we are less + # restrictive then the specification requires. We only need to check + # that document separators are not included in scalars. + if style == '"': + double = True + else: + double = False + chunks = [] + start_mark = self.get_mark() + quote = self.peek() + self.forward() + chunks.extend(self.scan_flow_scalar_non_spaces(double, start_mark)) + while self.peek() != quote: + chunks.extend(self.scan_flow_scalar_spaces(double, start_mark)) + chunks.extend(self.scan_flow_scalar_non_spaces(double, start_mark)) + self.forward() + end_mark = self.get_mark() + return ScalarToken(''.join(chunks), False, start_mark, end_mark, + style) + + ESCAPE_REPLACEMENTS = { + '0': '\0', + 'a': '\x07', + 'b': '\x08', + 't': '\x09', + '\t': '\x09', + 'n': '\x0A', + 'v': '\x0B', + 'f': '\x0C', + 'r': '\x0D', + 'e': '\x1B', + ' ': '\x20', + '\"': '\"', + '\\': '\\', + '/': '/', + 'N': '\x85', + '_': '\xA0', + 'L': '\u2028', + 'P': '\u2029', + } + + ESCAPE_CODES = { + 'x': 2, + 'u': 4, + 'U': 8, + } + + def scan_flow_scalar_non_spaces(self, double, start_mark): + # See the specification for details. + chunks = [] + while True: + length = 0 + while self.peek(length) not in '\'\"\\\0 \t\r\n\x85\u2028\u2029': + length += 1 + if length: + chunks.append(self.prefix(length)) + self.forward(length) + ch = self.peek() + if not double and ch == '\'' and self.peek(1) == '\'': + chunks.append('\'') + self.forward(2) + elif (double and ch == '\'') or (not double and ch in '\"\\'): + chunks.append(ch) + self.forward() + elif double and ch == '\\': + self.forward() + ch = self.peek() + if ch in self.ESCAPE_REPLACEMENTS: + chunks.append(self.ESCAPE_REPLACEMENTS[ch]) + self.forward() + elif ch in self.ESCAPE_CODES: + length = self.ESCAPE_CODES[ch] + self.forward() + for k in range(length): + if self.peek(k) not in '0123456789ABCDEFabcdef': + raise ScannerError("while scanning a double-quoted scalar", start_mark, + "expected escape sequence of %d hexadecimal numbers, but found %r" % + (length, self.peek(k)), self.get_mark()) + code = int(self.prefix(length), 16) + chunks.append(chr(code)) + self.forward(length) + elif ch in '\r\n\x85\u2028\u2029': + self.scan_line_break() + chunks.extend(self.scan_flow_scalar_breaks(double, start_mark)) + else: + raise ScannerError("while scanning a double-quoted scalar", start_mark, + "found unknown escape character %r" % ch, self.get_mark()) + else: + return chunks + + def scan_flow_scalar_spaces(self, double, start_mark): + # See the specification for details. + chunks = [] + length = 0 + while self.peek(length) in ' \t': + length += 1 + whitespaces = self.prefix(length) + self.forward(length) + ch = self.peek() + if ch == '\0': + raise ScannerError("while scanning a quoted scalar", start_mark, + "found unexpected end of stream", self.get_mark()) + elif ch in '\r\n\x85\u2028\u2029': + line_break = self.scan_line_break() + breaks = self.scan_flow_scalar_breaks(double, start_mark) + if line_break != '\n': + chunks.append(line_break) + elif not breaks: + chunks.append(' ') + chunks.extend(breaks) + else: + chunks.append(whitespaces) + return chunks + + def scan_flow_scalar_breaks(self, double, start_mark): + # See the specification for details. + chunks = [] + while True: + # Instead of checking indentation, we check for document + # separators. + prefix = self.prefix(3) + if (prefix == '---' or prefix == '...') \ + and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': + raise ScannerError("while scanning a quoted scalar", start_mark, + "found unexpected document separator", self.get_mark()) + while self.peek() in ' \t': + self.forward() + if self.peek() in '\r\n\x85\u2028\u2029': + chunks.append(self.scan_line_break()) + else: + return chunks + + def scan_plain(self): + # See the specification for details. + # We add an additional restriction for the flow context: + # plain scalars in the flow context cannot contain ',' or '?'. + # We also keep track of the `allow_simple_key` flag here. + # Indentation rules are loosed for the flow context. + chunks = [] + start_mark = self.get_mark() + end_mark = start_mark + indent = self.indent+1 + # We allow zero indentation for scalars, but then we need to check for + # document separators at the beginning of the line. + #if indent == 0: + # indent = 1 + spaces = [] + while True: + length = 0 + if self.peek() == '#': + break + while True: + ch = self.peek(length) + if ch in '\0 \t\r\n\x85\u2028\u2029' \ + or (ch == ':' and + self.peek(length+1) in '\0 \t\r\n\x85\u2028\u2029' + + (u',[]{}' if self.flow_level else u''))\ + or (self.flow_level and ch in ',?[]{}'): + break + length += 1 + if length == 0: + break + self.allow_simple_key = False + chunks.extend(spaces) + chunks.append(self.prefix(length)) + self.forward(length) + end_mark = self.get_mark() + spaces = self.scan_plain_spaces(indent, start_mark) + if not spaces or self.peek() == '#' \ + or (not self.flow_level and self.column < indent): + break + return ScalarToken(''.join(chunks), True, start_mark, end_mark) + + def scan_plain_spaces(self, indent, start_mark): + # See the specification for details. + # The specification is really confusing about tabs in plain scalars. + # We just forbid them completely. Do not use tabs in YAML! + chunks = [] + length = 0 + while self.peek(length) in ' ': + length += 1 + whitespaces = self.prefix(length) + self.forward(length) + ch = self.peek() + if ch in '\r\n\x85\u2028\u2029': + line_break = self.scan_line_break() + self.allow_simple_key = True + prefix = self.prefix(3) + if (prefix == '---' or prefix == '...') \ + and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': + return + breaks = [] + while self.peek() in ' \r\n\x85\u2028\u2029': + if self.peek() == ' ': + self.forward() + else: + breaks.append(self.scan_line_break()) + prefix = self.prefix(3) + if (prefix == '---' or prefix == '...') \ + and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': + return + if line_break != '\n': + chunks.append(line_break) + elif not breaks: + chunks.append(' ') + chunks.extend(breaks) + elif whitespaces: + chunks.append(whitespaces) + return chunks + + def scan_tag_handle(self, name, start_mark): + # See the specification for details. + # For some strange reasons, the specification does not allow '_' in + # tag handles. I have allowed it anyway. + ch = self.peek() + if ch != '!': + raise ScannerError("while scanning a %s" % name, start_mark, + "expected '!', but found %r" % ch, self.get_mark()) + length = 1 + ch = self.peek(length) + if ch != ' ': + while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-_': + length += 1 + ch = self.peek(length) + if ch != '!': + self.forward(length) + raise ScannerError("while scanning a %s" % name, start_mark, + "expected '!', but found %r" % ch, self.get_mark()) + length += 1 + value = self.prefix(length) + self.forward(length) + return value + + def scan_tag_uri(self, name, start_mark): + # See the specification for details. + # Note: we do not check if URI is well-formed. + chunks = [] + length = 0 + ch = self.peek(length) + while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-;/?:@&=+$,_.!~*\'()[]%': + if ch == '%': + chunks.append(self.prefix(length)) + self.forward(length) + length = 0 + chunks.append(self.scan_uri_escapes(name, start_mark)) + else: + length += 1 + ch = self.peek(length) + if length: + chunks.append(self.prefix(length)) + self.forward(length) + length = 0 + if not chunks: + raise ScannerError("while parsing a %s" % name, start_mark, + "expected URI, but found %r" % ch, self.get_mark()) + return ''.join(chunks) + + def scan_uri_escapes(self, name, start_mark): + # See the specification for details. + codes = [] + mark = self.get_mark() + while self.peek() == '%': + self.forward() + for k in range(2): + if self.peek(k) not in '0123456789ABCDEFabcdef': + raise ScannerError("while scanning a %s" % name, start_mark, + "expected URI escape sequence of 2 hexadecimal numbers, but found %r" + % self.peek(k), self.get_mark()) + codes.append(int(self.prefix(2), 16)) + self.forward(2) + try: + value = bytes(codes).decode('utf-8') + except UnicodeDecodeError as exc: + raise ScannerError("while scanning a %s" % name, start_mark, str(exc), mark) + return value + + def scan_line_break(self): + # Transforms: + # '\r\n' : '\n' + # '\r' : '\n' + # '\n' : '\n' + # '\x85' : '\n' + # '\u2028' : '\u2028' + # '\u2029 : '\u2029' + # default : '' + ch = self.peek() + if ch in '\r\n\x85': + if self.prefix(2) == '\r\n': + self.forward(2) + else: + self.forward() + return '\n' + elif ch in '\u2028\u2029': + self.forward() + return ch + return '' diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/serializer.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..fe911e67ae7a739abb491fbbc6834b9c37bbda4b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/serializer.py @@ -0,0 +1,111 @@ + +__all__ = ['Serializer', 'SerializerError'] + +from .error import YAMLError +from .events import * +from .nodes import * + +class SerializerError(YAMLError): + pass + +class Serializer: + + ANCHOR_TEMPLATE = 'id%03d' + + def __init__(self, encoding=None, + explicit_start=None, explicit_end=None, version=None, tags=None): + self.use_encoding = encoding + self.use_explicit_start = explicit_start + self.use_explicit_end = explicit_end + self.use_version = version + self.use_tags = tags + self.serialized_nodes = {} + self.anchors = {} + self.last_anchor_id = 0 + self.closed = None + + def open(self): + if self.closed is None: + self.emit(StreamStartEvent(encoding=self.use_encoding)) + self.closed = False + elif self.closed: + raise SerializerError("serializer is closed") + else: + raise SerializerError("serializer is already opened") + + def close(self): + if self.closed is None: + raise SerializerError("serializer is not opened") + elif not self.closed: + self.emit(StreamEndEvent()) + self.closed = True + + #def __del__(self): + # self.close() + + def serialize(self, node): + if self.closed is None: + raise SerializerError("serializer is not opened") + elif self.closed: + raise SerializerError("serializer is closed") + self.emit(DocumentStartEvent(explicit=self.use_explicit_start, + version=self.use_version, tags=self.use_tags)) + self.anchor_node(node) + self.serialize_node(node, None, None) + self.emit(DocumentEndEvent(explicit=self.use_explicit_end)) + self.serialized_nodes = {} + self.anchors = {} + self.last_anchor_id = 0 + + def anchor_node(self, node): + if node in self.anchors: + if self.anchors[node] is None: + self.anchors[node] = self.generate_anchor(node) + else: + self.anchors[node] = None + if isinstance(node, SequenceNode): + for item in node.value: + self.anchor_node(item) + elif isinstance(node, MappingNode): + for key, value in node.value: + self.anchor_node(key) + self.anchor_node(value) + + def generate_anchor(self, node): + self.last_anchor_id += 1 + return self.ANCHOR_TEMPLATE % self.last_anchor_id + + def serialize_node(self, node, parent, index): + alias = self.anchors[node] + if node in self.serialized_nodes: + self.emit(AliasEvent(alias)) + else: + self.serialized_nodes[node] = True + self.descend_resolver(parent, index) + if isinstance(node, ScalarNode): + detected_tag = self.resolve(ScalarNode, node.value, (True, False)) + default_tag = self.resolve(ScalarNode, node.value, (False, True)) + implicit = (node.tag == detected_tag), (node.tag == default_tag) + self.emit(ScalarEvent(alias, node.tag, implicit, node.value, + style=node.style)) + elif isinstance(node, SequenceNode): + implicit = (node.tag + == self.resolve(SequenceNode, node.value, True)) + self.emit(SequenceStartEvent(alias, node.tag, implicit, + flow_style=node.flow_style)) + index = 0 + for item in node.value: + self.serialize_node(item, node, index) + index += 1 + self.emit(SequenceEndEvent()) + elif isinstance(node, MappingNode): + implicit = (node.tag + == self.resolve(MappingNode, node.value, True)) + self.emit(MappingStartEvent(alias, node.tag, implicit, + flow_style=node.flow_style)) + for key, value in node.value: + self.serialize_node(key, node, None) + self.serialize_node(value, node, key) + self.emit(MappingEndEvent()) + self.ascend_resolver() + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/tokens.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/tokens.py new file mode 100644 index 0000000000000000000000000000000000000000..4d0b48a394ac8c019b401516a12f688df361cf90 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yaml/tokens.py @@ -0,0 +1,104 @@ + +class Token(object): + def __init__(self, start_mark, end_mark): + self.start_mark = start_mark + self.end_mark = end_mark + def __repr__(self): + attributes = [key for key in self.__dict__ + if not key.endswith('_mark')] + attributes.sort() + arguments = ', '.join(['%s=%r' % (key, getattr(self, key)) + for key in attributes]) + return '%s(%s)' % (self.__class__.__name__, arguments) + +#class BOMToken(Token): +# id = '' + +class DirectiveToken(Token): + id = '' + def __init__(self, name, value, start_mark, end_mark): + self.name = name + self.value = value + self.start_mark = start_mark + self.end_mark = end_mark + +class DocumentStartToken(Token): + id = '' + +class DocumentEndToken(Token): + id = '' + +class StreamStartToken(Token): + id = '' + def __init__(self, start_mark=None, end_mark=None, + encoding=None): + self.start_mark = start_mark + self.end_mark = end_mark + self.encoding = encoding + +class StreamEndToken(Token): + id = '' + +class BlockSequenceStartToken(Token): + id = '' + +class BlockMappingStartToken(Token): + id = '' + +class BlockEndToken(Token): + id = '' + +class FlowSequenceStartToken(Token): + id = '[' + +class FlowMappingStartToken(Token): + id = '{' + +class FlowSequenceEndToken(Token): + id = ']' + +class FlowMappingEndToken(Token): + id = '}' + +class KeyToken(Token): + id = '?' + +class ValueToken(Token): + id = ':' + +class BlockEntryToken(Token): + id = '-' + +class FlowEntryToken(Token): + id = ',' + +class AliasToken(Token): + id = '' + def __init__(self, value, start_mark, end_mark): + self.value = value + self.start_mark = start_mark + self.end_mark = end_mark + +class AnchorToken(Token): + id = '' + def __init__(self, value, start_mark, end_mark): + self.value = value + self.start_mark = start_mark + self.end_mark = end_mark + +class TagToken(Token): + id = '' + def __init__(self, value, start_mark, end_mark): + self.value = value + self.start_mark = start_mark + self.end_mark = end_mark + +class ScalarToken(Token): + id = '' + def __init__(self, value, plain, start_mark, end_mark, style=None): + self.value = value + self.plain = plain + self.start_mark = start_mark + self.end_mark = end_mark + self.style = style + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl-1.23.0.dist-info/INSTALLER b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl-1.23.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl-1.23.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl-1.23.0.dist-info/METADATA b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl-1.23.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..3e651131a098d7c3a644aa56a5700a6e5404c70e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl-1.23.0.dist-info/METADATA @@ -0,0 +1,2609 @@ +Metadata-Version: 2.4 +Name: yarl +Version: 1.23.0 +Summary: Yet another URL library +Home-page: https://github.com/aio-libs/yarl +Author: Andrew Svetlov +Author-email: andrew.svetlov@gmail.com +Maintainer: aiohttp team +Maintainer-email: team@aiohttp.org +License: Apache-2.0 +Project-URL: Chat: Matrix, https://matrix.to/#/#aio-libs:matrix.org +Project-URL: Chat: Matrix Space, https://matrix.to/#/#aio-libs-space:matrix.org +Project-URL: CI: GitHub Workflows, https://github.com/aio-libs/yarl/actions?query=branch:master +Project-URL: Code of Conduct, https://github.com/aio-libs/.github/blob/master/CODE_OF_CONDUCT.md +Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/yarl +Project-URL: Docs: Changelog, https://yarl.aio-libs.org/en/latest/changes/ +Project-URL: Docs: RTD, https://yarl.aio-libs.org +Project-URL: GitHub: issues, https://github.com/aio-libs/yarl/issues +Project-URL: GitHub: repo, https://github.com/aio-libs/yarl +Keywords: cython,cext,yarl +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Cython +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 :: WWW/HTTP +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.10 +Description-Content-Type: text/x-rst +License-File: LICENSE +License-File: NOTICE +Requires-Dist: idna>=2.0 +Requires-Dist: multidict>=4.0 +Requires-Dist: propcache>=0.2.1 +Dynamic: license-file + +yarl +==== + +The module provides handy URL class for URL parsing and changing. + +.. image:: https://github.com/aio-libs/yarl/workflows/CI/badge.svg + :target: https://github.com/aio-libs/yarl/actions?query=workflow%3ACI + :align: right + +.. image:: https://codecov.io/gh/aio-libs/yarl/graph/badge.svg?flag=pytest + :target: https://app.codecov.io/gh/aio-libs/yarl?flags[]=pytest + :alt: Codecov coverage for the pytest-driven measurements + +.. image:: https://img.shields.io/endpoint?url=https://codspeed.io/badge.json + :target: https://codspeed.io/aio-libs/yarl + +.. image:: https://badge.fury.io/py/yarl.svg + :target: https://badge.fury.io/py/yarl + +.. image:: https://readthedocs.org/projects/yarl/badge/?version=latest + :target: https://yarl.aio-libs.org + +.. image:: https://img.shields.io/pypi/pyversions/yarl.svg + :target: https://pypi.python.org/pypi/yarl + +.. image:: https://img.shields.io/matrix/aio-libs:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat + :target: https://matrix.to/#/%23aio-libs:matrix.org + :alt: Matrix Room — #aio-libs:matrix.org + +.. image:: https://img.shields.io/matrix/aio-libs-space:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs-space%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat + :target: https://matrix.to/#/%23aio-libs-space:matrix.org + :alt: Matrix Space — #aio-libs-space:matrix.org + + +Introduction +------------ + +Url is constructed from ``str``: + +.. code-block:: pycon + + >>> from yarl import URL + >>> url = URL('https://www.python.org/~guido?arg=1#frag') + >>> url + URL('https://www.python.org/~guido?arg=1#frag') + +All url parts: *scheme*, *user*, *password*, *host*, *port*, *path*, +*query* and *fragment* are accessible by properties: + +.. code-block:: pycon + + >>> url.scheme + 'https' + >>> url.host + 'www.python.org' + >>> url.path + '/~guido' + >>> url.query_string + 'arg=1' + >>> url.query + + >>> url.fragment + 'frag' + +All url manipulations produce a new url object: + +.. code-block:: pycon + + >>> url = URL('https://www.python.org') + >>> url / 'foo' / 'bar' + URL('https://www.python.org/foo/bar') + >>> url / 'foo' % {'bar': 'baz'} + URL('https://www.python.org/foo?bar=baz') + +Strings passed to constructor and modification methods are +automatically encoded giving canonical representation as result: + +.. code-block:: pycon + + >>> url = URL('https://www.python.org/шлях') + >>> url + URL('https://www.python.org/%D1%88%D0%BB%D1%8F%D1%85') + +Regular properties are *percent-decoded*, use ``raw_`` versions for +getting *encoded* strings: + +.. code-block:: pycon + + >>> url.path + '/шлях' + + >>> url.raw_path + '/%D1%88%D0%BB%D1%8F%D1%85' + +Human readable representation of URL is available as ``.human_repr()``: + +.. code-block:: pycon + + >>> url.human_repr() + 'https://www.python.org/шлях' + +For full documentation please read https://yarl.aio-libs.org. + + +Installation +------------ + +:: + + $ pip install yarl + +The library is Python 3 only! + +PyPI contains binary wheels for Linux, Windows and MacOS. If you want to install +``yarl`` on another operating system where wheels are not provided, +the tarball will be used to compile the library from +the source code. It requires a C compiler and and Python headers installed. + +To skip the compilation you must explicitly opt-in by using a PEP 517 +configuration setting ``pure-python``, or setting the ``YARL_NO_EXTENSIONS`` +environment variable to a non-empty value, e.g.: + +.. code-block:: console + + $ pip install yarl --config-settings=pure-python=false + +Please note that the pure-Python (uncompiled) version is much slower. However, +PyPy always uses a pure-Python implementation, and, as such, it is unaffected +by this variable. + +Dependencies +------------ + +YARL requires multidict_ and propcache_ libraries. + + +API documentation +------------------ + +The documentation is located at https://yarl.aio-libs.org. + + +Why isn't boolean supported by the URL query API? +------------------------------------------------- + +There is no standard for boolean representation of boolean values. + +Some systems prefer ``true``/``false``, others like ``yes``/``no``, ``on``/``off``, +``Y``/``N``, ``1``/``0``, etc. + +``yarl`` cannot make an unambiguous decision on how to serialize ``bool`` values because +it is specific to how the end-user's application is built and would be different for +different apps. The library doesn't accept booleans in the API; a user should convert +bools into strings using own preferred translation protocol. + + +Comparison with other URL libraries +------------------------------------ + +* furl (https://pypi.python.org/pypi/furl) + + The library has rich functionality but the ``furl`` object is mutable. + + I'm afraid to pass this object into foreign code: who knows if the + code will modify my url in a terrible way while I just want to send URL + with handy helpers for accessing URL properties. + + ``furl`` has other non-obvious tricky things but the main objection + is mutability. + +* URLObject (https://pypi.python.org/pypi/URLObject) + + URLObject is immutable, that's pretty good. + + Every URL change generates a new URL object. + + But the library doesn't do any decode/encode transformations leaving the + end user to cope with these gory details. + + +Source code +----------- + +The project is hosted on GitHub_ + +Please file an issue on the `bug tracker +`_ if you have found a bug +or have some suggestion in order to improve the library. + +Discussion list +--------------- + +*aio-libs* google group: https://groups.google.com/forum/#!forum/aio-libs + +Feel free to post your questions and ideas here. + + +Authors and License +------------------- + +The ``yarl`` package is written by Andrew Svetlov. + +It's *Apache 2* licensed and freely available. + + +.. _GitHub: https://github.com/aio-libs/yarl + +.. _multidict: https://github.com/aio-libs/multidict + +.. _propcache: https://github.com/aio-libs/propcache + +========= +Changelog +========= + +.. + You should *NOT* be adding new change log entries to this file, this + file is managed by towncrier. You *may* edit previous change logs to + fix problems like typo corrections or such. + To add a new change log entry, please see + https://pip.pypa.io/en/latest/development/#adding-a-news-entry + we named the news folder "changes". + + WARNING: Don't drop the next directive! + +.. towncrier release notes start + +1.23.0 +====== + +*(2025-12-16)* + + +Features +-------- + +- Added support for ``pydantic``, the ``~yarl.URL`` could be used as a + field type in ``pydantic`` models seamlessly. + + *Related issues and pull requests on GitHub:* + `#1607 `__. + + +Packaging updates and notes for downstreams +------------------------------------------- + +- The CI has been set up to notify Codecov about upload completion + -- by `@webknjaz `__. + + With this, Codecov no longer needs to guess whether it received all + the intended coverage reports or not. + + *Related issues and pull requests on GitHub:* + `#1577 `__. + +- The in-tree build backend allows the end-users appending + ``CFLAGS`` and ``LDFLAGS`` by setting respective environment + variables externally. + + It additionally sets up default compiler flags to perform + building with maximum optimization in release mode. This + makes the resulting artifacts shipped to PyPI smaller. + + When line tracing is requested, the compiler and linker + flags are configured to include as much information as + possible for debugging and coverage tracking. The + development builds are therefore smaller. + + -- by `@webknjaz `__ + + *Related issues and pull requests on GitHub:* + `#1586 `__. + +- The `PEP 517 `__ build backend now supports a new config + setting for controlling whether to build the project in-tree + or in a temporary directory. It only affects wheels and is + set up to build in a temporary directory by default. It does + not affect editable wheel builds — they will keep being + built in-tree regardless. + + -- by `@webknjaz `__ + + Here's an example of using this setting: + + .. code-block:: console + + $ python -m build \ + --config-setting=build-inplace=true + + *Related issues and pull requests on GitHub:* + `#1590 `__. + +- Starting this version, when building the wheels is happening + in an automatically created temporary directory, the build + backend makes an effort to normalize the respective file + system path to a deterministic source checkout directory. + + -- by `@webknjaz `__ + + It does so by injecting the ``-ffile-prefix-map`` compiler + option into the ``CFLAGS`` environment variable as suggested + by known `reproducible build practices + `__. + + The effect is that downstreams will get more reproducible + build results. + + *Related issues and pull requests on GitHub:* + `#1591 `__. + +- Dropped Python 3.9 support; Python 3.10 is the minimal supported Python version + -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1609 `__. + + +Contributor-facing changes +-------------------------- + +- The deprecated license classifier was removed from ``setup.cfg`` + -- by `@yegorich `__. + + *Related issues and pull requests on GitHub:* + `#1550 `__. + +- The in-tree build backend allows the end-users appending + ``CFLAGS`` and ``LDFLAGS`` by setting respective environment + variables externally. + + It additionally sets up default compiler flags to perform + building with maximum optimization in release mode. This + makes the resulting artifacts shipped to PyPI smaller. + + When line tracing is requested, the compiler and linker + flags are configured to include as much information as + possible for debugging and coverage tracking. The + development builds are therefore smaller. + + -- by `@webknjaz `__ + + *Related issues and pull requests on GitHub:* + `#1586 `__. + +- The CI has been updated to consistently benchmark optimized + release builds -- by `@webknjaz `__. + + When the release workflow is triggered, the pre-built wheels + ready to hit PyPI are being tested. Otherwise, the job + builds the project from source, while the rest of the + workflow uses debug builds for line tracing and coverage + collection. + + *Related issues and pull requests on GitHub:* + `#1587 `__. + + +---- + + +1.22.0 +====== + +*(2025-10-05)* + + +Features +-------- + +- Added arm64 Windows wheel builds + -- by `@finnagin `__. + + *Related issues and pull requests on GitHub:* + `#1516 `__. + + +---- + + +1.21.0 +====== + +*(2025-10-05)* + + +Contributor-facing changes +-------------------------- + +- The ``reusable-cibuildwheel.yml`` workflow has been refactored to + be more generic and ``ci-cd.yml`` now holds all the configuration + toggles -- by `@webknjaz `__. + + *Related issues and pull requests on GitHub:* + `#1535 `__. + +- When building wheels, the source distribution is now passed directly + to the ``cibuildwheel`` invocation -- by `@webknjaz `__. + + *Related issues and pull requests on GitHub:* + `#1536 `__. + +- Added CI for Python 3.14 -- by `@kumaraditya303 `__. + + *Related issues and pull requests on GitHub:* + `#1560 `__. + + +---- + + +1.20.1 +====== + +*(2025-06-09)* + + +Bug fixes +--------- + +- Started raising a ``ValueError`` exception raised for corrupted + IPv6 URL values. + + These fixes the issue where exception ``IndexError`` was + leaking from the internal code because of not being handled and + transformed into a user-facing error. The problem was happening + under the following conditions: empty IPv6 URL, brackets in + reverse order. + + -- by `@MaelPic `__. + + *Related issues and pull requests on GitHub:* + `#1512 `__. + + +Packaging updates and notes for downstreams +------------------------------------------- + +- Updated to use Cython 3.1 universally across the build path -- by `@lysnikolaou `__. + + *Related issues and pull requests on GitHub:* + `#1514 `__. + +- Made Cython line tracing opt-in via the ``with-cython-tracing`` build config setting -- by `@bdraco `__. + + Previously, line tracing was enabled by default in ``pyproject.toml``, which caused build issues for some users and made wheels nearly twice as slow. + Now line tracing is only enabled when explicitly requested via ``pip install . --config-setting=with-cython-tracing=true`` or by setting the ``YARL_CYTHON_TRACING`` environment variable. + + *Related issues and pull requests on GitHub:* + `#1521 `__. + + +---- + + +1.20.0 +====== + +*(2025-04-16)* + + +Features +-------- + +- Implemented support for the free-threaded build of CPython 3.13 -- by `@lysnikolaou `__. + + *Related issues and pull requests on GitHub:* + `#1456 `__. + + +Packaging updates and notes for downstreams +------------------------------------------- + +- Started building wheels for the free-threaded build of CPython 3.13 -- by `@lysnikolaou `__. + + *Related issues and pull requests on GitHub:* + `#1456 `__. + + +---- + + +1.19.0 +====== + +*(2025-04-05)* + + +Bug fixes +--------- + +- Fixed entire name being re-encoded when using ``yarl.URL.with_suffix()`` -- by `@NTFSvolume `__. + + *Related issues and pull requests on GitHub:* + `#1468 `__. + + +Features +-------- + +- Started building armv7l wheels for manylinux -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1495 `__. + + +Contributor-facing changes +-------------------------- + +- GitHub Actions CI/CD is now configured to manage caching pip-ecosystem + dependencies using `re-actors/cache-python-deps`_ -- an action by + `@webknjaz `__ that takes into account ABI stability and the exact + version of Python runtime. + + .. _`re-actors/cache-python-deps`: + https://github.com/marketplace/actions/cache-python-deps + + *Related issues and pull requests on GitHub:* + `#1471 `__. + +- Increased minimum `propcache`_ version to 0.2.1 to fix failing tests -- by `@bdraco `__. + + .. _`propcache`: + https://github.com/aio-libs/propcache + + *Related issues and pull requests on GitHub:* + `#1479 `__. + +- Added all hidden folders to pytest's ``norecursedirs`` to prevent it + from trying to collect tests there -- by `@lysnikolaou `__. + + *Related issues and pull requests on GitHub:* + `#1480 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved accuracy of type annotations -- by `@Dreamsorcerer `__. + + *Related issues and pull requests on GitHub:* + `#1484 `__. + +- Improved performance of parsing query strings -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1493 `__, `#1497 `__. + +- Improved performance of the C unquoter -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1496 `__, `#1498 `__. + + +---- + + +1.18.3 +====== + +*(2024-12-01)* + + +Bug fixes +--------- + +- Fixed uppercase ASCII hosts being rejected by ``URL.build()()`` and ``yarl.URL.with_host()`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#954 `__, `#1442 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performances of multiple path properties on cache miss -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1443 `__. + + +---- + + +1.18.2 +====== + +*(2024-11-29)* + + +No significant changes. + + +---- + + +1.18.1 +====== + +*(2024-11-29)* + + +Miscellaneous internal changes +------------------------------ + +- Improved cache performance when ``~yarl.URL`` objects are constructed from ``yarl.URL.build()`` with ``encoded=True`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1432 `__. + +- Improved cache performance for operations that produce a new ``~yarl.URL`` object -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1434 `__, `#1436 `__. + + +---- + + +1.18.0 +====== + +*(2024-11-21)* + + +Features +-------- + +- Added ``keep_query`` and ``keep_fragment`` flags in the ``yarl.URL.with_path()``, ``yarl.URL.with_name()`` and ``yarl.URL.with_suffix()`` methods, allowing users to optionally retain the query string and fragment in the resulting URL when replacing the path -- by `@paul-nameless `__. + + *Related issues and pull requests on GitHub:* + `#111 `__, `#1421 `__. + + +Contributor-facing changes +-------------------------- + +- Started running downstream ``aiohttp`` tests in CI -- by `@Cycloctane `__. + + *Related issues and pull requests on GitHub:* + `#1415 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of converting ``~yarl.URL`` to a string -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1422 `__. + + +---- + + +1.17.2 +====== + +*(2024-11-17)* + + +Bug fixes +--------- + +- Stopped implicitly allowing the use of Cython pre-release versions when + building the distribution package -- by `@ajsanchezsanz `__ and + `@markgreene74 `__. + + *Related issues and pull requests on GitHub:* + `#1411 `__, `#1412 `__. + +- Fixed a bug causing ``~yarl.URL.port`` to return the default port when the given port was zero + -- by `@gmacon `__. + + *Related issues and pull requests on GitHub:* + `#1413 `__. + + +Features +-------- + +- Make error messages include details of incorrect type when ``port`` is not int in ``yarl.URL.build()``. + -- by `@Cycloctane `__. + + *Related issues and pull requests on GitHub:* + `#1414 `__. + + +Packaging updates and notes for downstreams +------------------------------------------- + +- Stopped implicitly allowing the use of Cython pre-release versions when + building the distribution package -- by `@ajsanchezsanz `__ and + `@markgreene74 `__. + + *Related issues and pull requests on GitHub:* + `#1411 `__, `#1412 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of the ``yarl.URL.joinpath()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1418 `__. + + +---- + + +1.17.1 +====== + +*(2024-10-30)* + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of many ``~yarl.URL`` methods -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1396 `__, `#1397 `__, `#1398 `__. + +- Improved performance of passing a `dict` or `str` to ``yarl.URL.extend_query()`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1401 `__. + + +---- + + +1.17.0 +====== + +*(2024-10-28)* + + +Features +-------- + +- Added ``~yarl.URL.host_port_subcomponent`` which returns the ``3986#section-3.2.2`` host and ``3986#section-3.2.3`` port subcomponent -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1375 `__. + + +---- + + +1.16.0 +====== + +*(2024-10-21)* + + +Bug fixes +--------- + +- Fixed blocking I/O to load Python code when creating a new ``~yarl.URL`` with non-ascii characters in the network location part -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1342 `__. + + +Removals and backward incompatible breaking changes +--------------------------------------------------- + +- Migrated to using a single cache for encoding hosts -- by `@bdraco `__. + + Passing ``ip_address_size`` and ``host_validate_size`` to ``yarl.cache_configure()`` is deprecated in favor of the new ``encode_host_size`` parameter and will be removed in a future release. For backwards compatibility, the old parameters affect the ``encode_host`` cache size. + + *Related issues and pull requests on GitHub:* + `#1348 `__, `#1357 `__, `#1363 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of constructing ``~yarl.URL`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1336 `__. + +- Improved performance of calling ``yarl.URL.build()`` and constructing unencoded ``~yarl.URL`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1345 `__. + +- Reworked the internal encoding cache to improve performance on cache hit -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1369 `__. + + +---- + + +1.15.5 +====== + +*(2024-10-18)* + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of the ``yarl.URL.joinpath()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1304 `__. + +- Improved performance of the ``yarl.URL.extend_query()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1305 `__. + +- Improved performance of the ``yarl.URL.origin()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1306 `__. + +- Improved performance of the ``yarl.URL.with_path()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1307 `__. + +- Improved performance of the ``yarl.URL.with_query()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1308 `__, `#1328 `__. + +- Improved performance of the ``yarl.URL.update_query()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1309 `__, `#1327 `__. + +- Improved performance of the ``yarl.URL.join()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1313 `__. + +- Improved performance of ``~yarl.URL`` equality checks -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1315 `__. + +- Improved performance of ``~yarl.URL`` methods that modify the network location -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1316 `__. + +- Improved performance of the ``yarl.URL.with_fragment()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1317 `__. + +- Improved performance of calculating the hash of ``~yarl.URL`` objects -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1318 `__. + +- Improved performance of the ``yarl.URL.relative()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1319 `__. + +- Improved performance of the ``yarl.URL.with_name()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1320 `__. + +- Improved performance of ``~yarl.URL.parent`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1321 `__. + +- Improved performance of the ``yarl.URL.with_scheme()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1322 `__. + + +---- + + +1.15.4 +====== + +*(2024-10-16)* + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of the quoter when all characters are safe -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1288 `__. + +- Improved performance of unquoting strings -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1292 `__, `#1293 `__. + +- Improved performance of calling ``yarl.URL.build()`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1297 `__. + + +---- + + +1.15.3 +====== + +*(2024-10-15)* + + +Bug fixes +--------- + +- Fixed ``yarl.URL.build()`` failing to validate paths must start with a ``/`` when passing ``authority`` -- by `@bdraco `__. + + The validation only worked correctly when passing ``host``. + + *Related issues and pull requests on GitHub:* + `#1265 `__. + + +Removals and backward incompatible breaking changes +--------------------------------------------------- + +- Removed support for Python 3.8 as it has reached end of life -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1203 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of constructing ``~yarl.URL`` when the net location is only the host -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1271 `__. + + +---- + + +1.15.2 +====== + +*(2024-10-13)* + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of converting ``~yarl.URL`` to a string -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1234 `__. + +- Improved performance of ``yarl.URL.joinpath()`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1248 `__, `#1250 `__. + +- Improved performance of constructing query strings from ``~multidict.MultiDict`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1256 `__. + +- Improved performance of constructing query strings with ``int`` values -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1259 `__. + + +---- + + +1.15.1 +====== + +*(2024-10-12)* + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of calling ``yarl.URL.build()`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1222 `__. + +- Improved performance of all ``~yarl.URL`` methods that create new ``~yarl.URL`` objects -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1226 `__. + +- Improved performance of ``~yarl.URL`` methods that modify the network location -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1229 `__. + + +---- + + +1.15.0 +====== + +*(2024-10-11)* + + +Bug fixes +--------- + +- Fixed validation with ``yarl.URL.with_scheme()`` when passed scheme is not lowercase -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1189 `__. + + +Features +-------- + +- Started building ``armv7l`` wheels -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1204 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of constructing unencoded ``~yarl.URL`` objects -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1188 `__. + +- Added a cache for parsing hosts to reduce overhead of encoding ``~yarl.URL`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1190 `__. + +- Improved performance of constructing query strings from ``~collections.abc.Mapping`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1193 `__. + +- Improved performance of converting ``~yarl.URL`` objects to strings -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1198 `__. + + +---- + + +1.14.0 +====== + +*(2024-10-08)* + + +Packaging updates and notes for downstreams +------------------------------------------- + +- Switched to using the ``propcache`` package for property caching + -- by `@bdraco `__. + + The ``propcache`` package is derived from the property caching + code in ``yarl`` and has been broken out to avoid maintaining it for multiple + projects. + + *Related issues and pull requests on GitHub:* + `#1169 `__. + + +Contributor-facing changes +-------------------------- + +- Started testing with Hypothesis -- by `@webknjaz `__ and `@bdraco `__. + + Special thanks to `@Zac-HD `__ for helping us get started with this framework. + + *Related issues and pull requests on GitHub:* + `#860 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of ``yarl.URL.is_default_port()`` when no explicit port is set -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1168 `__. + +- Improved performance of converting ``~yarl.URL`` to a string when no explicit port is set -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1170 `__. + +- Improved performance of the ``yarl.URL.origin()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1175 `__. + +- Improved performance of encoding hosts -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1176 `__. + + +---- + + +1.13.1 +====== + +*(2024-09-27)* + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of calling ``yarl.URL.build()`` with ``authority`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1163 `__. + + +---- + + +1.13.0 +====== + +*(2024-09-26)* + + +Bug fixes +--------- + +- Started rejecting ASCII hostnames with invalid characters. For host strings that + look like authority strings, the exception message includes advice on what to do + instead -- by `@mjpieters `__. + + *Related issues and pull requests on GitHub:* + `#880 `__, `#954 `__. + +- Fixed IPv6 addresses missing brackets when the ``~yarl.URL`` was converted to a string -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1157 `__, `#1158 `__. + + +Features +-------- + +- Added ``~yarl.URL.host_subcomponent`` which returns the ``3986#section-3.2.2`` host subcomponent -- by `@bdraco `__. + + The only current practical difference between ``~yarl.URL.raw_host`` and ``~yarl.URL.host_subcomponent`` is that IPv6 addresses are returned bracketed. + + *Related issues and pull requests on GitHub:* + `#1159 `__. + + +---- + + +1.12.1 +====== + +*(2024-09-23)* + + +No significant changes. + + +---- + + +1.12.0 +====== + +*(2024-09-23)* + + +Features +-------- + +- Added ``~yarl.URL.path_safe`` to be able to fetch the path without ``%2F`` and ``%25`` decoded -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1150 `__. + + +Removals and backward incompatible breaking changes +--------------------------------------------------- + +- Restore decoding ``%2F`` (``/``) in ``URL.path`` -- by `@bdraco `__. + + This change restored the behavior before `#1057 `__. + + *Related issues and pull requests on GitHub:* + `#1151 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of processing paths -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1143 `__. + + +---- + + +1.11.1 +====== + +*(2024-09-09)* + + +Bug fixes +--------- + +- Allowed scheme replacement for relative URLs if the scheme does not require a host -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#280 `__, `#1138 `__. + +- Allowed empty host for URL schemes other than the special schemes listed in the WHATWG URL spec -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1136 `__. + + +Features +-------- + +- Loosened restriction on integers as query string values to allow classes that implement ``__int__`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1139 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of normalizing paths -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1137 `__. + + +---- + + +1.11.0 +====== + +*(2024-09-08)* + + +Features +-------- + +- Added ``URL.extend_query()()`` method, which can be used to extend parameters without replacing same named keys -- by `@bdraco `__. + + This method was primarily added to replace the inefficient hand rolled method currently used in ``aiohttp``. + + *Related issues and pull requests on GitHub:* + `#1128 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of the Cython ``cached_property`` implementation -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1122 `__. + +- Simplified computing ports by removing unnecessary code -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1123 `__. + +- Improved performance of encoding non IPv6 hosts -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1125 `__. + +- Improved performance of ``URL.build()()`` when the path, query string, or fragment is an empty string -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1126 `__. + +- Improved performance of the ``URL.update_query()()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1130 `__. + +- Improved performance of processing query string changes when arguments are ``str`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1131 `__. + + +---- + + +1.10.0 +====== + +*(2024-09-06)* + + +Bug fixes +--------- + +- Fixed joining a path when the existing path was empty -- by `@bdraco `__. + + A regression in ``URL.join()()`` was introduced in `#1082 `__. + + *Related issues and pull requests on GitHub:* + `#1118 `__. + + +Features +-------- + +- Added ``URL.without_query_params()()`` method, to drop some parameters from query string -- by `@hongquan `__. + + *Related issues and pull requests on GitHub:* + `#774 `__, `#898 `__, `#1010 `__. + +- The previously protected types ``_SimpleQuery``, ``_QueryVariable``, and ``_Query`` are now available for use externally as ``SimpleQuery``, ``QueryVariable``, and ``Query`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1050 `__, `#1113 `__. + + +Contributor-facing changes +-------------------------- + +- Replaced all ``~typing.Optional`` with ``~typing.Union`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1095 `__. + + +Miscellaneous internal changes +------------------------------ + +- Significantly improved performance of parsing the network location -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1112 `__. + +- Added internal types to the cache to prevent future refactoring errors -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1117 `__. + + +---- + + +1.9.11 +====== + +*(2024-09-04)* + + +Bug fixes +--------- + +- Fixed a ``TypeError`` with ``MultiDictProxy`` and Python 3.8 -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1084 `__, `#1105 `__, `#1107 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of encoding hosts -- by `@bdraco `__. + + Previously, the library would unconditionally try to parse a host as an IP Address. The library now avoids trying to parse a host as an IP Address if the string is not in one of the formats described in ``3986#section-3.2.2``. + + *Related issues and pull requests on GitHub:* + `#1104 `__. + + +---- + + +1.9.10 +====== + +*(2024-09-04)* + + +Bug fixes +--------- + +- ``URL.join()()`` has been changed to match + ``3986`` and align with + ``/ operation()`` and ``URL.joinpath()()`` + when joining URLs with empty segments. + Previously ``urllib.parse.urljoin`` was used, + which has known issues with empty segments + (`python/cpython#84774 `_). + + Due to the semantics of ``URL.join()()``, joining an + URL with scheme requires making it relative, prefixing with ``./``. + + .. code-block:: pycon + + >>> URL("https://web.archive.org/web/").join(URL("./https://github.com/aio-libs/yarl")) + URL('https://web.archive.org/web/https://github.com/aio-libs/yarl') + + + Empty segments are honored in the base as well as the joined part. + + .. code-block:: pycon + + >>> URL("https://web.archive.org/web/https://").join(URL("github.com/aio-libs/yarl")) + URL('https://web.archive.org/web/https://github.com/aio-libs/yarl') + + + + -- by `@commonism `__ + + This change initially appeared in 1.9.5 but was reverted in 1.9.6 to resolve a problem with query string handling. + + *Related issues and pull requests on GitHub:* + `#1039 `__, `#1082 `__. + + +Features +-------- + +- Added ``~yarl.URL.absolute`` which is now preferred over ``URL.is_absolute()`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1100 `__. + + +---- + + +1.9.9 +===== + +*(2024-09-04)* + + +Bug fixes +--------- + +- Added missing type on ``~yarl.URL.port`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1097 `__. + + +---- + + +1.9.8 +===== + +*(2024-09-03)* + + +Features +-------- + +- Covered the ``~yarl.URL`` object with types -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1084 `__. + +- Cache parsing of IP Addresses when encoding hosts -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1086 `__. + + +Contributor-facing changes +-------------------------- + +- Covered the ``~yarl.URL`` object with types -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1084 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of handling ports -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1081 `__. + + +---- + + +1.9.7 +===== + +*(2024-09-01)* + + +Removals and backward incompatible breaking changes +--------------------------------------------------- + +- Removed support ``3986#section-3.2.3`` port normalization when the scheme is not one of ``http``, ``https``, ``wss``, or ``ws`` -- by `@bdraco `__. + + Support for port normalization was recently added in `#1033 `__ and contained code that would do blocking I/O if the scheme was not one of the four listed above. The code has been removed because this library is intended to be safe for usage with ``asyncio``. + + *Related issues and pull requests on GitHub:* + `#1076 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of property caching -- by `@bdraco `__. + + The ``reify`` implementation from ``aiohttp`` was adapted to replace the internal ``cached_property`` implementation. + + *Related issues and pull requests on GitHub:* + `#1070 `__. + + +---- + + +1.9.6 +===== + +*(2024-08-30)* + + +Bug fixes +--------- + +- Reverted ``3986`` compatible ``URL.join()()`` honoring empty segments which was introduced in `#1039 `__. + + This change introduced a regression handling query string parameters with joined URLs. The change was reverted to maintain compatibility with the previous behavior. + + *Related issues and pull requests on GitHub:* + `#1067 `__. + + +---- + + +1.9.5 +===== + +*(2024-08-30)* + + +Bug fixes +--------- + +- Joining URLs with empty segments has been changed + to match ``3986``. + + Previously empty segments would be removed from path, + breaking use-cases such as + + .. code-block:: python + + URL("https://web.archive.org/web/") / "https://github.com/" + + Now ``/ operation()`` and ``URL.joinpath()()`` + keep empty segments, but do not introduce new empty segments. + e.g. + + .. code-block:: python + + URL("https://example.org/") / "" + + does not introduce an empty segment. + + -- by `@commonism `__ and `@youtux `__ + + *Related issues and pull requests on GitHub:* + `#1026 `__. + +- The default protocol ports of well-known URI schemes are now taken into account + during the normalization of the URL string representation in accordance with + ``3986#section-3.2.3``. + + Specified ports are removed from the ``str`` representation of a ``~yarl.URL`` + if the port matches the scheme's default port -- by `@commonism `__. + + *Related issues and pull requests on GitHub:* + `#1033 `__. + +- ``URL.join()()`` has been changed to match + ``3986`` and align with + ``/ operation()`` and ``URL.joinpath()()`` + when joining URLs with empty segments. + Previously ``urllib.parse.urljoin`` was used, + which has known issues with empty segments + (`python/cpython#84774 `_). + + Due to the semantics of ``URL.join()()``, joining an + URL with scheme requires making it relative, prefixing with ``./``. + + .. code-block:: pycon + + >>> URL("https://web.archive.org/web/").join(URL("./https://github.com/aio-libs/yarl")) + URL('https://web.archive.org/web/https://github.com/aio-libs/yarl') + + + Empty segments are honored in the base as well as the joined part. + + .. code-block:: pycon + + >>> URL("https://web.archive.org/web/https://").join(URL("github.com/aio-libs/yarl")) + URL('https://web.archive.org/web/https://github.com/aio-libs/yarl') + + + + -- by `@commonism `__ + + *Related issues and pull requests on GitHub:* + `#1039 `__. + + +Removals and backward incompatible breaking changes +--------------------------------------------------- + +- Stopped decoding ``%2F`` (``/``) in ``URL.path``, as this could lead to code incorrectly treating it as a path separator + -- by `@Dreamsorcerer `__. + + *Related issues and pull requests on GitHub:* + `#1057 `__. + +- Dropped support for Python 3.7 -- by `@Dreamsorcerer `__. + + *Related issues and pull requests on GitHub:* + `#1016 `__. + + +Improved documentation +---------------------- + +- On the ``Contributing docs`` page, + a link to the ``Towncrier philosophy`` has been fixed. + + *Related issues and pull requests on GitHub:* + `#981 `__. + +- The pre-existing ``/ magic method()`` + has been documented in the API reference -- by `@commonism `__. + + *Related issues and pull requests on GitHub:* + `#1026 `__. + + +Packaging updates and notes for downstreams +------------------------------------------- + +- A flaw in the logic for copying the project directory into a + temporary folder that led to infinite recursion when ``TMPDIR`` + was set to a project subdirectory path. This was happening in Fedora + and its downstream due to the use of `pyproject-rpm-macros + `__. It was + only reproducible with ``pip wheel`` and was not affecting the + ``pyproject-build`` users. + + -- by `@hroncok `__ and `@webknjaz `__ + + *Related issues and pull requests on GitHub:* + `#992 `__, `#1014 `__. + +- Support Python 3.13 and publish non-free-threaded wheels + + *Related issues and pull requests on GitHub:* + `#1054 `__. + + +Contributor-facing changes +-------------------------- + +- The CI/CD setup has been updated to test ``arm64`` wheels + under macOS 14, except for Python 3.7 that is unsupported + in that environment -- by `@webknjaz `__. + + *Related issues and pull requests on GitHub:* + `#1015 `__. + +- Removed unused type ignores and casts -- by `@hauntsaninja `__. + + *Related issues and pull requests on GitHub:* + `#1031 `__. + + +Miscellaneous internal changes +------------------------------ + +- ``port``, ``scheme``, and ``raw_host`` are now ``cached_property`` -- by `@bdraco `__. + + ``aiohttp`` accesses these properties quite often, which cause ``urllib`` to build the ``_hostinfo`` property every time. ``port``, ``scheme``, and ``raw_host`` are now cached properties, which will improve performance. + + *Related issues and pull requests on GitHub:* + `#1044 `__, `#1058 `__. + + +---- + + +1.9.4 (2023-12-06) +================== + +Bug fixes +--------- + +- Started raising ``TypeError`` when a string value is passed into + ``yarl.URL.build()`` as the ``port`` argument -- by `@commonism `__. + + Previously the empty string as port would create malformed URLs when rendered as string representations. (`#883 `__) + + +Packaging updates and notes for downstreams +------------------------------------------- + +- The leading ``--`` has been dropped from the `PEP 517 `__ in-tree build + backend config setting names. ``--pure-python`` is now just ``pure-python`` + -- by `@webknjaz `__. + + The usage now looks as follows: + + .. code-block:: console + + $ python -m build \ + --config-setting=pure-python=true \ + --config-setting=with-cython-tracing=true + + (`#963 `__) + + +Contributor-facing changes +-------------------------- + +- A step-by-step ``Release Guide`` guide has + been added, describing how to release *yarl* -- by `@webknjaz `__. + + This is primarily targeting maintainers. (`#960 `__) +- Coverage collection has been implemented for the Cython modules + -- by `@webknjaz `__. + + It will also be reported to Codecov from any non-release CI jobs. + + To measure coverage in a development environment, *yarl* can be + installed in editable mode: + + .. code-block:: console + + $ python -Im pip install -e . + + Editable install produces C-files required for the Cython coverage + plugin to map the measurements back to the PYX-files. + + `#961 `__ + +- It is now possible to request line tracing in Cython builds using the + ``with-cython-tracing`` `PEP 517 `__ config setting + -- `@webknjaz `__. + + This can be used in CI and development environment to measure coverage + on Cython modules, but is not normally useful to the end-users or + downstream packagers. + + Here's a usage example: + + .. code-block:: console + + $ python -Im pip install . --config-settings=with-cython-tracing=true + + For editable installs, this setting is on by default. Otherwise, it's + off unless requested explicitly. + + The following produces C-files required for the Cython coverage + plugin to map the measurements back to the PYX-files: + + .. code-block:: console + + $ python -Im pip install -e . + + Alternatively, the ``YARL_CYTHON_TRACING=1`` environment variable + can be set to do the same as the `PEP 517 `__ config setting. + + `#962 `__ + + +1.9.3 (2023-11-20) +================== + +Bug fixes +--------- + +- Stopped dropping trailing slashes in ``yarl.URL.joinpath()`` -- by `@gmacon `__. (`#862 `__, `#866 `__) +- Started accepting string subclasses in ``yarl.URL.__truediv__()`` operations (``URL / segment``) -- by `@mjpieters `__. (`#871 `__, `#884 `__) +- Fixed the human representation of URLs with square brackets in usernames and passwords -- by `@mjpieters `__. (`#876 `__, `#882 `__) +- Updated type hints to include ``URL.missing_port()``, ``URL.__bytes__()`` + and the ``encoding`` argument to ``yarl.URL.joinpath()`` + -- by `@mjpieters `__. (`#891 `__) + + +Packaging updates and notes for downstreams +------------------------------------------- + +- Integrated Cython 3 to enable building *yarl* under Python 3.12 -- by `@mjpieters `__. (`#829 `__, `#881 `__) +- Declared modern ``setuptools.build_meta`` as the `PEP 517 `__ build + backend in ``pyproject.toml`` explicitly -- by `@webknjaz `__. (`#886 `__) +- Converted most of the packaging setup into a declarative ``setup.cfg`` + config -- by `@webknjaz `__. (`#890 `__) +- The packaging is replaced from an old-fashioned ``setup.py`` to an + in-tree `PEP 517 `__ build backend -- by `@webknjaz `__. + + Whenever the end-users or downstream packagers need to build ``yarl`` from + source (a Git checkout or an sdist), they may pass a ``config_settings`` + flag ``--pure-python``. If this flag is not set, a C-extension will be built + and included into the distribution. + + Here is how this can be done with ``pip``: + + .. code-block:: console + + $ python -m pip install . --config-settings=--pure-python=false + + This will also work with ``-e | --editable``. + + The same can be achieved via ``pypa/build``: + + .. code-block:: console + + $ python -m build --config-setting=--pure-python=false + + Adding ``-w | --wheel`` can force ``pypa/build`` produce a wheel from source + directly, as opposed to building an ``sdist`` and then building from it. (`#893 `__) + + .. attention:: + + v1.9.3 was the only version using the ``--pure-python`` setting name. + Later versions dropped the ``--`` prefix, making it just ``pure-python``. + +- Declared Python 3.12 supported officially in the distribution package metadata + -- by `@edgarrmondragon `__. (`#942 `__) + + +Contributor-facing changes +-------------------------- + +- A regression test for no-host URLs was added per `#821 `__ + and ``3986`` -- by `@kenballus `__. (`#821 `__, `#822 `__) +- Started testing *yarl* against Python 3.12 in CI -- by `@mjpieters `__. (`#881 `__) +- All Python 3.12 jobs are now marked as required to pass in CI + -- by `@edgarrmondragon `__. (`#942 `__) +- MyST is now integrated in Sphinx -- by `@webknjaz `__. + + This allows the contributors to author new documents in Markdown + when they have difficulties with going straight RST. (`#953 `__) + + +1.9.2 (2023-04-25) +================== + +Bugfixes +-------- + +- Fix regression with ``yarl.URL.__truediv__()`` and absolute URLs with empty paths causing the raw path to lack the leading ``/``. + (`#854 `_) + + +1.9.1 (2023-04-21) +================== + +Bugfixes +-------- + +- Marked tests that fail on older Python patch releases (< 3.7.10, < 3.8.8 and < 3.9.2) as expected to fail due to missing a security fix for CVE-2021-23336. (`#850 `_) + + +1.9.0 (2023-04-19) +================== + +This release was never published to PyPI, due to issues with the build process. + +Features +-------- + +- Added ``URL.joinpath(*elements)``, to create a new URL appending multiple path elements. (`#704 `_) +- Made ``URL.__truediv__()()`` return ``NotImplemented`` if called with an + unsupported type — by `@michaeljpeters `__. + (`#832 `_) + + +Bugfixes +-------- + +- Path normalization for absolute URLs no longer raises a ValueError exception + when ``..`` segments would otherwise go beyond the URL path root. + (`#536 `_) +- Fixed an issue with update_query() not getting rid of the query when argument is None. (`#792 `_) +- Added some input restrictions on with_port() function to prevent invalid boolean inputs or out of valid port inputs; handled incorrect 0 port representation. (`#793 `_) +- Made ``yarl.URL.build()`` raise a ``TypeError`` if the ``host`` argument is ``None`` — by `@paulpapacz `__. (`#808 `_) +- Fixed an issue with ``update_query()`` getting rid of the query when the argument + is empty but not ``None``. (`#845 `_) + + +Misc +---- + +- `#220 `_ + + +1.8.2 (2022-12-03) +================== + +This is the first release that started shipping wheels for Python 3.11. + + +1.8.1 (2022-08-01) +================== + +Misc +---- + +- `#694 `_, `#699 `_, `#700 `_, `#701 `_, `#702 `_, `#703 `_, `#739 `_ + + +1.8.0 (2022-08-01) +================== + +Features +-------- + +- Added ``URL.raw_suffix``, ``URL.suffix``, ``URL.raw_suffixes``, ``URL.suffixes``, ``URL.with_suffix``. (`#613 `_) + + +Improved Documentation +---------------------- + +- Fixed broken internal references to ``yarl.URL.human_repr()``. + (`#665 `_) +- Fixed broken external references to ``multidict:index`` docs. (`#665 `_) + + +Deprecations and Removals +------------------------- + +- Dropped Python 3.6 support. (`#672 `_) + + +Misc +---- + +- `#646 `_, `#699 `_, `#701 `_ + + +1.7.2 (2021-11-01) +================== + +Bugfixes +-------- + +- Changed call in ``with_port()`` to stop reencoding parts of the URL that were already encoded. (`#623 `_) + + +1.7.1 (2021-10-07) +================== + +Bugfixes +-------- + +- Fix 1.7.0 build error + +1.7.0 (2021-10-06) +================== + +Features +-------- + +- Add ``__bytes__()`` magic method so that ``bytes(url)`` will work and use optimal ASCII encoding. + (`#582 `_) +- Started shipping platform-specific arm64 wheels for Apple Silicon. (`#622 `_) +- Started shipping platform-specific wheels with the ``musl`` tag targeting typical Alpine Linux runtimes. (`#622 `_) +- Added support for Python 3.10. (`#622 `_) + + +1.6.3 (2020-11-14) +================== + +Bugfixes +-------- + +- No longer loose characters when decoding incorrect percent-sequences (like ``%e2%82%f8``). All non-decodable percent-sequences are now preserved. + `#517 `_ +- Provide x86 Windows wheels. + `#535 `_ + + +---- + + +1.6.2 (2020-10-12) +================== + + +Bugfixes +-------- + +- Provide generated ``.c`` files in TarBall distribution. + `#530 `_ + +1.6.1 (2020-10-12) +================== + +Features +-------- + +- Provide wheels for ``aarch64``, ``i686``, ``ppc64le``, ``s390x`` architectures on + Linux as well as ``x86_64``. + `#507 `_ +- Provide wheels for Python 3.9. + `#526 `_ + +Bugfixes +-------- + +- ``human_repr()`` now always produces valid representation equivalent to the original URL (if the original URL is valid). + `#511 `_ +- Fixed requoting a single percent followed by a percent-encoded character in the Cython implementation. + `#514 `_ +- Fix ValueError when decoding ``%`` which is not followed by two hexadecimal digits. + `#516 `_ +- Fix decoding ``%`` followed by a space and hexadecimal digit. + `#520 `_ +- Fix annotation of ``with_query()``/``update_query()`` methods for ``key=[val1, val2]`` case. + `#528 `_ + +Removal +------- + +- Drop Python 3.5 support; Python 3.6 is the minimal supported Python version. + + +---- + + +1.6.0 (2020-09-23) +================== + +Features +-------- + +- Allow for int and float subclasses in query, while still denying bool. + `#492 `_ + + +Bugfixes +-------- + +- Do not requote arguments in ``URL.build()``, ``with_xxx()`` and in ``/`` operator. + `#502 `_ +- Keep IPv6 brackets in ``origin()``. + `#504 `_ + + +---- + + +1.5.1 (2020-08-01) +================== + +Bugfixes +-------- + +- Fix including relocated internal ``yarl._quoting_c`` C-extension into published PyPI dists. + `#485 `_ + + +Misc +---- + +- `#484 `_ + + +---- + + +1.5.0 (2020-07-26) +================== + +Features +-------- + +- Convert host to lowercase on URL building. + `#386 `_ +- Allow using ``mod`` operator (``%``) for updating query string (an alias for ``update_query()`` method). + `#435 `_ +- Allow use of sequences such as ``list`` and ``tuple`` in the values + of a mapping such as ``dict`` to represent that a key has many values:: + + url = URL("http://example.com") + assert url.with_query({"a": [1, 2]}) == URL("http://example.com/?a=1&a=2") + + `#443 `_ +- Support ``URL.build()`` with scheme and path (creates a relative URL). + `#464 `_ +- Cache slow IDNA encode/decode calls. + `#476 `_ +- Add ``@final`` / ``Final`` type hints + `#477 `_ +- Support URL authority/raw_authority properties and authority argument of ``URL.build()`` method. + `#478 `_ +- Hide the library implementation details, make the exposed public list very clean. + `#483 `_ + + +Bugfixes +-------- + +- Fix tests with newer Python (3.7.6, 3.8.1 and 3.9.0+). + `#409 `_ +- Fix a bug where query component, passed in a form of mapping or sequence, is unquoted in unexpected way. + `#426 `_ +- Hide ``Query`` and ``QueryVariable`` type aliases in ``__init__.pyi``, now they are prefixed with underscore. + `#431 `_ +- Keep IPv6 brackets after updating port/user/password. + `#451 `_ + + +---- + + +1.4.2 (2019-12-05) +================== + +Features +-------- + +- Workaround for missing ``str.isascii()`` in Python 3.6 + `#389 `_ + + +---- + + +1.4.1 (2019-11-29) +================== + +* Fix regression, make the library work on Python 3.5 and 3.6 again. + +1.4.0 (2019-11-29) +================== + +* Distinguish an empty password in URL from a password not provided at all (#262) + +* Fixed annotations for optional parameters of ``URL.build`` (#309) + +* Use None as default value of ``user`` parameter of ``URL.build`` (#309) + +* Enforce building C Accelerated modules when installing from source tarball, use + ``YARL_NO_EXTENSIONS`` environment variable for falling back to (slower) Pure Python + implementation (#329) + +* Drop Python 3.5 support + +* Fix quoting of plus in path by pure python version (#339) + +* Don't create a new URL if fragment is unchanged (#292) + +* Included in error message the path that produces starting slash forbidden error (#376) + +* Skip slow IDNA encoding for ASCII-only strings (#387) + + +1.3.0 (2018-12-11) +================== + +* Fix annotations for ``query`` parameter (#207) + +* An incoming query sequence can have int variables (the same as for + Mapping type) (#208) + +* Add ``URL.explicit_port`` property (#218) + +* Give a friendlier error when port can't be converted to int (#168) + +* ``bool(URL())`` now returns ``False`` (#272) + +1.2.6 (2018-06-14) +================== + +* Drop Python 3.4 trove classifier (#205) + +1.2.5 (2018-05-23) +================== + +* Fix annotations for ``build`` (#199) + +1.2.4 (2018-05-08) +================== + +* Fix annotations for ``cached_property`` (#195) + +1.2.3 (2018-05-03) +================== + +* Accept ``str`` subclasses in ``URL`` constructor (#190) + +1.2.2 (2018-05-01) +================== + +* Fix build + +1.2.1 (2018-04-30) +================== + +* Pin minimal required Python to 3.5.3 (#189) + +1.2.0 (2018-04-30) +================== + +* Forbid inheritance, replace ``__init__`` with ``__new__`` (#171) + +* Support PEP-561 (provide type hinting marker) (#182) + +1.1.1 (2018-02-17) +================== + +* Fix performance regression: don't encode empty ``netloc`` (#170) + +1.1.0 (2018-01-21) +================== + +* Make pure Python quoter consistent with Cython version (#162) + +1.0.0 (2018-01-15) +================== + +* Use fast path if quoted string does not need requoting (#154) + +* Speed up quoting/unquoting by ``_Quoter`` and ``_Unquoter`` classes (#155) + +* Drop ``yarl.quote`` and ``yarl.unquote`` public functions (#155) + +* Add custom string writer, reuse static buffer if available (#157) + Code is 50-80 times faster than Pure Python version (was 4-5 times faster) + +* Don't recode IP zone (#144) + +* Support ``encoded=True`` in ``yarl.URL.build()`` (#158) + +* Fix updating query with multiple keys (#160) + +0.18.0 (2018-01-10) +=================== + +* Fallback to IDNA 2003 if domain name is not IDNA 2008 compatible (#152) + +0.17.0 (2017-12-30) +=================== + +* Use IDNA 2008 for domain name processing (#149) + +0.16.0 (2017-12-07) +=================== + +* Fix raising ``TypeError`` by ``url.query_string()`` after + ``url.with_query({})`` (empty mapping) (#141) + +0.15.0 (2017-11-23) +=================== + +* Add ``raw_path_qs`` attribute (#137) + +0.14.2 (2017-11-14) +=================== + +* Restore ``strict`` parameter as no-op in ``quote`` / ``unquote`` + +0.14.1 (2017-11-13) +=================== + +* Restore ``strict`` parameter as no-op for sake of compatibility with + aiohttp 2.2 + +0.14.0 (2017-11-11) +=================== + +* Drop strict mode (#123) + +* Fix ``"ValueError: Unallowed PCT %"`` when there's a ``"%"`` in the URL (#124) + +0.13.0 (2017-10-01) +=================== + +* Document ``encoded`` parameter (#102) + +* Support relative URLs like ``'?key=value'`` (#100) + +* Unsafe encoding for QS fixed. Encode ``;`` character in value parameter (#104) + +* Process passwords without user names (#95) + +0.12.0 (2017-06-26) +=================== + +* Properly support paths without leading slash in ``URL.with_path()`` (#90) + +* Enable type annotation checks + +0.11.0 (2017-06-26) +=================== + +* Normalize path (#86) + +* Clear query and fragment parts in ``.with_path()`` (#85) + +0.10.3 (2017-06-13) +=================== + +* Prevent double URL arguments unquoting (#83) + +0.10.2 (2017-05-05) +=================== + +* Unexpected hash behavior (#75) + + +0.10.1 (2017-05-03) +=================== + +* Unexpected compare behavior (#73) + +* Do not quote or unquote + if not a query string. (#74) + + +0.10.0 (2017-03-14) +=================== + +* Added ``URL.build`` class method (#58) + +* Added ``path_qs`` attribute (#42) + + +0.9.8 (2017-02-16) +================== + +* Do not quote ``:`` in path + + +0.9.7 (2017-02-16) +================== + +* Load from pickle without _cache (#56) + +* Percent-encoded pluses in path variables become spaces (#59) + + +0.9.6 (2017-02-15) +================== + +* Revert backward incompatible change (BaseURL) + + +0.9.5 (2017-02-14) +================== + +* Fix BaseURL rich comparison support + + +0.9.4 (2017-02-14) +================== + +* Use BaseURL + + +0.9.3 (2017-02-14) +================== + +* Added BaseURL + + +0.9.2 (2017-02-08) +================== + +* Remove debug print + + +0.9.1 (2017-02-07) +================== + +* Do not lose tail chars (#45) + + +0.9.0 (2017-02-07) +================== + +* Allow to quote ``%`` in non strict mode (#21) + +* Incorrect parsing of query parameters with %3B (;) inside (#34) + +* Fix core dumps (#41) + +* ``tmpbuf`` - compiling error (#43) + +* Added ``URL.update_path()`` method + +* Added ``URL.update_query()`` method (#47) + + +0.8.1 (2016-12-03) +================== + +* Fix broken aiohttp: revert back ``quote`` / ``unquote``. + + +0.8.0 (2016-12-03) +================== + +* Support more verbose error messages in ``.with_query()`` (#24) + +* Don't percent-encode ``@`` and ``:`` in path (#32) + +* Don't expose ``yarl.quote`` and ``yarl.unquote``, these functions are + part of private API + +0.7.1 (2016-11-18) +================== + +* Accept not only ``str`` but all classes inherited from ``str`` also (#25) + +0.7.0 (2016-11-07) +================== + +* Accept ``int`` as value for ``.with_query()`` + +0.6.0 (2016-11-07) +================== + +* Explicitly use UTF8 encoding in ``setup.py`` (#20) +* Properly unquote non-UTF8 strings (#19) + +0.5.3 (2016-11-02) +================== + +* Don't use ``typing.NamedTuple`` fields but indexes on URL construction + +0.5.2 (2016-11-02) +================== + +* Inline ``_encode`` class method + +0.5.1 (2016-11-02) +================== + +* Make URL construction faster by removing extra classmethod calls + +0.5.0 (2016-11-02) +================== + +* Add Cython optimization for quoting/unquoting +* Provide binary wheels + +0.4.3 (2016-09-29) +================== + +* Fix typing stubs + +0.4.2 (2016-09-29) +================== + +* Expose ``quote()`` and ``unquote()`` as public API + +0.4.1 (2016-09-28) +================== + +* Support empty values in query (``'/path?arg'``) + +0.4.0 (2016-09-27) +================== + +* Introduce ``relative()`` (#16) + +0.3.2 (2016-09-27) +================== + +* Typo fixes #15 + +0.3.1 (2016-09-26) +================== + +* Support sequence of pairs as ``with_query()`` parameter + +0.3.0 (2016-09-26) +================== + +* Introduce ``is_default_port()`` + +0.2.1 (2016-09-26) +================== + +* Raise ValueError for URLs like 'http://:8080/' + +0.2.0 (2016-09-18) +================== + +* Avoid doubling slashes when joining paths (#13) + +* Appending path starting from slash is forbidden (#12) + +0.1.4 (2016-09-09) +================== + +* Add ``kwargs`` support for ``with_query()`` (#10) + +0.1.3 (2016-09-07) +================== + +* Document ``with_query()``, ``with_fragment()`` and ``origin()`` + +* Allow ``None`` for ``with_query()`` and ``with_fragment()`` + +0.1.2 (2016-09-07) +================== + +* Fix links, tune docs theme. + +0.1.1 (2016-09-06) +================== + +* Update README, old version used obsolete API + +0.1.0 (2016-09-06) +================== + +* The library was deeply refactored, bytes are gone away but all + accepted strings are encoded if needed. + +0.0.1 (2016-08-30) +================== + +* The first release. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl-1.23.0.dist-info/RECORD b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl-1.23.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..f5c4a0a8ad91603291a86dbb49cbbe315169b7c2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl-1.23.0.dist-info/RECORD @@ -0,0 +1,26 @@ +yarl-1.23.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +yarl-1.23.0.dist-info/METADATA,sha256=l0VbtblnSH8XWPZKR_A1jQl3ROPvc-nkbPqws64ygMs,82198 +yarl-1.23.0.dist-info/RECORD,, +yarl-1.23.0.dist-info/WHEEL,sha256=Qh2avHng3Fd3MK94tkj7sAzq7BeNPYVHo4ICDcBUXug,101 +yarl-1.23.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +yarl-1.23.0.dist-info/licenses/NOTICE,sha256=VtasbIEFwKUTBMIdsGDjYa-ajqCvmnXCOcKLXRNpODg,609 +yarl-1.23.0.dist-info/top_level.txt,sha256=vf3SJuQh-k7YtvsUrV_OPOrT9Kqn0COlk7IPYyhtGkQ,5 +yarl/__init__.py,sha256=KmyqgCWeULtsz7vrl88s5DoGlB_TWhnidh9gjmpQUdg,281 +yarl/__pycache__/__init__.cpython-311.pyc,, +yarl/__pycache__/_parse.cpython-311.pyc,, +yarl/__pycache__/_path.cpython-311.pyc,, +yarl/__pycache__/_query.cpython-311.pyc,, +yarl/__pycache__/_quoters.cpython-311.pyc,, +yarl/__pycache__/_quoting.cpython-311.pyc,, +yarl/__pycache__/_quoting_py.cpython-311.pyc,, +yarl/__pycache__/_url.cpython-311.pyc,, +yarl/_parse.py,sha256=svtLt64KnlURnY4PBwxrudOc7JU5Tptu4hC7LwUTwBU,7100 +yarl/_path.py,sha256=A0FJUylZyzmlT0a3UDOBbK-EzZXCAYuQQBvG9eAC9hs,1291 +yarl/_query.py,sha256=BbAz7wC44pd6kR6UfPvTp4h3abidMKsmSkvdKwWZnus,4041 +yarl/_quoters.py,sha256=herzLBL6OgD37k7SIUnQ1qEsPKtcrUDt_4ai6xwevQk,1117 +yarl/_quoting.py,sha256=yKIqFTzFzWLVb08xy1DSxKNjFwo4f-oLlzxTuKwC57M,506 +yarl/_quoting_c.cp311-win_amd64.pyd,sha256=52-92Y267Xe6rM0yKZx7hjlKbK9iVVBdRoQhgD4x-qI,81408 +yarl/_quoting_c.pyx,sha256=X40gvQSUB4l7nPKGeiS6pq2JreM36avLhVeBMxd5zmo,14297 +yarl/_quoting_py.py,sha256=_l-v8siONK5WihAvui1M5krNqooeV01s1t9nQGMjcVI,6752 +yarl/_url.py,sha256=NPloMycA8KSUZWe6MV3CryOZqWVpE70ROkr0mraS6rM,56976 +yarl/py.typed,sha256=ay5OMO475PlcZ_Fbun9maHW7Y6MBTk0UXL4ztHx3Iug,14 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl-1.23.0.dist-info/WHEEL b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl-1.23.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..8c29ba5e81d5d4eeef1233de33444324d813f82f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl-1.23.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.0) +Root-Is-Purelib: false +Tag: cp311-cp311-win_amd64 + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl-1.23.0.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl-1.23.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl-1.23.0.dist-info/licenses/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl-1.23.0.dist-info/licenses/NOTICE b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl-1.23.0.dist-info/licenses/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..fa53b2b138df881c4c95239d0e4bede831b36ab5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl-1.23.0.dist-info/licenses/NOTICE @@ -0,0 +1,13 @@ + Copyright 2016-2021, Andrew Svetlov and aio-libs team + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl-1.23.0.dist-info/top_level.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl-1.23.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..e93e8bddefb14a8a753f7ecab6b934fd899cd9e5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl-1.23.0.dist-info/top_level.txt @@ -0,0 +1 @@ +yarl diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6280e4c72a09244ac133dd04432cf3a4b6efd4d8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__init__.py @@ -0,0 +1,14 @@ +from ._query import Query, QueryVariable, SimpleQuery +from ._url import URL, cache_clear, cache_configure, cache_info + +__version__ = "1.23.0" + +__all__ = ( + "URL", + "SimpleQuery", + "QueryVariable", + "Query", + "cache_clear", + "cache_configure", + "cache_info", +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ef82f44159dd0e19cc6b4e198d8ba6103b2dab5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__pycache__/_parse.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__pycache__/_parse.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..049a92418cc5d98b3e50f55682efd2839e176581 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__pycache__/_parse.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__pycache__/_path.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__pycache__/_path.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4cf1678ccd5e2d0287ae02ea2daa8136dd3282f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__pycache__/_path.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__pycache__/_query.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__pycache__/_query.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c92c71266b1487277e92b96d3b8cc0f5884d577 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__pycache__/_query.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__pycache__/_quoters.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__pycache__/_quoters.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..268861447b1211c615750a9effc21e74d7c76a8d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__pycache__/_quoters.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__pycache__/_quoting.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__pycache__/_quoting.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..baef960ee6eb2ea52085720ba19f357da6672c35 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__pycache__/_quoting.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__pycache__/_quoting_py.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__pycache__/_quoting_py.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf9159e97e343f9741e610d23a45cbd75d2ff211 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__pycache__/_quoting_py.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__pycache__/_url.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__pycache__/_url.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9883db3fdfb8ce352d8262e8f474679a638ff0a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/__pycache__/_url.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_parse.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..bb64165c7a7bcaf04d55aa8639db70ce24140cfd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_parse.py @@ -0,0 +1,202 @@ +"""URL parsing utilities.""" + +import re +import unicodedata +from functools import lru_cache +from urllib.parse import scheme_chars, uses_netloc + +from ._quoters import QUOTER, UNQUOTER_PLUS + +# Leading and trailing C0 control and space to be stripped per WHATWG spec. +# == "".join([chr(i) for i in range(0, 0x20 + 1)]) +WHATWG_C0_CONTROL_OR_SPACE = ( + "\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10" + "\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f " +) + +# Unsafe bytes to be removed per WHATWG spec +UNSAFE_URL_BYTES_TO_REMOVE = ["\t", "\r", "\n"] +USES_AUTHORITY = frozenset(uses_netloc) + +SplitURLType = tuple[str, str, str, str, str] + + +def split_url(url: str) -> SplitURLType: + """Split URL into parts.""" + # Adapted from urllib.parse.urlsplit + # Only lstrip url as some applications rely on preserving trailing space. + # (https://url.spec.whatwg.org/#concept-basic-url-parser would strip both) + url = url.lstrip(WHATWG_C0_CONTROL_OR_SPACE) + for b in UNSAFE_URL_BYTES_TO_REMOVE: + if b in url: + url = url.replace(b, "") + + scheme = netloc = query = fragment = "" + i = url.find(":") + if i > 0 and url[0] in scheme_chars: + for c in url[1:i]: + if c not in scheme_chars: + break + else: + scheme, url = url[:i].lower(), url[i + 1 :] + has_hash = "#" in url + has_question_mark = "?" in url + if url[:2] == "//": + delim = len(url) # position of end of domain part of url, default is end + if has_hash and has_question_mark: + delim_chars = "/?#" + elif has_question_mark: + delim_chars = "/?" + elif has_hash: + delim_chars = "/#" + else: + delim_chars = "/" + for c in delim_chars: # look for delimiters; the order is NOT important + wdelim = url.find(c, 2) # find first of this delim + if wdelim >= 0 and wdelim < delim: # if found + delim = wdelim # use earliest delim position + netloc = url[2:delim] + url = url[delim:] + has_left_bracket = "[" in netloc + has_right_bracket = "]" in netloc + if (has_left_bracket and not has_right_bracket) or ( + has_right_bracket and not has_left_bracket + ): + raise ValueError("Invalid IPv6 URL") + if has_left_bracket: + bracketed_host = netloc.partition("[")[2].partition("]")[0] + # Valid bracketed hosts are defined in + # https://www.rfc-editor.org/rfc/rfc3986#page-49 + # https://url.spec.whatwg.org/ + if bracketed_host and bracketed_host[0] == "v": + if not re.match(r"\Av[a-fA-F0-9]+\..+\Z", bracketed_host): + raise ValueError("IPvFuture address is invalid") + elif ":" not in bracketed_host: + raise ValueError("The IPv6 content between brackets is not valid") + if has_hash: + url, _, fragment = url.partition("#") + if has_question_mark: + url, _, query = url.partition("?") + if netloc and not netloc.isascii(): + _check_netloc(netloc) + return scheme, netloc, url, query, fragment + + +def _check_netloc(netloc: str) -> None: + # Adapted from urllib.parse._checknetloc + # looking for characters like \u2100 that expand to 'a/c' + # IDNA uses NFKC equivalence, so normalize for this check + + # ignore characters already included + # but not the surrounding text + n = netloc.replace("@", "").replace(":", "").replace("#", "").replace("?", "") + normalized_netloc = unicodedata.normalize("NFKC", n) + if n == normalized_netloc: + return + # Note that there are no unicode decompositions for the character '@' so + # its currently impossible to have test coverage for this branch, however if the + # one should be added in the future we want to make sure its still checked. + for c in "/?#@:": # pragma: no branch + if c in normalized_netloc: + raise ValueError( + f"netloc '{netloc}' contains invalid " + "characters under NFKC normalization" + ) + + +@lru_cache # match the same size as urlsplit +def split_netloc( + netloc: str, +) -> tuple[str | None, str | None, str | None, int | None]: + """Split netloc into username, password, host and port.""" + if "@" not in netloc: + username: str | None = None + password: str | None = None + hostinfo = netloc + else: + userinfo, _, hostinfo = netloc.rpartition("@") + username, have_password, password = userinfo.partition(":") + if not have_password: + password = None + + if "[" in hostinfo: + _, _, bracketed = hostinfo.partition("[") + hostname, _, port_str = bracketed.partition("]") + _, _, port_str = port_str.partition(":") + else: + hostname, _, port_str = hostinfo.partition(":") + + if not port_str: + return username or None, password, hostname or None, None + + try: + port = int(port_str) + except ValueError: + raise ValueError("Invalid URL: port can't be converted to integer") + if not (0 <= port <= 65535): + raise ValueError("Port out of range 0-65535") + return username or None, password, hostname or None, port + + +def unsplit_result( + scheme: str, netloc: str, url: str, query: str, fragment: str +) -> str: + """Unsplit a URL without any normalization.""" + if netloc or (scheme and scheme in USES_AUTHORITY) or url[:2] == "//": + if url and url[:1] != "/": + url = f"{scheme}://{netloc}/{url}" if scheme else f"{scheme}:{url}" + else: + url = f"{scheme}://{netloc}{url}" if scheme else f"//{netloc}{url}" + elif scheme: + url = f"{scheme}:{url}" + if query: + url = f"{url}?{query}" + return f"{url}#{fragment}" if fragment else url + + +@lru_cache # match the same size as urlsplit +def make_netloc( + user: str | None, + password: str | None, + host: str | None, + port: int | None, + encode: bool = False, +) -> str: + """Make netloc from parts. + + The user and password are encoded if encode is True. + + The host must already be encoded with _encode_host. + """ + if host is None: + return "" + ret = host + if port is not None: + ret = f"{ret}:{port}" + if user is None and password is None: + return ret + if password is not None: + if not user: + user = "" + elif encode: + user = QUOTER(user) + if encode: + password = QUOTER(password) + user = f"{user}:{password}" + elif user and encode: + user = QUOTER(user) + return f"{user}@{ret}" if user else ret + + +def query_to_pairs(query_string: str) -> list[tuple[str, str]]: + """Parse a query given as a string argument. + + Works like urllib.parse.parse_qsl with keep empty values. + """ + pairs: list[tuple[str, str]] = [] + if not query_string: + return pairs + for k_v in query_string.split("&"): + k, _, v = k_v.partition("=") + pairs.append((UNQUOTER_PLUS(k), UNQUOTER_PLUS(v))) + return pairs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_path.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_path.py new file mode 100644 index 0000000000000000000000000000000000000000..c22f0b4b8cdd9280fd36789e2bc052b1c4938167 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_path.py @@ -0,0 +1,41 @@ +"""Utilities for working with paths.""" + +from collections.abc import Sequence +from contextlib import suppress + + +def normalize_path_segments(segments: Sequence[str]) -> list[str]: + """Drop '.' and '..' from a sequence of str segments""" + + resolved_path: list[str] = [] + + for seg in segments: + if seg == "..": + # ignore any .. segments that would otherwise cause an + # IndexError when popped from resolved_path if + # resolving for rfc3986 + with suppress(IndexError): + resolved_path.pop() + elif seg != ".": + resolved_path.append(seg) + + if segments and segments[-1] in (".", ".."): + # do some post-processing here. + # if the last segment was a relative dir, + # then we need to append the trailing '/' + resolved_path.append("") + + return resolved_path + + +def normalize_path(path: str) -> str: + # Drop '.' and '..' from str path + prefix = "" + if path and path[0] == "/": + # preserve the "/" root element of absolute paths, copying it to the + # normalised output as per sections 5.2.4 and 6.2.2.3 of rfc3986. + prefix = "/" + path = path[1:] + + segments = path.split("/") + return prefix + "/".join(normalize_path_segments(segments)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_query.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_query.py new file mode 100644 index 0000000000000000000000000000000000000000..809948d9a30c3e23207daf3573397511105ad6a4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_query.py @@ -0,0 +1,121 @@ +"""Query string handling.""" + +import math +from collections.abc import Iterable, Mapping, Sequence +from typing import TYPE_CHECKING, Any, SupportsInt, Union, cast + +from multidict import istr + +from ._quoters import QUERY_PART_QUOTER, QUERY_QUOTER + +SimpleQuery = Union[str, SupportsInt, float] +QueryVariable = Union[SimpleQuery, Sequence[SimpleQuery]] +Query = Union[ + None, str, Mapping[str, QueryVariable], Sequence[tuple[str, QueryVariable]] +] + + +def query_var(v: SimpleQuery) -> str: + """Convert a query variable to a string.""" + cls = type(v) + if cls is int: # Fast path for non-subclassed int + return str(v) + if isinstance(v, str): + return v + if isinstance(v, float): + if math.isinf(v): + raise ValueError("float('inf') is not supported") + if math.isnan(v): + raise ValueError("float('nan') is not supported") + return str(float(v)) + if cls is not bool and isinstance(v, SupportsInt): + return str(int(v)) + raise TypeError( + "Invalid variable type: value " + "should be str, int or float, got {!r} " + "of type {}".format(v, cls) + ) + + +def get_str_query_from_sequence_iterable( + items: Iterable[tuple[str | istr, QueryVariable]], +) -> str: + """Return a query string from a sequence of (key, value) pairs. + + value is a single value or a sequence of values for the key + + The sequence of values must be a list or tuple. + """ + quoter = QUERY_PART_QUOTER + pairs = [ + f"{quoter(k)}={quoter(v if type(v) is str else query_var(v))}" + for k, val in items + for v in ( + val if type(val) is not str and isinstance(val, (list, tuple)) else (val,) + ) + ] + return "&".join(pairs) + + +def get_str_query_from_iterable( + items: Iterable[tuple[str | istr, SimpleQuery]], +) -> str: + """Return a query string from an iterable. + + The iterable must contain (key, value) pairs. + + The values are not allowed to be sequences, only single values are + allowed. For sequences, use `_get_str_query_from_sequence_iterable`. + """ + quoter = QUERY_PART_QUOTER + # A listcomp is used since listcomps are inlined on CPython 3.12+ and + # they are a bit faster than a generator expression. + pairs = [ + f"{quoter(k)}={quoter(v if type(v) is str else query_var(v))}" for k, v in items + ] + return "&".join(pairs) + + +def get_str_query(*args: Any, **kwargs: Any) -> str | None: + """Return a query string from supported args.""" + query: ( + str + | Mapping[str, QueryVariable] + | Sequence[tuple[str | istr, SimpleQuery]] + | None + ) + if kwargs: + if args: + msg = "Either kwargs or single query parameter must be present" + raise ValueError(msg) + query = kwargs + elif len(args) == 1: + query = args[0] + else: + raise ValueError("Either kwargs or single query parameter must be present") + + if query is None: + return None + if not query: + return "" + if type(query) is dict: + return get_str_query_from_sequence_iterable(query.items()) + if type(query) is str or isinstance(query, str): + return QUERY_QUOTER(query) + if isinstance(query, Mapping): + return get_str_query_from_sequence_iterable(query.items()) + if isinstance(query, (bytes, bytearray, memoryview)): + msg = "Invalid query type: bytes, bytearray and memoryview are forbidden" + raise TypeError(msg) + if isinstance(query, Sequence): + # We don't expect sequence values if we're given a list of pairs + # already; only mappings like builtin `dict` which can't have the + # same key pointing to multiple values are allowed to use + # `_query_seq_pairs`. + if TYPE_CHECKING: + query = cast(Sequence[tuple[Union[str, istr], SimpleQuery]], query) + return get_str_query_from_iterable(query) + raise TypeError( + "Invalid query type: only str, mapping or " + "sequence of (key, value) pairs is allowed" + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_quoters.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_quoters.py new file mode 100644 index 0000000000000000000000000000000000000000..78f77ca1249f0c5b609d2605c7b01460c084350d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_quoters.py @@ -0,0 +1,32 @@ +"""Quoting and unquoting utilities for URL parts.""" + +from urllib.parse import quote + +from ._quoting import _Quoter, _Unquoter + +QUOTER = _Quoter(requote=False) +REQUOTER = _Quoter() +PATH_QUOTER = _Quoter(safe="@:", protected="/+", requote=False) +PATH_REQUOTER = _Quoter(safe="@:", protected="/+") +QUERY_QUOTER = _Quoter(safe="?/:@", protected="=+&;", qs=True, requote=False) +QUERY_REQUOTER = _Quoter(safe="?/:@", protected="=+&;", qs=True) +QUERY_PART_QUOTER = _Quoter(safe="?/:@", qs=True, requote=False) +FRAGMENT_QUOTER = _Quoter(safe="?/:@", requote=False) +FRAGMENT_REQUOTER = _Quoter(safe="?/:@") + +UNQUOTER = _Unquoter() +PATH_UNQUOTER = _Unquoter(unsafe="+") +PATH_SAFE_UNQUOTER = _Unquoter(ignore="/%", unsafe="+") +QS_UNQUOTER = _Unquoter(qs=True) +UNQUOTER_PLUS = _Unquoter(plus=True) # to match urllib.parse.unquote_plus + + +def human_quote(s: str | None, unsafe: str) -> str | None: + if not s: + return s + for c in "%" + unsafe: + if c in s: + s = s.replace(c, f"%{ord(c):02X}") + if s.isprintable(): + return s + return "".join(c if c.isprintable() else quote(c) for c in s) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_quoting.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_quoting.py new file mode 100644 index 0000000000000000000000000000000000000000..25d76c885cacaa815bb7e0149aedbe76c20f2228 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_quoting.py @@ -0,0 +1,19 @@ +import os +import sys +from typing import TYPE_CHECKING + +__all__ = ("_Quoter", "_Unquoter") + + +NO_EXTENSIONS = bool(os.environ.get("YARL_NO_EXTENSIONS")) # type: bool +if sys.implementation.name != "cpython": + NO_EXTENSIONS = True + + +if TYPE_CHECKING or NO_EXTENSIONS: + from ._quoting_py import _Quoter, _Unquoter +else: + try: + from ._quoting_c import _Quoter, _Unquoter + except ImportError: # pragma: no cover + from ._quoting_py import _Quoter, _Unquoter # type: ignore[assignment] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_quoting_c.cp311-win_amd64.pyd b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_quoting_c.cp311-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..a19212f04683b37605c19a9fbbf37018621d3e34 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_quoting_c.cp311-win_amd64.pyd differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_quoting_c.pyx b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_quoting_c.pyx new file mode 100644 index 0000000000000000000000000000000000000000..dacf6b088c53e77a43f0435c06a2cbf51dcf4486 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_quoting_c.pyx @@ -0,0 +1,451 @@ +from cpython.exc cimport PyErr_NoMemory +from cpython.mem cimport PyMem_Free, PyMem_Malloc, PyMem_Realloc +from cpython.unicode cimport ( + PyUnicode_DATA, + PyUnicode_DecodeASCII, + PyUnicode_DecodeUTF8Stateful, + PyUnicode_GET_LENGTH, + PyUnicode_KIND, + PyUnicode_READ, +) +from libc.stdint cimport uint8_t, uint64_t +from libc.string cimport memcpy, memset + +from string import ascii_letters, digits + + +cdef str GEN_DELIMS = ":/?#[]@" +cdef str SUB_DELIMS_WITHOUT_QS = "!$'()*," +cdef str SUB_DELIMS = SUB_DELIMS_WITHOUT_QS + '+?=;' +cdef str RESERVED = GEN_DELIMS + SUB_DELIMS +cdef str UNRESERVED = ascii_letters + digits + '-._~' +cdef str ALLOWED = UNRESERVED + SUB_DELIMS_WITHOUT_QS +cdef str QS = '+&=;' + +DEF BUF_SIZE = 8 * 1024 # 8KiB + +cdef inline Py_UCS4 _to_hex(uint8_t v) noexcept: + if v < 10: + return (v+0x30) # ord('0') == 0x30 + else: + return (v+0x41-10) # ord('A') == 0x41 + + +cdef inline int _from_hex(Py_UCS4 v) noexcept: + if '0' <= v <= '9': + return (v) - 0x30 # ord('0') == 0x30 + elif 'A' <= v <= 'F': + return (v) - 0x41 + 10 # ord('A') == 0x41 + elif 'a' <= v <= 'f': + return (v) - 0x61 + 10 # ord('a') == 0x61 + else: + return -1 + + +cdef inline int _is_lower_hex(Py_UCS4 v) noexcept: + return 'a' <= v <= 'f' + + +cdef inline long _restore_ch(Py_UCS4 d1, Py_UCS4 d2): + cdef int digit1 = _from_hex(d1) + if digit1 < 0: + return -1 + cdef int digit2 = _from_hex(d2) + if digit2 < 0: + return -1 + return digit1 << 4 | digit2 + + +cdef uint8_t ALLOWED_TABLE[16] +cdef uint8_t ALLOWED_NOTQS_TABLE[16] + + +cdef inline bint bit_at(uint8_t array[], uint64_t ch) noexcept: + return array[ch >> 3] & (1 << (ch & 7)) + + +cdef inline void set_bit(uint8_t array[], uint64_t ch) noexcept: + array[ch >> 3] |= (1 << (ch & 7)) + + +memset(ALLOWED_TABLE, 0, sizeof(ALLOWED_TABLE)) +memset(ALLOWED_NOTQS_TABLE, 0, sizeof(ALLOWED_NOTQS_TABLE)) + +for i in range(128): + if chr(i) in ALLOWED: + set_bit(ALLOWED_TABLE, i) + set_bit(ALLOWED_NOTQS_TABLE, i) + if chr(i) in QS: + set_bit(ALLOWED_NOTQS_TABLE, i) + +# ----------------- writer --------------------------- + +cdef struct Writer: + char *buf + bint heap_allocated_buf + Py_ssize_t size + Py_ssize_t pos + bint changed + + +cdef inline void _init_writer(Writer* writer, char* buf): + writer.buf = buf + writer.heap_allocated_buf = False + writer.size = BUF_SIZE + writer.pos = 0 + writer.changed = 0 + + +cdef inline void _release_writer(Writer* writer): + if writer.heap_allocated_buf: + PyMem_Free(writer.buf) + + +cdef inline int _write_char(Writer* writer, Py_UCS4 ch, bint changed): + cdef char * buf + cdef Py_ssize_t size + + if writer.pos == writer.size: + # reallocate + size = writer.size + BUF_SIZE + if not writer.heap_allocated_buf: + buf = PyMem_Malloc(size) + if buf == NULL: + PyErr_NoMemory() + return -1 + memcpy(buf, writer.buf, writer.size) + writer.heap_allocated_buf = True + else: + buf = PyMem_Realloc(writer.buf, size) + if buf == NULL: + PyErr_NoMemory() + return -1 + writer.buf = buf + writer.size = size + writer.buf[writer.pos] = ch + writer.pos += 1 + writer.changed |= changed + return 0 + + +cdef inline int _write_pct(Writer* writer, uint8_t ch, bint changed): + if _write_char(writer, '%', changed) < 0: + return -1 + if _write_char(writer, _to_hex(ch >> 4), changed) < 0: + return -1 + return _write_char(writer, _to_hex(ch & 0x0f), changed) + + +cdef inline int _write_utf8(Writer* writer, Py_UCS4 symbol): + cdef uint64_t utf = symbol + + if utf < 0x80: + return _write_pct(writer, utf, True) + elif utf < 0x800: + if _write_pct(writer, (0xc0 | (utf >> 6)), True) < 0: + return -1 + return _write_pct(writer, (0x80 | (utf & 0x3f)), True) + elif 0xD800 <= utf <= 0xDFFF: + # surogate pair, ignored + return 0 + elif utf < 0x10000: + if _write_pct(writer, (0xe0 | (utf >> 12)), True) < 0: + return -1 + if _write_pct(writer, (0x80 | ((utf >> 6) & 0x3f)), + True) < 0: + return -1 + return _write_pct(writer, (0x80 | (utf & 0x3f)), True) + elif utf > 0x10FFFF: + # symbol is too large + return 0 + else: + if _write_pct(writer, (0xf0 | (utf >> 18)), True) < 0: + return -1 + if _write_pct(writer, (0x80 | ((utf >> 12) & 0x3f)), + True) < 0: + return -1 + if _write_pct(writer, (0x80 | ((utf >> 6) & 0x3f)), + True) < 0: + return -1 + return _write_pct(writer, (0x80 | (utf & 0x3f)), True) + + +# --------------------- end writer -------------------------- + + +cdef class _Quoter: + cdef bint _qs + cdef bint _requote + + cdef uint8_t _safe_table[16] + cdef uint8_t _protected_table[16] + + def __init__( + self, *, str safe='', str protected='', bint qs=False, bint requote=True, + ): + cdef Py_UCS4 ch + + self._qs = qs + self._requote = requote + + if not self._qs: + memcpy(self._safe_table, + ALLOWED_NOTQS_TABLE, + sizeof(self._safe_table)) + else: + memcpy(self._safe_table, + ALLOWED_TABLE, + sizeof(self._safe_table)) + for ch in safe: + if ord(ch) > 127: + raise ValueError("Only safe symbols with ORD < 128 are allowed") + set_bit(self._safe_table, ch) + + memset(self._protected_table, 0, sizeof(self._protected_table)) + for ch in protected: + if ord(ch) > 127: + raise ValueError("Only safe symbols with ORD < 128 are allowed") + set_bit(self._safe_table, ch) + set_bit(self._protected_table, ch) + + def __call__(self, val): + if val is None: + return None + if type(val) is not str: + if isinstance(val, str): + # derived from str + val = str(val) + else: + raise TypeError("Argument should be str") + return self._do_quote_or_skip(val) + + cdef str _do_quote_or_skip(self, str val): + cdef char[BUF_SIZE] buffer + cdef Py_UCS4 ch + cdef Py_ssize_t length = PyUnicode_GET_LENGTH(val) + cdef Py_ssize_t idx = length + cdef bint must_quote = 0 + cdef Writer writer + cdef int kind = PyUnicode_KIND(val) + cdef const void *data = PyUnicode_DATA(val) + + # If everything in the string is in the safe + # table and all ASCII, we can skip quoting + while idx: + idx -= 1 + ch = PyUnicode_READ(kind, data, idx) + if ch >= 128 or not bit_at(self._safe_table, ch): + must_quote = 1 + break + + if not must_quote: + return val + + _init_writer(&writer, &buffer[0]) + try: + return self._do_quote(val, length, kind, data, &writer) + finally: + _release_writer(&writer) + + cdef str _do_quote( + self, + str val, + Py_ssize_t length, + int kind, + const void *data, + Writer *writer + ): + cdef Py_UCS4 ch + cdef long chl + cdef int changed + cdef Py_ssize_t idx = 0 + + while idx < length: + ch = PyUnicode_READ(kind, data, idx) + idx += 1 + if ch == '%' and self._requote and idx <= length - 2: + chl = _restore_ch( + PyUnicode_READ(kind, data, idx), + PyUnicode_READ(kind, data, idx + 1) + ) + if chl != -1: + ch = chl + idx += 2 + if ch < 128: + if bit_at(self._protected_table, ch): + if _write_pct(writer, ch, True) < 0: + raise + continue + + if bit_at(self._safe_table, ch): + if _write_char(writer, ch, True) < 0: + raise + continue + + changed = (_is_lower_hex(PyUnicode_READ(kind, data, idx - 2)) or + _is_lower_hex(PyUnicode_READ(kind, data, idx - 1))) + if _write_pct(writer, ch, changed) < 0: + raise + continue + else: + ch = '%' + + if self._write(writer, ch) < 0: + raise + + if not writer.changed: + return val + else: + return PyUnicode_DecodeASCII(writer.buf, writer.pos, "strict") + + cdef inline int _write(self, Writer *writer, Py_UCS4 ch): + if self._qs: + if ch == ' ': + return _write_char(writer, '+', True) + + if ch < 128 and bit_at(self._safe_table, ch): + return _write_char(writer, ch, False) + + return _write_utf8(writer, ch) + + +cdef class _Unquoter: + cdef str _ignore + cdef bint _has_ignore + cdef str _unsafe + cdef bytes _unsafe_bytes + cdef Py_ssize_t _unsafe_bytes_len + cdef const unsigned char * _unsafe_bytes_char + cdef bint _qs + cdef bint _plus # to match urllib.parse.unquote_plus + cdef _Quoter _quoter + cdef _Quoter _qs_quoter + + def __init__(self, *, ignore="", unsafe="", qs=False, plus=False): + self._ignore = ignore + self._has_ignore = bool(self._ignore) + self._unsafe = unsafe + # unsafe may only be extended ascii characters (0-255) + self._unsafe_bytes = self._unsafe.encode('ascii') + self._unsafe_bytes_len = len(self._unsafe_bytes) + self._unsafe_bytes_char = self._unsafe_bytes + self._qs = qs + self._plus = plus + self._quoter = _Quoter() + self._qs_quoter = _Quoter(qs=True) + + def __call__(self, val): + if val is None: + return None + if type(val) is not str: + if isinstance(val, str): + # derived from str + val = str(val) + else: + raise TypeError("Argument should be str") + return self._do_unquote(val) + + cdef str _do_unquote(self, str val): + cdef Py_ssize_t length = PyUnicode_GET_LENGTH(val) + if length == 0: + return val + + cdef list ret = [] + cdef char buffer[4] + cdef Py_ssize_t buflen = 0 + cdef Py_ssize_t consumed + cdef str unquoted + cdef Py_UCS4 ch = 0 + cdef long chl = 0 + cdef Py_ssize_t idx = 0 + cdef Py_ssize_t start_pct + cdef int kind = PyUnicode_KIND(val) + cdef const void *data = PyUnicode_DATA(val) + cdef bint changed = 0 + while idx < length: + ch = PyUnicode_READ(kind, data, idx) + idx += 1 + if ch == '%' and idx <= length - 2: + changed = 1 + chl = _restore_ch( + PyUnicode_READ(kind, data, idx), + PyUnicode_READ(kind, data, idx + 1) + ) + if chl != -1: + ch = chl + idx += 2 + assert buflen < 4 + buffer[buflen] = ch + buflen += 1 + try: + unquoted = PyUnicode_DecodeUTF8Stateful(buffer, buflen, + NULL, &consumed) + except UnicodeDecodeError: + start_pct = idx - buflen * 3 + buffer[0] = ch + buflen = 1 + ret.append(val[start_pct : idx - 3]) + try: + unquoted = PyUnicode_DecodeUTF8Stateful(buffer, buflen, + NULL, &consumed) + except UnicodeDecodeError: + buflen = 0 + ret.append(val[idx - 3 : idx]) + continue + if not unquoted: + assert consumed == 0 + continue + assert consumed == buflen + buflen = 0 + if self._qs and unquoted in '+=&;': + ret.append(self._qs_quoter(unquoted)) + elif ( + (self._unsafe_bytes_len and unquoted in self._unsafe) or + (self._has_ignore and unquoted in self._ignore) + ): + ret.append(self._quoter(unquoted)) + else: + ret.append(unquoted) + continue + else: + ch = '%' + + if buflen: + start_pct = idx - 1 - buflen * 3 + ret.append(val[start_pct : idx - 1]) + buflen = 0 + + if ch == '+': + if ( + (not self._qs and not self._plus) or + (self._unsafe_bytes_len and self._is_char_unsafe(ch)) + ): + ret.append('+') + else: + changed = 1 + ret.append(' ') + continue + + if self._unsafe_bytes_len and self._is_char_unsafe(ch): + changed = 1 + ret.append('%') + h = hex(ord(ch)).upper()[2:] + for ch in h: + ret.append(ch) + continue + + ret.append(ch) + + if not changed: + return val + + if buflen: + ret.append(val[length - buflen * 3 : length]) + + return ''.join(ret) + + cdef inline bint _is_char_unsafe(self, Py_UCS4 ch): + for i in range(self._unsafe_bytes_len): + if ch == self._unsafe_bytes_char[i]: + return True + return False diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_quoting_py.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_quoting_py.py new file mode 100644 index 0000000000000000000000000000000000000000..98197aa98db038ade28f206f8d71a1f68d0b9124 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_quoting_py.py @@ -0,0 +1,213 @@ +import codecs +import re +from string import ascii_letters, ascii_lowercase, digits +from typing import overload + +BASCII_LOWERCASE = ascii_lowercase.encode("ascii") +BPCT_ALLOWED = {f"%{i:02X}".encode("ascii") for i in range(256)} +GEN_DELIMS = ":/?#[]@" +SUB_DELIMS_WITHOUT_QS = "!$'()*," +SUB_DELIMS = SUB_DELIMS_WITHOUT_QS + "+&=;" +RESERVED = GEN_DELIMS + SUB_DELIMS +UNRESERVED = ascii_letters + digits + "-._~" +ALLOWED = UNRESERVED + SUB_DELIMS_WITHOUT_QS + + +_IS_HEX = re.compile(b"[A-Z0-9][A-Z0-9]") +_IS_HEX_STR = re.compile("[A-Fa-f0-9][A-Fa-f0-9]") + +utf8_decoder = codecs.getincrementaldecoder("utf-8") + + +class _Quoter: + def __init__( + self, + *, + safe: str = "", + protected: str = "", + qs: bool = False, + requote: bool = True, + ) -> None: + self._safe = safe + self._protected = protected + self._qs = qs + self._requote = requote + + @overload + def __call__(self, val: str) -> str: ... + @overload + def __call__(self, val: None) -> None: ... + def __call__(self, val: str | None) -> str | None: + if val is None: + return None + if not isinstance(val, str): + raise TypeError("Argument should be str") + if not val: + return "" + bval = val.encode("utf8", errors="ignore") + ret = bytearray() + pct = bytearray() + safe = self._safe + safe += ALLOWED + if not self._qs: + safe += "+&=;" + safe += self._protected + bsafe = safe.encode("ascii") + idx = 0 + while idx < len(bval): + ch = bval[idx] + idx += 1 + + if pct: + if ch in BASCII_LOWERCASE: + ch = ch - 32 # convert to uppercase + pct.append(ch) + if len(pct) == 3: # pragma: no branch # peephole optimizer + buf = pct[1:] + if not _IS_HEX.match(buf): + ret.extend(b"%25") + pct.clear() + idx -= 2 + continue + try: + unquoted = chr(int(pct[1:].decode("ascii"), base=16)) + except ValueError: + ret.extend(b"%25") + pct.clear() + idx -= 2 + continue + + if unquoted in self._protected: + ret.extend(pct) + elif unquoted in safe: + ret.append(ord(unquoted)) + else: + ret.extend(pct) + pct.clear() + + # special case, if we have only one char after "%" + elif len(pct) == 2 and idx == len(bval): + ret.extend(b"%25") + pct.clear() + idx -= 1 + + continue + + elif ch == ord("%") and self._requote: + pct.clear() + pct.append(ch) + + # special case if "%" is last char + if idx == len(bval): + ret.extend(b"%25") + + continue + + if self._qs and ch == ord(" "): + ret.append(ord("+")) + continue + if ch in bsafe: + ret.append(ch) + continue + + ret.extend((f"%{ch:02X}").encode("ascii")) + + ret2 = ret.decode("ascii") + if ret2 == val: + return val + return ret2 + + +class _Unquoter: + def __init__( + self, + *, + ignore: str = "", + unsafe: str = "", + qs: bool = False, + plus: bool = False, + ) -> None: + self._ignore = ignore + self._unsafe = unsafe + self._qs = qs + self._plus = plus # to match urllib.parse.unquote_plus + self._quoter = _Quoter() + self._qs_quoter = _Quoter(qs=True) + + @overload + def __call__(self, val: str) -> str: ... + @overload + def __call__(self, val: None) -> None: ... + def __call__(self, val: str | None) -> str | None: + if val is None: + return None + if not isinstance(val, str): + raise TypeError("Argument should be str") + if not val: + return "" + decoder = utf8_decoder() + ret = [] + idx = 0 + while idx < len(val): + ch = val[idx] + idx += 1 + if ch == "%" and idx <= len(val) - 2: + pct = val[idx : idx + 2] + if _IS_HEX_STR.fullmatch(pct): + b = bytes([int(pct, base=16)]) + idx += 2 + try: + unquoted = decoder.decode(b) + except UnicodeDecodeError: + start_pct = idx - 3 - len(decoder.buffer) * 3 + ret.append(val[start_pct : idx - 3]) + decoder.reset() + try: + unquoted = decoder.decode(b) + except UnicodeDecodeError: + ret.append(val[idx - 3 : idx]) + continue + if not unquoted: + continue + if self._qs and unquoted in "+=&;": + to_add = self._qs_quoter(unquoted) + if to_add is None: # pragma: no cover + raise RuntimeError("Cannot quote None") + ret.append(to_add) + elif unquoted in self._unsafe or unquoted in self._ignore: + to_add = self._quoter(unquoted) + if to_add is None: # pragma: no cover + raise RuntimeError("Cannot quote None") + ret.append(to_add) + else: + ret.append(unquoted) + continue + + if decoder.buffer: + start_pct = idx - 1 - len(decoder.buffer) * 3 + ret.append(val[start_pct : idx - 1]) + decoder.reset() + + if ch == "+": + if (not self._qs and not self._plus) or ch in self._unsafe: + ret.append("+") + else: + ret.append(" ") + continue + + if ch in self._unsafe: + ret.append("%") + h = hex(ord(ch)).upper()[2:] + for ch in h: + ret.append(ch) + continue + + ret.append(ch) + + if decoder.buffer: + ret.append(val[-len(decoder.buffer) * 3 :]) + + ret2 = "".join(ret) + if ret2 == val: + return val + return ret2 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_url.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_url.py new file mode 100644 index 0000000000000000000000000000000000000000..75043d52185a9b52191330d43ae9646cbbb06d42 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/_url.py @@ -0,0 +1,1665 @@ +import re +import sys +import warnings +from collections.abc import Mapping, Sequence +from enum import Enum +from functools import _CacheInfo, lru_cache +from ipaddress import ip_address +from typing import ( + TYPE_CHECKING, + Any, + NoReturn, + TypedDict, + TypeVar, + Union, + cast, + overload, +) +from urllib.parse import SplitResult, uses_relative + +import idna +from multidict import MultiDict, MultiDictProxy, istr +from propcache.api import under_cached_property as cached_property + +from ._parse import ( + USES_AUTHORITY, + SplitURLType, + make_netloc, + query_to_pairs, + split_netloc, + split_url, + unsplit_result, +) +from ._path import normalize_path, normalize_path_segments +from ._query import ( + Query, + QueryVariable, + SimpleQuery, + get_str_query, + get_str_query_from_iterable, + get_str_query_from_sequence_iterable, +) +from ._quoters import ( + FRAGMENT_QUOTER, + FRAGMENT_REQUOTER, + PATH_QUOTER, + PATH_REQUOTER, + PATH_SAFE_UNQUOTER, + PATH_UNQUOTER, + QS_UNQUOTER, + QUERY_QUOTER, + QUERY_REQUOTER, + QUOTER, + REQUOTER, + UNQUOTER, + human_quote, +) + +try: + from pydantic import GetCoreSchemaHandler, GetJsonSchemaHandler + from pydantic.json_schema import JsonSchemaValue + from pydantic_core import core_schema + + HAS_PYDANTIC = True +except ImportError: + HAS_PYDANTIC = False + + +DEFAULT_PORTS = {"http": 80, "https": 443, "ws": 80, "wss": 443, "ftp": 21} +USES_RELATIVE = frozenset(uses_relative) + +# Special schemes https://url.spec.whatwg.org/#special-scheme +# are not allowed to have an empty host https://url.spec.whatwg.org/#url-representation +SCHEME_REQUIRES_HOST = frozenset(("http", "https", "ws", "wss", "ftp")) + + +# reg-name: unreserved / pct-encoded / sub-delims +# this pattern matches anything that is *not* in those classes. and is only used +# on lower-cased ASCII values. +NOT_REG_NAME = re.compile( + r""" + # any character not in the unreserved or sub-delims sets, plus % + # (validated with the additional check for pct-encoded sequences below) + [^a-z0-9\-._~!$&'()*+,;=%] + | + # % only allowed if it is part of a pct-encoded + # sequence of 2 hex digits. + %(?![0-9a-f]{2}) + """, + re.VERBOSE, +) + +_T = TypeVar("_T") + +if sys.version_info >= (3, 11): + from typing import Self +else: + Self = Any + + +class UndefinedType(Enum): + """Singleton type for use with not set sentinel values.""" + + _singleton = 0 + + +UNDEFINED = UndefinedType._singleton + + +class CacheInfo(TypedDict): + """Host encoding cache.""" + + idna_encode: _CacheInfo + idna_decode: _CacheInfo + ip_address: _CacheInfo + host_validate: _CacheInfo + encode_host: _CacheInfo + + +class _InternalURLCache(TypedDict, total=False): + _val: SplitURLType + _origin: "URL" + absolute: bool + hash: int + scheme: str + raw_authority: str + authority: str + raw_user: str | None + user: str | None + raw_password: str | None + password: str | None + raw_host: str | None + host: str | None + host_subcomponent: str | None + host_port_subcomponent: str | None + port: int | None + explicit_port: int | None + raw_path: str + path: str + _parsed_query: list[tuple[str, str]] + query: "MultiDictProxy[str]" + raw_query_string: str + query_string: str + path_qs: str + raw_path_qs: str + raw_fragment: str + fragment: str + raw_parts: tuple[str, ...] + parts: tuple[str, ...] + parent: "URL" + raw_name: str + name: str + raw_suffix: str + suffix: str + raw_suffixes: tuple[str, ...] + suffixes: tuple[str, ...] + + +def rewrite_module(obj: _T) -> _T: + obj.__module__ = "yarl" + return obj + + +@lru_cache +def encode_url(url_str: str) -> "URL": + """Parse unencoded URL.""" + cache: _InternalURLCache = {} + host: str | None + scheme, netloc, path, query, fragment = split_url(url_str) + if not netloc: # netloc + host = "" + else: + if ":" in netloc or "@" in netloc or "[" in netloc: + # Complex netloc + username, password, host, port = split_netloc(netloc) + else: + username = password = port = None + host = netloc + if host is None: + if scheme in SCHEME_REQUIRES_HOST: + msg = ( + "Invalid URL: host is required for " + f"absolute urls with the {scheme} scheme" + ) + raise ValueError(msg) + else: + host = "" + host = _encode_host(host, validate_host=False) + # Remove brackets as host encoder adds back brackets for IPv6 addresses + cache["raw_host"] = host[1:-1] if "[" in host else host + cache["explicit_port"] = port + if password is None and username is None: + # Fast path for URLs without user, password + netloc = host if port is None else f"{host}:{port}" + cache["raw_user"] = None + cache["raw_password"] = None + else: + raw_user = REQUOTER(username) if username else username + raw_password = REQUOTER(password) if password else password + netloc = make_netloc(raw_user, raw_password, host, port) + cache["raw_user"] = raw_user + cache["raw_password"] = raw_password + + if path: + path = PATH_REQUOTER(path) + if netloc and "." in path: + path = normalize_path(path) + if query: + query = QUERY_REQUOTER(query) + if fragment: + fragment = FRAGMENT_REQUOTER(fragment) + + cache["scheme"] = scheme + cache["raw_path"] = "/" if not path and netloc else path + cache["raw_query_string"] = query + cache["raw_fragment"] = fragment + + self = object.__new__(URL) + self._scheme = scheme + self._netloc = netloc + self._path = path + self._query = query + self._fragment = fragment + self._cache = cache + return self + + +@lru_cache +def pre_encoded_url(url_str: str) -> "URL": + """Parse pre-encoded URL.""" + self = object.__new__(URL) + val = split_url(url_str) + self._scheme, self._netloc, self._path, self._query, self._fragment = val + self._cache = {} + return self + + +@lru_cache +def build_pre_encoded_url( + scheme: str, + authority: str, + user: str | None, + password: str | None, + host: str, + port: int | None, + path: str, + query_string: str, + fragment: str, +) -> "URL": + """Build a pre-encoded URL from parts.""" + self = object.__new__(URL) + self._scheme = scheme + if authority: + self._netloc = authority + elif host: + if port is not None: + port = None if port == DEFAULT_PORTS.get(scheme) else port + if user is None and password is None: + self._netloc = host if port is None else f"{host}:{port}" + else: + self._netloc = make_netloc(user, password, host, port) + else: + self._netloc = "" + self._path = path + self._query = query_string + self._fragment = fragment + self._cache = {} + return self + + +def from_parts_uncached( + scheme: str, netloc: str, path: str, query: str, fragment: str +) -> "URL": + """Create a new URL from parts.""" + self = object.__new__(URL) + self._scheme = scheme + self._netloc = netloc + self._path = path + self._query = query + self._fragment = fragment + self._cache = {} + return self + + +from_parts = lru_cache(from_parts_uncached) + + +@rewrite_module +class URL: + # Don't derive from str + # follow pathlib.Path design + # probably URL will not suffer from pathlib problems: + # it's intended for libraries like aiohttp, + # not to be passed into standard library functions like os.open etc. + + # URL grammar (RFC 3986) + # pct-encoded = "%" HEXDIG HEXDIG + # reserved = gen-delims / sub-delims + # gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@" + # sub-delims = "!" / "$" / "&" / "'" / "(" / ")" + # / "*" / "+" / "," / ";" / "=" + # unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" + # URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ] + # hier-part = "//" authority path-abempty + # / path-absolute + # / path-rootless + # / path-empty + # scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) + # authority = [ userinfo "@" ] host [ ":" port ] + # userinfo = *( unreserved / pct-encoded / sub-delims / ":" ) + # host = IP-literal / IPv4address / reg-name + # IP-literal = "[" ( IPv6address / IPvFuture ) "]" + # IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" ) + # IPv6address = 6( h16 ":" ) ls32 + # / "::" 5( h16 ":" ) ls32 + # / [ h16 ] "::" 4( h16 ":" ) ls32 + # / [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + # / [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + # / [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + # / [ *4( h16 ":" ) h16 ] "::" ls32 + # / [ *5( h16 ":" ) h16 ] "::" h16 + # / [ *6( h16 ":" ) h16 ] "::" + # ls32 = ( h16 ":" h16 ) / IPv4address + # ; least-significant 32 bits of address + # h16 = 1*4HEXDIG + # ; 16 bits of address represented in hexadecimal + # IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet + # dec-octet = DIGIT ; 0-9 + # / %x31-39 DIGIT ; 10-99 + # / "1" 2DIGIT ; 100-199 + # / "2" %x30-34 DIGIT ; 200-249 + # / "25" %x30-35 ; 250-255 + # reg-name = *( unreserved / pct-encoded / sub-delims ) + # port = *DIGIT + # path = path-abempty ; begins with "/" or is empty + # / path-absolute ; begins with "/" but not "//" + # / path-noscheme ; begins with a non-colon segment + # / path-rootless ; begins with a segment + # / path-empty ; zero characters + # path-abempty = *( "/" segment ) + # path-absolute = "/" [ segment-nz *( "/" segment ) ] + # path-noscheme = segment-nz-nc *( "/" segment ) + # path-rootless = segment-nz *( "/" segment ) + # path-empty = 0 + # segment = *pchar + # segment-nz = 1*pchar + # segment-nz-nc = 1*( unreserved / pct-encoded / sub-delims / "@" ) + # ; non-zero-length segment without any colon ":" + # pchar = unreserved / pct-encoded / sub-delims / ":" / "@" + # query = *( pchar / "/" / "?" ) + # fragment = *( pchar / "/" / "?" ) + # URI-reference = URI / relative-ref + # relative-ref = relative-part [ "?" query ] [ "#" fragment ] + # relative-part = "//" authority path-abempty + # / path-absolute + # / path-noscheme + # / path-empty + # absolute-URI = scheme ":" hier-part [ "?" query ] + __slots__ = ("_cache", "_scheme", "_netloc", "_path", "_query", "_fragment") + + _cache: _InternalURLCache + _scheme: str + _netloc: str + _path: str + _query: str + _fragment: str + + def __new__( + cls, + val: Union[str, SplitResult, "URL", UndefinedType] = UNDEFINED, + *, + encoded: bool = False, + strict: bool | None = None, + ) -> "URL": + if strict is not None: # pragma: no cover + warnings.warn("strict parameter is ignored") + if type(val) is str: + return pre_encoded_url(val) if encoded else encode_url(val) + if type(val) is cls: + return val + if type(val) is SplitResult: + if not encoded: + raise ValueError("Cannot apply decoding to SplitResult") + return from_parts(*val) + if isinstance(val, str): + return pre_encoded_url(str(val)) if encoded else encode_url(str(val)) + if val is UNDEFINED: + # Special case for UNDEFINED since it might be unpickling and we do + # not want to cache as the `__set_state__` call would mutate the URL + # object in the `pre_encoded_url` or `encoded_url` caches. + self = object.__new__(URL) + self._scheme = self._netloc = self._path = self._query = self._fragment = "" + self._cache = {} + return self + raise TypeError("Constructor parameter should be str") + + @classmethod + def build( + cls, + *, + scheme: str = "", + authority: str = "", + user: str | None = None, + password: str | None = None, + host: str = "", + port: int | None = None, + path: str = "", + query: Query | None = None, + query_string: str = "", + fragment: str = "", + encoded: bool = False, + ) -> "URL": + """Creates and returns a new URL""" + + if authority and (user or password or host or port): + raise ValueError( + 'Can\'t mix "authority" with "user", "password", "host" or "port".' + ) + if port is not None and not isinstance(port, int): + raise TypeError(f"The port is required to be int, got {type(port)!r}.") + if port and not host: + raise ValueError('Can\'t build URL with "port" but without "host".') + if query and query_string: + raise ValueError('Only one of "query" or "query_string" should be passed') + if ( + scheme is None # type: ignore[redundant-expr] + or authority is None # type: ignore[redundant-expr] + or host is None # type: ignore[redundant-expr] + or path is None # type: ignore[redundant-expr] + or query_string is None # type: ignore[redundant-expr] + or fragment is None + ): + raise TypeError( + 'NoneType is illegal for "scheme", "authority", "host", "path", ' + '"query_string", and "fragment" args, use empty string instead.' + ) + + if query: + query_string = get_str_query(query) or "" + + if encoded: + return build_pre_encoded_url( + scheme, + authority, + user, + password, + host, + port, + path, + query_string, + fragment, + ) + + self = object.__new__(URL) + self._scheme = scheme + _host: str | None = None + if authority: + user, password, _host, port = split_netloc(authority) + _host = _encode_host(_host, validate_host=False) if _host else "" + elif host: + _host = _encode_host(host, validate_host=True) + else: + self._netloc = "" + + if _host is not None: + if port is not None: + port = None if port == DEFAULT_PORTS.get(scheme) else port + if user is None and password is None: + self._netloc = _host if port is None else f"{_host}:{port}" + else: + self._netloc = make_netloc(user, password, _host, port, True) + + path = PATH_QUOTER(path) if path else path + if path and self._netloc: + if "." in path: + path = normalize_path(path) + if path[0] != "/": + msg = ( + "Path in a URL with authority should " + "start with a slash ('/') if set" + ) + raise ValueError(msg) + + self._path = path + if not query and query_string: + query_string = QUERY_QUOTER(query_string) + self._query = query_string + self._fragment = FRAGMENT_QUOTER(fragment) if fragment else fragment + self._cache = {} + return self + + def __init_subclass__(cls) -> NoReturn: + raise TypeError(f"Inheriting a class {cls!r} from URL is forbidden") + + def __str__(self) -> str: + if not self._path and self._netloc and (self._query or self._fragment): + path = "/" + else: + path = self._path + if (port := self.explicit_port) is not None and port == DEFAULT_PORTS.get( + self._scheme + ): + # port normalization - using None for default ports to remove from rendering + # https://datatracker.ietf.org/doc/html/rfc3986.html#section-6.2.3 + host = self.host_subcomponent + netloc = make_netloc(self.raw_user, self.raw_password, host, None) + else: + netloc = self._netloc + return unsplit_result(self._scheme, netloc, path, self._query, self._fragment) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}('{str(self)}')" + + def __bytes__(self) -> bytes: + return str(self).encode("ascii") + + def __eq__(self, other: object) -> bool: + if type(other) is not URL: + return NotImplemented + + path1 = "/" if not self._path and self._netloc else self._path + path2 = "/" if not other._path and other._netloc else other._path + return ( + self._scheme == other._scheme + and self._netloc == other._netloc + and path1 == path2 + and self._query == other._query + and self._fragment == other._fragment + ) + + def __hash__(self) -> int: + if (ret := self._cache.get("hash")) is None: + path = "/" if not self._path and self._netloc else self._path + ret = self._cache["hash"] = hash( + (self._scheme, self._netloc, path, self._query, self._fragment) + ) + return ret + + def __le__(self, other: object) -> bool: + if type(other) is not URL: + return NotImplemented + return self._val <= other._val + + def __lt__(self, other: object) -> bool: + if type(other) is not URL: + return NotImplemented + return self._val < other._val + + def __ge__(self, other: object) -> bool: + if type(other) is not URL: + return NotImplemented + return self._val >= other._val + + def __gt__(self, other: object) -> bool: + if type(other) is not URL: + return NotImplemented + return self._val > other._val + + def __truediv__(self, name: str) -> "URL": + if not isinstance(name, str): + return NotImplemented # type: ignore[unreachable] + return self._make_child((str(name),)) + + def __mod__(self, query: Query) -> "URL": + return self.update_query(query) + + def __bool__(self) -> bool: + return bool(self._netloc or self._path or self._query or self._fragment) + + def __getstate__(self) -> tuple[SplitResult]: + return (tuple.__new__(SplitResult, self._val),) + + def __setstate__( + self, state: tuple[SplitURLType] | tuple[None, _InternalURLCache] + ) -> None: + if state[0] is None and isinstance(state[1], dict): + # default style pickle + val = state[1]["_val"] + else: + unused: list[object] + val, *unused = state + self._scheme, self._netloc, self._path, self._query, self._fragment = val + self._cache = {} + + def _cache_netloc(self) -> None: + """Cache the netloc parts of the URL.""" + c = self._cache + split_loc = split_netloc(self._netloc) + c["raw_user"], c["raw_password"], c["raw_host"], c["explicit_port"] = split_loc + + def is_absolute(self) -> bool: + """A check for absolute URLs. + + Return True for absolute ones (having scheme or starting + with //), False otherwise. + + Is is preferred to call the .absolute property instead + as it is cached. + """ + return self.absolute + + def is_default_port(self) -> bool: + """A check for default port. + + Return True if port is default for specified scheme, + e.g. 'http://python.org' or 'http://python.org:80', False + otherwise. + + Return False for relative URLs. + + """ + if (explicit := self.explicit_port) is None: + # If the explicit port is None, then the URL must be + # using the default port unless its a relative URL + # which does not have an implicit port / default port + return self._netloc != "" + return explicit == DEFAULT_PORTS.get(self._scheme) + + def origin(self) -> "URL": + """Return an URL with scheme, host and port parts only. + + user, password, path, query and fragment are removed. + + """ + # TODO: add a keyword-only option for keeping user/pass maybe? + return self._origin + + @cached_property + def _val(self) -> SplitURLType: + return (self._scheme, self._netloc, self._path, self._query, self._fragment) + + @cached_property + def _origin(self) -> "URL": + """Return an URL with scheme, host and port parts only. + + user, password, path, query and fragment are removed. + """ + if not (netloc := self._netloc): + raise ValueError("URL should be absolute") + if not (scheme := self._scheme): + raise ValueError("URL should have scheme") + if "@" in netloc: + encoded_host = self.host_subcomponent + netloc = make_netloc(None, None, encoded_host, self.explicit_port) + elif not self._path and not self._query and not self._fragment: + return self + return from_parts(scheme, netloc, "", "", "") + + def relative(self) -> "URL": + """Return a relative part of the URL. + + scheme, user, password, host and port are removed. + + """ + if not self._netloc: + raise ValueError("URL should be absolute") + return from_parts("", "", self._path, self._query, self._fragment) + + @cached_property + def absolute(self) -> bool: + """A check for absolute URLs. + + Return True for absolute ones (having scheme or starting + with //), False otherwise. + + """ + # `netloc`` is an empty string for relative URLs + # Checking `netloc` is faster than checking `hostname` + # because `hostname` is a property that does some extra work + # to parse the host from the `netloc` + return self._netloc != "" + + @cached_property + def scheme(self) -> str: + """Scheme for absolute URLs. + + Empty string for relative URLs or URLs starting with // + + """ + return self._scheme + + @cached_property + def raw_authority(self) -> str: + """Encoded authority part of URL. + + Empty string for relative URLs. + + """ + return self._netloc + + @cached_property + def authority(self) -> str: + """Decoded authority part of URL. + + Empty string for relative URLs. + + """ + return make_netloc(self.user, self.password, self.host, self.port) + + @cached_property + def raw_user(self) -> str | None: + """Encoded user part of URL. + + None if user is missing. + + """ + # not .username + self._cache_netloc() + return self._cache["raw_user"] + + @cached_property + def user(self) -> str | None: + """Decoded user part of URL. + + None if user is missing. + + """ + if (raw_user := self.raw_user) is None: + return None + return UNQUOTER(raw_user) + + @cached_property + def raw_password(self) -> str | None: + """Encoded password part of URL. + + None if password is missing. + + """ + self._cache_netloc() + return self._cache["raw_password"] + + @cached_property + def password(self) -> str | None: + """Decoded password part of URL. + + None if password is missing. + + """ + if (raw_password := self.raw_password) is None: + return None + return UNQUOTER(raw_password) + + @cached_property + def raw_host(self) -> str | None: + """Encoded host part of URL. + + None for relative URLs. + + When working with IPv6 addresses, use the `host_subcomponent` property instead + as it will return the host subcomponent with brackets. + """ + # Use host instead of hostname for sake of shortness + # May add .hostname prop later + self._cache_netloc() + return self._cache["raw_host"] + + @cached_property + def host(self) -> str | None: + """Decoded host part of URL. + + None for relative URLs. + + """ + if (raw := self.raw_host) is None: + return None + if raw and raw[-1].isdigit() or ":" in raw: + # IP addresses are never IDNA encoded + return raw + return _idna_decode(raw) + + @cached_property + def host_subcomponent(self) -> str | None: + """Return the host subcomponent part of URL. + + None for relative URLs. + + https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.2 + + `IP-literal = "[" ( IPv6address / IPvFuture ) "]"` + + Examples: + - `http://example.com:8080` -> `example.com` + - `http://example.com:80` -> `example.com` + - `https://127.0.0.1:8443` -> `127.0.0.1` + - `https://[::1]:8443` -> `[::1]` + - `http://[::1]` -> `[::1]` + + """ + if (raw := self.raw_host) is None: + return None + return f"[{raw}]" if ":" in raw else raw + + @cached_property + def host_port_subcomponent(self) -> str | None: + """Return the host and port subcomponent part of URL. + + Trailing dots are removed from the host part. + + This value is suitable for use in the Host header of an HTTP request. + + None for relative URLs. + + https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.2 + `IP-literal = "[" ( IPv6address / IPvFuture ) "]"` + https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.3 + port = *DIGIT + + Examples: + - `http://example.com:8080` -> `example.com:8080` + - `http://example.com:80` -> `example.com` + - `http://example.com.:80` -> `example.com` + - `https://127.0.0.1:8443` -> `127.0.0.1:8443` + - `https://[::1]:8443` -> `[::1]:8443` + - `http://[::1]` -> `[::1]` + + """ + if (raw := self.raw_host) is None: + return None + if raw[-1] == ".": + # Remove all trailing dots from the netloc as while + # they are valid FQDNs in DNS, TLS validation fails. + # See https://github.com/aio-libs/aiohttp/issues/3636. + # To avoid string manipulation we only call rstrip if + # the last character is a dot. + raw = raw.rstrip(".") + port = self.explicit_port + if port is None or port == DEFAULT_PORTS.get(self._scheme): + return f"[{raw}]" if ":" in raw else raw + return f"[{raw}]:{port}" if ":" in raw else f"{raw}:{port}" + + @cached_property + def port(self) -> int | None: + """Port part of URL, with scheme-based fallback. + + None for relative URLs or URLs without explicit port and + scheme without default port substitution. + + """ + if (explicit_port := self.explicit_port) is not None: + return explicit_port + return DEFAULT_PORTS.get(self._scheme) + + @cached_property + def explicit_port(self) -> int | None: + """Port part of URL, without scheme-based fallback. + + None for relative URLs or URLs without explicit port. + + """ + self._cache_netloc() + return self._cache["explicit_port"] + + @cached_property + def raw_path(self) -> str: + """Encoded path of URL. + + / for absolute URLs without path part. + + """ + return self._path if self._path or not self._netloc else "/" + + @cached_property + def path(self) -> str: + """Decoded path of URL. + + / for absolute URLs without path part. + + """ + return PATH_UNQUOTER(self._path) if self._path else "/" if self._netloc else "" + + @cached_property + def path_safe(self) -> str: + """Decoded path of URL. + + / for absolute URLs without path part. + + / (%2F) and % (%25) are not decoded + + """ + if self._path: + return PATH_SAFE_UNQUOTER(self._path) + return "/" if self._netloc else "" + + @cached_property + def _parsed_query(self) -> list[tuple[str, str]]: + """Parse query part of URL.""" + return query_to_pairs(self._query) + + @cached_property + def query(self) -> "MultiDictProxy[str]": + """A MultiDictProxy representing parsed query parameters in decoded + representation. + + Empty value if URL has no query part. + + """ + return MultiDictProxy(MultiDict(self._parsed_query)) + + @cached_property + def raw_query_string(self) -> str: + """Encoded query part of URL. + + Empty string if query is missing. + + """ + return self._query + + @cached_property + def query_string(self) -> str: + """Decoded query part of URL. + + Empty string if query is missing. + + """ + return QS_UNQUOTER(self._query) if self._query else "" + + @cached_property + def path_qs(self) -> str: + """Decoded path of URL with query.""" + return self.path if not (q := self.query_string) else f"{self.path}?{q}" + + @cached_property + def raw_path_qs(self) -> str: + """Encoded path of URL with query.""" + if q := self._query: + return f"{self._path}?{q}" if self._path or not self._netloc else f"/?{q}" + return self._path if self._path or not self._netloc else "/" + + @cached_property + def raw_fragment(self) -> str: + """Encoded fragment part of URL. + + Empty string if fragment is missing. + + """ + return self._fragment + + @cached_property + def fragment(self) -> str: + """Decoded fragment part of URL. + + Empty string if fragment is missing. + + """ + return UNQUOTER(self._fragment) if self._fragment else "" + + @cached_property + def raw_parts(self) -> tuple[str, ...]: + """A tuple containing encoded *path* parts. + + ('/',) for absolute URLs if *path* is missing. + + """ + path = self._path + if self._netloc: + return ("/", *path[1:].split("/")) if path else ("/",) + if path and path[0] == "/": + return ("/", *path[1:].split("/")) + return tuple(path.split("/")) + + @cached_property + def parts(self) -> tuple[str, ...]: + """A tuple containing decoded *path* parts. + + ('/',) for absolute URLs if *path* is missing. + + """ + return tuple(UNQUOTER(part) for part in self.raw_parts) + + @cached_property + def parent(self) -> "URL": + """A new URL with last part of path removed and cleaned up query and + fragment. + + """ + path = self._path + if not path or path == "/": + if self._fragment or self._query: + return from_parts(self._scheme, self._netloc, path, "", "") + return self + parts = path.split("/") + return from_parts(self._scheme, self._netloc, "/".join(parts[:-1]), "", "") + + @cached_property + def raw_name(self) -> str: + """The last part of raw_parts.""" + parts = self.raw_parts + if not self._netloc: + return parts[-1] + parts = parts[1:] + return parts[-1] if parts else "" + + @cached_property + def name(self) -> str: + """The last part of parts.""" + return UNQUOTER(self.raw_name) + + @cached_property + def raw_suffix(self) -> str: + name = self.raw_name + i = name.rfind(".") + return name[i:] if 0 < i < len(name) - 1 else "" + + @cached_property + def suffix(self) -> str: + return UNQUOTER(self.raw_suffix) + + @cached_property + def raw_suffixes(self) -> tuple[str, ...]: + name = self.raw_name + if name.endswith("."): + return () + name = name.lstrip(".") + return tuple("." + suffix for suffix in name.split(".")[1:]) + + @cached_property + def suffixes(self) -> tuple[str, ...]: + return tuple(UNQUOTER(suffix) for suffix in self.raw_suffixes) + + def _make_child(self, paths: "Sequence[str]", encoded: bool = False) -> "URL": + """ + add paths to self._path, accounting for absolute vs relative paths, + keep existing, but do not create new, empty segments + """ + parsed: list[str] = [] + needs_normalize: bool = False + for idx, path in enumerate(reversed(paths)): + # empty segment of last is not removed + last = idx == 0 + if path and path[0] == "/": + raise ValueError( + f"Appending path {path!r} starting from slash is forbidden" + ) + # We need to quote the path if it is not already encoded + # This cannot be done at the end because the existing + # path is already quoted and we do not want to double quote + # the existing path. + path = path if encoded else PATH_QUOTER(path) + needs_normalize |= "." in path + segments = path.split("/") + segments.reverse() + # remove trailing empty segment for all but the last path + parsed += segments[1:] if not last and segments[0] == "" else segments + + if (path := self._path) and (old_segments := path.split("/")): + # If the old path ends with a slash, the last segment is an empty string + # and should be removed before adding the new path segments. + old = old_segments[:-1] if old_segments[-1] == "" else old_segments + old.reverse() + parsed += old + + # If the netloc is present, inject a leading slash when adding a + # path to an absolute URL where there was none before. + if (netloc := self._netloc) and parsed and parsed[-1] != "": + parsed.append("") + + parsed.reverse() + if not netloc or not needs_normalize: + return from_parts(self._scheme, netloc, "/".join(parsed), "", "") + + path = "/".join(normalize_path_segments(parsed)) + # If normalizing the path segments removed the leading slash, add it back. + if path and path[0] != "/": + path = f"/{path}" + return from_parts(self._scheme, netloc, path, "", "") + + def with_scheme(self, scheme: str) -> "URL": + """Return a new URL with scheme replaced.""" + # N.B. doesn't cleanup query/fragment + if not isinstance(scheme, str): + raise TypeError("Invalid scheme type") + lower_scheme = scheme.lower() + netloc = self._netloc + if not netloc and lower_scheme in SCHEME_REQUIRES_HOST: + msg = ( + "scheme replacement is not allowed for " + f"relative URLs for the {lower_scheme} scheme" + ) + raise ValueError(msg) + return from_parts(lower_scheme, netloc, self._path, self._query, self._fragment) + + def with_user(self, user: str | None) -> "URL": + """Return a new URL with user replaced. + + Autoencode user if needed. + + Clear user/password if user is None. + + """ + # N.B. doesn't cleanup query/fragment + if user is None: + password = None + elif isinstance(user, str): + user = QUOTER(user) + password = self.raw_password + else: + raise TypeError("Invalid user type") + if not (netloc := self._netloc): + raise ValueError("user replacement is not allowed for relative URLs") + encoded_host = self.host_subcomponent or "" + netloc = make_netloc(user, password, encoded_host, self.explicit_port) + return from_parts(self._scheme, netloc, self._path, self._query, self._fragment) + + def with_password(self, password: str | None) -> "URL": + """Return a new URL with password replaced. + + Autoencode password if needed. + + Clear password if argument is None. + + """ + # N.B. doesn't cleanup query/fragment + if password is None: + pass + elif isinstance(password, str): + password = QUOTER(password) + else: + raise TypeError("Invalid password type") + if not (netloc := self._netloc): + raise ValueError("password replacement is not allowed for relative URLs") + encoded_host = self.host_subcomponent or "" + port = self.explicit_port + netloc = make_netloc(self.raw_user, password, encoded_host, port) + return from_parts(self._scheme, netloc, self._path, self._query, self._fragment) + + def with_host(self, host: str) -> "URL": + """Return a new URL with host replaced. + + Autoencode host if needed. + + Changing host for relative URLs is not allowed, use .join() + instead. + + """ + # N.B. doesn't cleanup query/fragment + if not isinstance(host, str): + raise TypeError("Invalid host type") + if not (netloc := self._netloc): + raise ValueError("host replacement is not allowed for relative URLs") + if not host: + raise ValueError("host removing is not allowed") + encoded_host = _encode_host(host, validate_host=True) if host else "" + port = self.explicit_port + netloc = make_netloc(self.raw_user, self.raw_password, encoded_host, port) + return from_parts(self._scheme, netloc, self._path, self._query, self._fragment) + + def with_port(self, port: int | None) -> "URL": + """Return a new URL with port replaced. + + Clear port to default if None is passed. + + """ + # N.B. doesn't cleanup query/fragment + if port is not None: + if isinstance(port, bool) or not isinstance(port, int): + raise TypeError(f"port should be int or None, got {type(port)}") + if not (0 <= port <= 65535): + raise ValueError(f"port must be between 0 and 65535, got {port}") + if not (netloc := self._netloc): + raise ValueError("port replacement is not allowed for relative URLs") + encoded_host = self.host_subcomponent or "" + netloc = make_netloc(self.raw_user, self.raw_password, encoded_host, port) + return from_parts(self._scheme, netloc, self._path, self._query, self._fragment) + + def with_path( + self, + path: str, + *, + encoded: bool = False, + keep_query: bool = False, + keep_fragment: bool = False, + ) -> "URL": + """Return a new URL with path replaced.""" + netloc = self._netloc + if not encoded: + path = PATH_QUOTER(path) + if netloc: + path = normalize_path(path) if "." in path else path + if path and path[0] != "/": + path = f"/{path}" + query = self._query if keep_query else "" + fragment = self._fragment if keep_fragment else "" + return from_parts(self._scheme, netloc, path, query, fragment) + + @overload + def with_query(self, query: Query) -> "URL": ... + + @overload + def with_query(self, **kwargs: QueryVariable) -> "URL": ... + + def with_query(self, *args: Any, **kwargs: Any) -> "URL": + """Return a new URL with query part replaced. + + Accepts any Mapping (e.g. dict, multidict.MultiDict instances) + or str, autoencode the argument if needed. + + A sequence of (key, value) pairs is supported as well. + + It also can take an arbitrary number of keyword arguments. + + Clear query if None is passed. + + """ + # N.B. doesn't cleanup query/fragment + query = get_str_query(*args, **kwargs) or "" + return from_parts_uncached( + self._scheme, self._netloc, self._path, query, self._fragment + ) + + @overload + def extend_query(self, query: Query) -> "URL": ... + + @overload + def extend_query(self, **kwargs: QueryVariable) -> "URL": ... + + def extend_query(self, *args: Any, **kwargs: Any) -> "URL": + """Return a new URL with query part combined with the existing. + + This method will not remove existing query parameters. + + Example: + >>> url = URL('http://example.com/?a=1&b=2') + >>> url.extend_query(a=3, c=4) + URL('http://example.com/?a=1&b=2&a=3&c=4') + """ + if not (new_query := get_str_query(*args, **kwargs)): + return self + if query := self._query: + # both strings are already encoded so we can use a simple + # string join + query += new_query if query[-1] == "&" else f"&{new_query}" + else: + query = new_query + return from_parts_uncached( + self._scheme, self._netloc, self._path, query, self._fragment + ) + + @overload + def update_query(self, query: Query) -> "URL": ... + + @overload + def update_query(self, **kwargs: QueryVariable) -> "URL": ... + + def update_query(self, *args: Any, **kwargs: Any) -> "URL": + """Return a new URL with query part updated. + + This method will overwrite existing query parameters. + + Example: + >>> url = URL('http://example.com/?a=1&b=2') + >>> url.update_query(a=3, c=4) + URL('http://example.com/?a=3&b=2&c=4') + """ + in_query: ( + str + | Mapping[str, QueryVariable] + | Sequence[tuple[str | istr, SimpleQuery]] + | None + ) + if kwargs: + if args: + msg = "Either kwargs or single query parameter must be present" + raise ValueError(msg) + in_query = kwargs + elif len(args) == 1: + in_query = args[0] + else: + raise ValueError("Either kwargs or single query parameter must be present") + + if in_query is None: + query = "" + elif not in_query: + query = self._query + elif isinstance(in_query, Mapping): + qm: MultiDict[QueryVariable] = MultiDict(self._parsed_query) + qm.update(in_query) + query = get_str_query_from_sequence_iterable(qm.items()) + elif isinstance(in_query, str): + qstr: MultiDict[str] = MultiDict(self._parsed_query) + qstr.update(query_to_pairs(in_query)) + query = get_str_query_from_iterable(qstr.items()) + elif isinstance(in_query, (bytes, bytearray, memoryview)): + msg = "Invalid query type: bytes, bytearray and memoryview are forbidden" + raise TypeError(msg) + elif isinstance(in_query, Sequence): + # We don't expect sequence values if we're given a list of pairs + # already; only mappings like builtin `dict` which can't have the + # same key pointing to multiple values are allowed to use + # `_query_seq_pairs`. + if TYPE_CHECKING: + in_query = cast( + Sequence[tuple[Union[str, istr], SimpleQuery]], in_query + ) + qs: MultiDict[SimpleQuery] = MultiDict(self._parsed_query) + qs.update(in_query) + query = get_str_query_from_iterable(qs.items()) + else: + raise TypeError( + "Invalid query type: only str, mapping or " + "sequence of (key, value) pairs is allowed" + ) + return from_parts_uncached( + self._scheme, self._netloc, self._path, query, self._fragment + ) + + def without_query_params(self, *query_params: str) -> "URL": + """Remove some keys from query part and return new URL.""" + params_to_remove = set(query_params) & self.query.keys() + if not params_to_remove: + return self + return self.with_query( + tuple( + (name, value) + for name, value in self.query.items() + if name not in params_to_remove + ) + ) + + def with_fragment(self, fragment: str | None) -> "URL": + """Return a new URL with fragment replaced. + + Autoencode fragment if needed. + + Clear fragment to default if None is passed. + + """ + # N.B. doesn't cleanup query/fragment + if fragment is None: + raw_fragment = "" + elif not isinstance(fragment, str): + raise TypeError("Invalid fragment type") + else: + raw_fragment = FRAGMENT_QUOTER(fragment) + if self._fragment == raw_fragment: + return self + return from_parts( + self._scheme, self._netloc, self._path, self._query, raw_fragment + ) + + def with_name( + self, + name: str, + *, + keep_query: bool = False, + keep_fragment: bool = False, + ) -> "URL": + """Return a new URL with name (last part of path) replaced. + + Query and fragment parts are cleaned up. + + Name is encoded if needed. + + """ + # N.B. DOES cleanup query/fragment + if not isinstance(name, str): + raise TypeError("Invalid name type") + if "/" in name: + raise ValueError("Slash in name is not allowed") + name = PATH_QUOTER(name) + if name in (".", ".."): + raise ValueError(". and .. values are forbidden") + parts = list(self.raw_parts) + if netloc := self._netloc: + if len(parts) == 1: + parts.append(name) + else: + parts[-1] = name + parts[0] = "" # replace leading '/' + else: + parts[-1] = name + if parts[0] == "/": + parts[0] = "" # replace leading '/' + + query = self._query if keep_query else "" + fragment = self._fragment if keep_fragment else "" + return from_parts(self._scheme, netloc, "/".join(parts), query, fragment) + + def with_suffix( + self, + suffix: str, + *, + keep_query: bool = False, + keep_fragment: bool = False, + ) -> "URL": + """Return a new URL with suffix (file extension of name) replaced. + + Query and fragment parts are cleaned up. + + suffix is encoded if needed. + """ + if not isinstance(suffix, str): + raise TypeError("Invalid suffix type") + if suffix and not suffix[0] == "." or suffix == "." or "/" in suffix: + raise ValueError(f"Invalid suffix {suffix!r}") + name = self.raw_name + if not name: + raise ValueError(f"{self!r} has an empty name") + old_suffix = self.raw_suffix + suffix = PATH_QUOTER(suffix) + name = name + suffix if not old_suffix else name[: -len(old_suffix)] + suffix + if name in (".", ".."): + raise ValueError(". and .. values are forbidden") + parts = list(self.raw_parts) + if netloc := self._netloc: + if len(parts) == 1: + parts.append(name) + else: + parts[-1] = name + parts[0] = "" # replace leading '/' + else: + parts[-1] = name + if parts[0] == "/": + parts[0] = "" # replace leading '/' + + query = self._query if keep_query else "" + fragment = self._fragment if keep_fragment else "" + return from_parts(self._scheme, netloc, "/".join(parts), query, fragment) + + def join(self, url: "URL") -> "URL": + """Join URLs + + Construct a full (“absolute”) URL by combining a “base URL” + (self) with another URL (url). + + Informally, this uses components of the base URL, in + particular the addressing scheme, the network location and + (part of) the path, to provide missing components in the + relative URL. + + """ + if type(url) is not URL: + raise TypeError("url should be URL") + + scheme = url._scheme or self._scheme + if scheme != self._scheme or scheme not in USES_RELATIVE: + return url + + # scheme is in uses_authority as uses_authority is a superset of uses_relative + if (join_netloc := url._netloc) and scheme in USES_AUTHORITY: + return from_parts(scheme, join_netloc, url._path, url._query, url._fragment) + + orig_path = self._path + if join_path := url._path: + if join_path[0] == "/": + path = join_path + elif not orig_path: + path = f"/{join_path}" + elif orig_path[-1] == "/": + path = f"{orig_path}{join_path}" + else: + # … + # and relativizing ".." + # parts[0] is / for absolute urls, + # this join will add a double slash there + path = "/".join([*self.parts[:-1], ""]) + join_path + # which has to be removed + if orig_path[0] == "/": + path = path[1:] + path = normalize_path(path) if "." in path else path + else: + path = orig_path + + return from_parts( + scheme, + self._netloc, + path, + url._query if join_path or url._query else self._query, + url._fragment if join_path or url._fragment else self._fragment, + ) + + def joinpath(self, *other: str, encoded: bool = False) -> "URL": + """Return a new URL with the elements in other appended to the path.""" + return self._make_child(other, encoded=encoded) + + def human_repr(self) -> str: + """Return decoded human readable string for URL representation.""" + user = human_quote(self.user, "#/:?@[]") + password = human_quote(self.password, "#/:?@[]") + if (host := self.host) and ":" in host: + host = f"[{host}]" + path = human_quote(self.path, "#?") + if TYPE_CHECKING: + assert path is not None + query_string = "&".join( + "{}={}".format(human_quote(k, "#&+;="), human_quote(v, "#&+;=")) + for k, v in self.query.items() + ) + fragment = human_quote(self.fragment, "") + if TYPE_CHECKING: + assert fragment is not None + netloc = make_netloc(user, password, host, self.explicit_port) + return unsplit_result(self._scheme, netloc, path, query_string, fragment) + + if HAS_PYDANTIC: # pragma: no cover + # Borrowed from https://docs.pydantic.dev/latest/concepts/types/#handling-third-party-types + @classmethod + def __get_pydantic_json_schema__( + cls, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler + ) -> JsonSchemaValue: + field_schema: dict[str, Any] = {} + field_schema.update(type="string", format="uri") + return field_schema + + @classmethod + def __get_pydantic_core_schema__( + cls, source_type: type[Self] | type[str], handler: GetCoreSchemaHandler + ) -> core_schema.CoreSchema: + from_str_schema = core_schema.chain_schema( + [ + core_schema.str_schema(), + core_schema.no_info_plain_validator_function(URL), + ] + ) + + return core_schema.json_or_python_schema( + json_schema=from_str_schema, + python_schema=core_schema.union_schema( + [ + # check if it's an instance first before doing any further work + core_schema.is_instance_schema(URL), + from_str_schema, + ] + ), + serialization=core_schema.plain_serializer_function_ser_schema(str), + ) + + +_DEFAULT_IDNA_SIZE = 256 +_DEFAULT_ENCODE_SIZE = 512 + + +@lru_cache(_DEFAULT_IDNA_SIZE) +def _idna_decode(raw: str) -> str: + try: + return idna.decode(raw.encode("ascii")) + except UnicodeError: # e.g. '::1' + return raw.encode("ascii").decode("idna") + + +@lru_cache(_DEFAULT_IDNA_SIZE) +def _idna_encode(host: str) -> str: + try: + return idna.encode(host, uts46=True).decode("ascii") + except UnicodeError: + return host.encode("idna").decode("ascii") + + +@lru_cache(_DEFAULT_ENCODE_SIZE) +def _encode_host(host: str, validate_host: bool) -> str: + """Encode host part of URL.""" + # If the host ends with a digit or contains a colon, its likely + # an IP address. + if host and (host[-1].isdigit() or ":" in host): + raw_ip, sep, zone = host.partition("%") + # If it looks like an IP, we check with _ip_compressed_version + # and fall-through if its not an IP address. This is a performance + # optimization to avoid parsing IP addresses as much as possible + # because it is orders of magnitude slower than almost any other + # operation this library does. + # Might be an IP address, check it + # + # IP Addresses can look like: + # https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.2 + # - 127.0.0.1 (last character is a digit) + # - 2001:db8::ff00:42:8329 (contains a colon) + # - 2001:db8::ff00:42:8329%eth0 (contains a colon) + # - [2001:db8::ff00:42:8329] (contains a colon -- brackets should + # have been removed before it gets here) + # Rare IP Address formats are not supported per: + # https://datatracker.ietf.org/doc/html/rfc3986#section-7.4 + # + # IP parsing is slow, so its wrapped in an LRU + try: + ip = ip_address(raw_ip) + except ValueError: + pass + else: + # These checks should not happen in the + # LRU to keep the cache size small + host = ip.compressed + if ip.version == 6: + return f"[{host}%{zone}]" if sep else f"[{host}]" + return f"{host}%{zone}" if sep else host + + # IDNA encoding is slow, skip it for ASCII-only strings + if host.isascii(): + # Check for invalid characters explicitly; _idna_encode() does this + # for non-ascii host names. + host = host.lower() + if validate_host and (invalid := NOT_REG_NAME.search(host)): + value, pos, extra = invalid.group(), invalid.start(), "" + if value == "@" or (value == ":" and "@" in host[pos:]): + # this looks like an authority string + extra = ( + ", if the value includes a username or password, " + "use 'authority' instead of 'host'" + ) + raise ValueError( + f"Host {host!r} cannot contain {value!r} (at position {pos}){extra}" + ) from None + return host + + return _idna_encode(host) + + +@rewrite_module +def cache_clear() -> None: + """Clear all LRU caches.""" + _idna_encode.cache_clear() + _idna_decode.cache_clear() + _encode_host.cache_clear() + + +@rewrite_module +def cache_info() -> CacheInfo: + """Report cache statistics.""" + return { + "idna_encode": _idna_encode.cache_info(), + "idna_decode": _idna_decode.cache_info(), + "ip_address": _encode_host.cache_info(), + "host_validate": _encode_host.cache_info(), + "encode_host": _encode_host.cache_info(), + } + + +@rewrite_module +def cache_configure( + *, + idna_encode_size: int | None = _DEFAULT_IDNA_SIZE, + idna_decode_size: int | None = _DEFAULT_IDNA_SIZE, + ip_address_size: int | None | UndefinedType = UNDEFINED, + host_validate_size: int | None | UndefinedType = UNDEFINED, + encode_host_size: int | None | UndefinedType = UNDEFINED, +) -> None: + """Configure LRU cache sizes.""" + global _idna_decode, _idna_encode, _encode_host + # ip_address_size, host_validate_size are no longer + # used, but are kept for backwards compatibility. + if ip_address_size is not UNDEFINED or host_validate_size is not UNDEFINED: + warnings.warn( + "cache_configure() no longer accepts the " + "ip_address_size or host_validate_size arguments, " + "they are used to set the encode_host_size instead " + "and will be removed in the future", + DeprecationWarning, + stacklevel=2, + ) + + if encode_host_size is not None: + for size in (ip_address_size, host_validate_size): + if size is None: + encode_host_size = None + elif encode_host_size is UNDEFINED: + if size is not UNDEFINED: + encode_host_size = size + elif size is not UNDEFINED: + if TYPE_CHECKING: + assert isinstance(size, int) + assert isinstance(encode_host_size, int) + encode_host_size = max(size, encode_host_size) + if encode_host_size is UNDEFINED: + encode_host_size = _DEFAULT_ENCODE_SIZE + + _encode_host = lru_cache(encode_host_size)(_encode_host.__wrapped__) + _idna_decode = lru_cache(idna_decode_size)(_idna_decode.__wrapped__) + _idna_encode = lru_cache(idna_encode_size)(_idna_encode.__wrapped__) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/py.typed b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..dcf2c804da5e19d617a03a6c68aa128d1d1f89a0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/yarl/py.typed @@ -0,0 +1 @@ +# Placeholder diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp-3.23.1.dist-info/INSTALLER b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp-3.23.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp-3.23.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp-3.23.1.dist-info/METADATA b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp-3.23.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..6d202013061c4aa9235985581488c01e45f478c9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp-3.23.1.dist-info/METADATA @@ -0,0 +1,108 @@ +Metadata-Version: 2.4 +Name: zipp +Version: 3.23.1 +Summary: Backport of pathlib-compatible object wrapper for zip files +Author-email: "Jason R. Coombs" +License-Expression: MIT +Project-URL: Source, https://github.com/jaraco/zipp +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Requires-Python: >=3.9 +Description-Content-Type: text/x-rst +License-File: LICENSE +Provides-Extra: test +Requires-Dist: pytest!=8.1.*,>=6; extra == "test" +Requires-Dist: jaraco.itertools; extra == "test" +Requires-Dist: jaraco.functools; extra == "test" +Requires-Dist: more_itertools; extra == "test" +Requires-Dist: big-O; extra == "test" +Requires-Dist: pytest-ignore-flaky; extra == "test" +Requires-Dist: jaraco.test; extra == "test" +Provides-Extra: doc +Requires-Dist: sphinx>=3.5; extra == "doc" +Requires-Dist: jaraco.packaging>=9.3; extra == "doc" +Requires-Dist: rst.linker>=1.9; extra == "doc" +Requires-Dist: furo; extra == "doc" +Requires-Dist: sphinx-lint; extra == "doc" +Requires-Dist: jaraco.tidelift>=1.4; extra == "doc" +Provides-Extra: check +Requires-Dist: pytest-checkdocs>=2.4; extra == "check" +Requires-Dist: pytest-ruff>=0.2.1; sys_platform != "cygwin" and extra == "check" +Provides-Extra: cover +Requires-Dist: pytest-cov; extra == "cover" +Provides-Extra: enabler +Requires-Dist: pytest-enabler>=2.2; extra == "enabler" +Provides-Extra: type +Requires-Dist: pytest-mypy; extra == "type" +Dynamic: license-file + +.. image:: https://img.shields.io/pypi/v/zipp.svg + :target: https://pypi.org/project/zipp + +.. image:: https://img.shields.io/pypi/pyversions/zipp.svg + +.. image:: https://github.com/jaraco/zipp/actions/workflows/main.yml/badge.svg + :target: https://github.com/jaraco/zipp/actions?query=workflow%3A%22tests%22 + :alt: tests + +.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Ruff + +.. image:: https://readthedocs.org/projects/zipp/badge/?version=latest +.. :target: https://zipp.readthedocs.io/en/latest/?badge=latest + +.. image:: https://img.shields.io/badge/skeleton-2025-informational + :target: https://blog.jaraco.com/skeleton + +.. image:: https://tidelift.com/badges/package/pypi/zipp + :target: https://tidelift.com/subscription/pkg/pypi-zipp?utm_source=pypi-zipp&utm_medium=readme + + +A pathlib-compatible Zipfile object wrapper. Official backport of the standard library +`Path object `_. + + +Compatibility +============= + +New features are introduced in this third-party library and later merged +into CPython. The following table indicates which versions of this library +were contributed to different versions in the standard library: + +.. list-table:: + :header-rows: 1 + + * - zipp + - stdlib + * - 3.21 + - 3.15 + * - 3.18 + - 3.13 + * - 3.16 + - 3.12 + * - 3.5 + - 3.11 + * - 3.2 + - 3.10 + * - 3.3 ?? + - 3.9 + * - 1.0 + - 3.8 + + +Usage +===== + +Use ``zipp.Path`` in place of ``zipfile.Path`` on any Python. + +For Enterprise +============== + +Available as part of the Tidelift Subscription. + +This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use. + +`Learn more `_. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp-3.23.1.dist-info/RECORD b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp-3.23.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..de26b05f91cd7c02a4eda4817b73338bbbb52a56 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp-3.23.1.dist-info/RECORD @@ -0,0 +1,20 @@ +zipp-3.23.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +zipp-3.23.1.dist-info/METADATA,sha256=QgvdwjSWH73LWr38QuMX4KcGkXqcoWP4FWIeF79DR68,3587 +zipp-3.23.1.dist-info/RECORD,, +zipp-3.23.1.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91 +zipp-3.23.1.dist-info/licenses/LICENSE,sha256=l1WhhRlmbl8PTK49qtPXASvK5IpgCzEjfXXp_hNOZoM,1076 +zipp-3.23.1.dist-info/top_level.txt,sha256=iAbdoSHfaGqBfVb2XuR9JqSQHCoOsOtG6y9C_LSpqFw,5 +zipp/__init__.py,sha256=BsHiDI07HCJfbVU0rXaFfe2XAoivwR0pByJLEgtBJX4,12047 +zipp/__pycache__/__init__.cpython-311.pyc,, +zipp/__pycache__/_functools.cpython-311.pyc,, +zipp/__pycache__/glob.cpython-311.pyc,, +zipp/_functools.py,sha256=LZrqt6bu0I4bxxAbDsNs07fb5ad5_INdG1gzSdhTLv8,789 +zipp/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +zipp/compat/__pycache__/__init__.cpython-311.pyc,, +zipp/compat/__pycache__/overlay.cpython-311.pyc,, +zipp/compat/__pycache__/py310.cpython-311.pyc,, +zipp/compat/__pycache__/py313.cpython-311.pyc,, +zipp/compat/overlay.py,sha256=oEIGAnbr8yGjuKTrVSO2ByewPui71uppbX18BLnYTKE,783 +zipp/compat/py310.py,sha256=S7i6N9mToEn3asNb2ILyjnzvITOXrATD_J4emjyBbDU,256 +zipp/compat/py313.py,sha256=RndvDNtuY7H2D9ecnnzcPBMZ8mZc42gmXD_IwQAXXAE,654 +zipp/glob.py,sha256=DLV9LBsDxA6YVW82e3-tkoNrus1h4R-j3BR6VqS0AzE,3382 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp-3.23.1.dist-info/WHEEL b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp-3.23.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..14a883f292bc96b20c2b76a3081991f2676523a9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp-3.23.1.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/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp-3.23.1.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp-3.23.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c891f411dc44c70ff121531af2ee189d3da4c871 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp-3.23.1.dist-info/licenses/LICENSE @@ -0,0 +1,18 @@ +MIT License + +Copyright (c) 2026 + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO +EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp-3.23.1.dist-info/top_level.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp-3.23.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..e82f676f82a3381fa909d1e6578c7a22044fafca --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp-3.23.1.dist-info/top_level.txt @@ -0,0 +1 @@ +zipp diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5f9fadc20416529f3b5d344f48f75a96bbe9db37 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/__init__.py @@ -0,0 +1,457 @@ +""" +A Path-like interface for zipfiles. + +This codebase is shared between zipfile.Path in the stdlib +and zipp in PyPI. See +https://github.com/python/importlib_metadata/wiki/Development-Methodology +for more detail. +""" + +import functools +import io +import itertools +import pathlib +import posixpath +import re +import stat +import sys +import zipfile + +from ._functools import none_as, save_method_args +from .compat.py310 import text_encoding +from .glob import Translator + +__all__ = ['Path'] + + +def _parents(path): + """ + Given a path with elements separated by + posixpath.sep, generate all parents of that path. + + >>> list(_parents('b/d')) + ['b'] + >>> list(_parents('/b/d/')) + ['/b'] + >>> list(_parents('b/d/f/')) + ['b/d', 'b'] + >>> list(_parents('b')) + [] + >>> list(_parents('')) + [] + """ + return itertools.islice(_ancestry(path), 1, None) + + +def _ancestry(path): + """ + Given a path with elements separated by + posixpath.sep, generate all elements of that path. + + >>> list(_ancestry('b/d')) + ['b/d', 'b'] + >>> list(_ancestry('/b/d/')) + ['/b/d', '/b'] + >>> list(_ancestry('b/d/f/')) + ['b/d/f', 'b/d', 'b'] + >>> list(_ancestry('b')) + ['b'] + >>> list(_ancestry('')) + [] + + Multiple separators are treated like a single. + + >>> list(_ancestry('//b//d///f//')) + ['//b//d///f', '//b//d', '//b'] + """ + path = path.rstrip(posixpath.sep) + while path.rstrip(posixpath.sep): + yield path + path, tail = posixpath.split(path) + + +_dedupe = dict.fromkeys +"""Deduplicate an iterable in original order""" + + +def _difference(minuend, subtrahend): + """ + Return items in minuend not in subtrahend, retaining order + with O(1) lookup. + """ + return itertools.filterfalse(set(subtrahend).__contains__, minuend) + + +class InitializedState: + """ + Mix-in to save the initialization state for pickling. + """ + + @save_method_args + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + def __getstate__(self): + return self._saved___init__.args, self._saved___init__.kwargs + + def __setstate__(self, state): + args, kwargs = state + super().__init__(*args, **kwargs) + + +class CompleteDirs(InitializedState, zipfile.ZipFile): + """ + A ZipFile subclass that ensures that implied directories + are always included in the namelist. + + >>> list(CompleteDirs._implied_dirs(['foo/bar.txt', 'foo/bar/baz.txt'])) + ['foo/', 'foo/bar/'] + >>> list(CompleteDirs._implied_dirs(['foo/bar.txt', 'foo/bar/baz.txt', 'foo/bar/'])) + ['foo/'] + """ + + @staticmethod + def _implied_dirs(names): + parents = itertools.chain.from_iterable(map(_parents, names)) + as_dirs = (p + posixpath.sep for p in parents) + return _dedupe(_difference(as_dirs, names)) + + def namelist(self): + names = super().namelist() + return names + list(self._implied_dirs(names)) + + def _name_set(self): + return set(self.namelist()) + + def resolve_dir(self, name): + """ + If the name represents a directory, return that name + as a directory (with the trailing slash). + """ + names = self._name_set() + dirname = name + '/' + dir_match = name not in names and dirname in names + return dirname if dir_match else name + + def getinfo(self, name): + """ + Supplement getinfo for implied dirs. + """ + try: + return super().getinfo(name) + except KeyError: + if not name.endswith('/') or name not in self._name_set(): + raise + return zipfile.ZipInfo(filename=name) + + @classmethod + def make(cls, source): + """ + Given a source (filename or zipfile), return an + appropriate CompleteDirs subclass. + """ + if isinstance(source, CompleteDirs): + return source + + if not isinstance(source, zipfile.ZipFile): + return cls(source) + + # Only allow for FastLookup when supplied zipfile is read-only + if 'r' not in source.mode: + cls = CompleteDirs + + source.__class__ = cls + return source + + @classmethod + def inject(cls, zf: zipfile.ZipFile) -> zipfile.ZipFile: + """ + Given a writable zip file zf, inject directory entries for + any directories implied by the presence of children. + """ + for name in cls._implied_dirs(zf.namelist()): + zf.writestr(name, b"") + return zf + + +class FastLookup(CompleteDirs): + """ + ZipFile subclass to ensure implicit + dirs exist and are resolved rapidly. + """ + + def namelist(self): + return self._namelist + + @functools.cached_property + def _namelist(self): + return super().namelist() + + def _name_set(self): + return self._name_set_prop + + @functools.cached_property + def _name_set_prop(self): + return super()._name_set() + + +def _extract_text_encoding(encoding=None, *args, **kwargs): + # compute stack level so that the caller of the caller sees any warning. + is_pypy = sys.implementation.name == 'pypy' + # PyPy no longer special cased after 7.3.19 (or maybe 7.3.18) + # See jaraco/zipp#143 + is_old_pypi = is_pypy and sys.pypy_version_info < (7, 3, 19) + stack_level = 3 + is_old_pypi + return text_encoding(encoding, stack_level), args, kwargs + + +class Path: + """ + A :class:`importlib.resources.abc.Traversable` interface for zip files. + + Implements many of the features users enjoy from + :class:`pathlib.Path`. + + Consider a zip file with this structure:: + + . + ├── a.txt + └── b + ├── c.txt + └── d + └── e.txt + + >>> data = io.BytesIO() + >>> zf = zipfile.ZipFile(data, 'w') + >>> zf.writestr('a.txt', 'content of a') + >>> zf.writestr('b/c.txt', 'content of c') + >>> zf.writestr('b/d/e.txt', 'content of e') + >>> zf.filename = 'mem/abcde.zip' + + Path accepts the zipfile object itself or a filename + + >>> path = Path(zf) + + From there, several path operations are available. + + Directory iteration (including the zip file itself): + + >>> a, b = path.iterdir() + >>> a + Path('mem/abcde.zip', 'a.txt') + >>> b + Path('mem/abcde.zip', 'b/') + + name property: + + >>> b.name + 'b' + + join with divide operator: + + >>> c = b / 'c.txt' + >>> c + Path('mem/abcde.zip', 'b/c.txt') + >>> c.name + 'c.txt' + + Read text: + + >>> c.read_text(encoding='utf-8') + 'content of c' + + existence: + + >>> c.exists() + True + >>> (b / 'missing.txt').exists() + False + + Coercion to string: + + >>> import os + >>> str(c).replace(os.sep, posixpath.sep) + 'mem/abcde.zip/b/c.txt' + + At the root, ``name``, ``filename``, and ``parent`` + resolve to the zipfile. + + >>> str(path) + 'mem/abcde.zip' + >>> path.name + 'abcde.zip' + >>> path.filename == pathlib.Path('mem/abcde.zip') + True + >>> str(path.parent) + 'mem' + + If the zipfile has no filename, such attributes are not + valid and accessing them will raise an Exception. + + >>> zf.filename = None + >>> path.name + Traceback (most recent call last): + ... + TypeError: ... + + >>> path.filename + Traceback (most recent call last): + ... + TypeError: ... + + >>> path.parent + Traceback (most recent call last): + ... + TypeError: ... + + # workaround python/cpython#106763 + >>> pass + """ + + __repr = "{self.__class__.__name__}({self.root.filename!r}, {self.at!r})" + + def __init__(self, root, at=""): + """ + Construct a Path from a ZipFile or filename. + + Note: When the source is an existing ZipFile object, + its type (__class__) will be mutated to a + specialized type. If the caller wishes to retain the + original type, the caller should either create a + separate ZipFile object or pass a filename. + """ + self.root = FastLookup.make(root) + self.at = at + + def __eq__(self, other): + """ + >>> Path(zipfile.ZipFile(io.BytesIO(), 'w')) == 'foo' + False + """ + if self.__class__ is not other.__class__: + return NotImplemented + return (self.root, self.at) == (other.root, other.at) + + def __hash__(self): + return hash((self.root, self.at)) + + def open(self, mode='r', *args, pwd=None, **kwargs): + """ + Open this entry as text or binary following the semantics + of ``pathlib.Path.open()`` by passing arguments through + to io.TextIOWrapper(). + """ + if self.is_dir(): + raise IsADirectoryError(self) + zip_mode = mode[0] + if zip_mode == 'r' and not self.exists(): + raise FileNotFoundError(self) + stream = self.root.open(self.at, zip_mode, pwd=pwd) + if 'b' in mode: + if args or kwargs: + raise ValueError("encoding args invalid for binary operation") + return stream + # Text mode: + encoding, args, kwargs = _extract_text_encoding(*args, **kwargs) + return io.TextIOWrapper(stream, encoding, *args, **kwargs) + + def _base(self): + return pathlib.PurePosixPath(self.at) if self.at else self.filename + + @property + def name(self): + return self._base().name + + @property + def suffix(self): + return self._base().suffix + + @property + def suffixes(self): + return self._base().suffixes + + @property + def stem(self): + return self._base().stem + + @property + def filename(self): + return pathlib.Path(self.root.filename).joinpath(self.at) + + def read_text(self, *args, **kwargs): + encoding, args, kwargs = _extract_text_encoding(*args, **kwargs) + with self.open('r', encoding, *args, **kwargs) as strm: + return strm.read() + + def read_bytes(self): + with self.open('rb') as strm: + return strm.read() + + def _is_child(self, path): + return posixpath.dirname(path.at.rstrip("/")) == self.at.rstrip("/") + + def _next(self, at): + return self.__class__(self.root, at) + + def is_dir(self): + return not self.at or self.at.endswith("/") + + def is_file(self): + return self.exists() and not self.is_dir() + + def exists(self): + return self.at in self.root._name_set() + + def iterdir(self): + if not self.is_dir(): + raise ValueError("Can't listdir a file") + subs = map(self._next, self.root.namelist()) + return filter(self._is_child, subs) + + def match(self, path_pattern): + return pathlib.PurePosixPath(self.at).match(path_pattern) + + def is_symlink(self): + """ + Return whether this path is a symlink. + """ + info = self.root.getinfo(self.at) + mode = info.external_attr >> 16 + return stat.S_ISLNK(mode) + + def glob(self, pattern): + if not pattern: + raise ValueError(f"Unacceptable pattern: {pattern!r}") + + prefix = re.escape(self.at) + tr = Translator(seps='/') + matches = re.compile(prefix + tr.translate(pattern)).fullmatch + return map(self._next, filter(matches, self.root.namelist())) + + def rglob(self, pattern): + return self.glob(f'**/{pattern}') + + def relative_to(self, other, *extra): + return posixpath.relpath(str(self), str(other.joinpath(*extra))) + + def __str__(self): + root = none_as(self.root.filename, ':zipfile:') + return posixpath.join(root, self.at) if self.at else root + + def __repr__(self): + return self.__repr.format(self=self) + + def joinpath(self, *other): + next = posixpath.join(self.at, *other) + return self._next(self.root.resolve_dir(next)) + + __truediv__ = joinpath + + @property + def parent(self): + if not self.at: + return self.filename.parent + parent_at = posixpath.dirname(self.at.rstrip('/')) + if parent_at: + parent_at += '/' + return self._next(parent_at) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90ca337ab7df293960d4e31633d0aab63bc1e471 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/__pycache__/_functools.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/__pycache__/_functools.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a92a841b0afb2441c94d10f9a98699b9c5267d58 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/__pycache__/_functools.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/__pycache__/glob.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/__pycache__/glob.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3fa7dad46512663610a400754aeb19106952d749 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/__pycache__/glob.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/_functools.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/_functools.py new file mode 100644 index 0000000000000000000000000000000000000000..7d82636ac8d627add2635ce3d5580a411d1744e6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/_functools.py @@ -0,0 +1,31 @@ +import collections +import functools + + +# from jaraco.functools 4.0.2 +def save_method_args(method): + """ + Wrap a method such that when it is called, the args and kwargs are + saved on the method. + """ + args_and_kwargs = collections.namedtuple('args_and_kwargs', 'args kwargs') # noqa: PYI024 + + @functools.wraps(method) + def wrapper(self, /, *args, **kwargs): + attr_name = '_saved_' + method.__name__ + attr = args_and_kwargs(args, kwargs) + setattr(self, attr_name, attr) + return method(self, *args, **kwargs) + + return wrapper + + +# from jaraco.functools 4.3 +def none_as(value, replacement=None): + """ + >>> none_as(None, 'foo') + 'foo' + >>> none_as('bar', 'foo') + 'bar' + """ + return replacement if value is None else value diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/compat/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/compat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/compat/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/compat/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8cf0507d53d3dedb512de1c0a506a483e57905ce Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/compat/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/compat/__pycache__/overlay.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/compat/__pycache__/overlay.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ad1673ee5307abac24167cb2adabbd4e52e16ad Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/compat/__pycache__/overlay.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/compat/__pycache__/py310.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/compat/__pycache__/py310.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bec9bcd137a6b00f88c5f5d92d39e4a60a33b030 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/compat/__pycache__/py310.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/compat/__pycache__/py313.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/compat/__pycache__/py313.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c070784a8f989e970634fd76c9ea63f04f76656 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/compat/__pycache__/py313.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/compat/overlay.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/compat/overlay.py new file mode 100644 index 0000000000000000000000000000000000000000..5a97ee7cd8b98f3a5487c0a0b0a80ffde5ff4dfd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/compat/overlay.py @@ -0,0 +1,37 @@ +""" +Expose zipp.Path as .zipfile.Path. + +Includes everything else in ``zipfile`` to match future usage. Just +use: + +>>> from zipp.compat.overlay import zipfile + +in place of ``import zipfile``. + +Relative imports are supported too. + +>>> from zipp.compat.overlay.zipfile import ZipInfo + +The ``zipfile`` object added to ``sys.modules`` needs to be +hashable (#126). + +>>> _ = hash(sys.modules['zipp.compat.overlay.zipfile']) +""" + +import importlib +import sys +import types + +import zipp + + +class HashableNamespace(types.SimpleNamespace): + def __hash__(self): + return hash(tuple(vars(self))) + + +zipfile = HashableNamespace(**vars(importlib.import_module('zipfile'))) +zipfile.Path = zipp.Path +zipfile._path = zipp + +sys.modules[__name__ + '.zipfile'] = zipfile # type: ignore[assignment] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/compat/py310.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/compat/py310.py new file mode 100644 index 0000000000000000000000000000000000000000..e1e7ec229062b8556cdd85f530d1ff301b2e6845 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/compat/py310.py @@ -0,0 +1,13 @@ +import io +import sys + + +def _text_encoding(encoding, stacklevel=2, /): # pragma: no cover + return encoding + + +text_encoding = ( + io.text_encoding # type: ignore[unused-ignore, attr-defined] + if sys.version_info > (3, 10) + else _text_encoding +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/compat/py313.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/compat/py313.py new file mode 100644 index 0000000000000000000000000000000000000000..ae458690553f92107ce296adf4bb49add8e78250 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/compat/py313.py @@ -0,0 +1,34 @@ +import functools +import sys + + +# from jaraco.functools 4.1 +def identity(x): + return x + + +# from jaraco.functools 4.1 +def apply(transform): + def wrap(func): + return functools.wraps(func)(compose(transform, func)) + + return wrap + + +# from jaraco.functools 4.1 +def compose(*funcs): + def compose_two(f1, f2): + return lambda *args, **kwargs: f1(f2(*args, **kwargs)) + + return functools.reduce(compose_two, funcs) + + +def replace(pattern): + r""" + >>> replace(r'foo\z') + 'foo\\Z' + """ + return pattern[:-2] + pattern[-2:].replace(r'\z', r'\Z') + + +legacy_end_marker = apply(replace) if sys.version_info < (3, 14) else identity diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/glob.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/glob.py new file mode 100644 index 0000000000000000000000000000000000000000..1b4ffb33187b65b4378925c472071c845bcecc26 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/zipp/glob.py @@ -0,0 +1,116 @@ +import os +import re + +from .compat.py313 import legacy_end_marker + +_default_seps = os.sep + str(os.altsep) * bool(os.altsep) + + +class Translator: + """ + >>> Translator('xyz') + Traceback (most recent call last): + ... + AssertionError: Invalid separators + + >>> Translator('') + Traceback (most recent call last): + ... + AssertionError: Invalid separators + """ + + seps: str + + def __init__(self, seps: str = _default_seps): + assert seps and set(seps) <= set(_default_seps), "Invalid separators" + self.seps = seps + + def translate(self, pattern): + """ + Given a glob pattern, produce a regex that matches it. + """ + return self.extend(self.match_dirs(self.translate_core(pattern))) + + @legacy_end_marker + def extend(self, pattern): + r""" + Extend regex for pattern-wide concerns. + + Apply '(?s:)' to create a non-matching group that + matches newlines (valid on Unix). + + Append '\z' to imply fullmatch even when match is used. + """ + return rf'(?s:{pattern})\z' + + def match_dirs(self, pattern): + """ + Ensure that zipfile.Path directory names are matched. + + zipfile.Path directory names always end in a slash. + """ + return rf'{pattern}[/]?' + + def translate_core(self, pattern): + r""" + Given a glob pattern, produce a regex that matches it. + + >>> t = Translator() + >>> t.translate_core('*.txt').replace('\\\\', '') + '[^/]*\\.txt' + >>> t.translate_core('a?txt') + 'a[^/]txt' + >>> t.translate_core('**/*').replace('\\\\', '') + '.*/[^/][^/]*' + """ + self.restrict_rglob(pattern) + return ''.join(map(self.replace, separate(self.star_not_empty(pattern)))) + + def replace(self, match): + """ + Perform the replacements for a match from :func:`separate`. + """ + return match.group('set') or ( + re.escape(match.group(0)) + .replace('\\*\\*', r'.*') + .replace('\\*', rf'[^{re.escape(self.seps)}]*') + .replace('\\?', r'[^/]') + ) + + def restrict_rglob(self, pattern): + """ + Raise ValueError if ** appears in anything but a full path segment. + + >>> Translator().translate('**foo') + Traceback (most recent call last): + ... + ValueError: ** must appear alone in a path segment + """ + seps_pattern = rf'[{re.escape(self.seps)}]+' + segments = re.split(seps_pattern, pattern) + if any('**' in segment and segment != '**' for segment in segments): + raise ValueError("** must appear alone in a path segment") + + def star_not_empty(self, pattern): + """ + Ensure that * will not match an empty segment. + """ + + def handle_segment(match): + segment = match.group(0) + return '?*' if segment == '*' else segment + + not_seps_pattern = rf'[^{re.escape(self.seps)}]+' + return re.sub(not_seps_pattern, handle_segment, pattern) + + +def separate(pattern): + """ + Separate out character sets to avoid translating their contents. + + >>> [m.group(0) for m in separate('*.txt')] + ['*.txt'] + >>> [m.group(0) for m in separate('a[?]txt')] + ['a', '[?]', 'txt'] + """ + return re.finditer(r'([^\[]+)|(?P[\[].*?[\]])|([\[][^\]]*$)', pattern) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard-0.25.0.dist-info/INSTALLER b/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard-0.25.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard-0.25.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard-0.25.0.dist-info/METADATA b/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard-0.25.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..8d5ff3d49efb40d33eb9cf9edd03d115f1bddbc3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard-0.25.0.dist-info/METADATA @@ -0,0 +1,64 @@ +Metadata-Version: 2.4 +Name: zstandard +Version: 0.25.0 +Summary: Zstandard bindings for Python +Author-email: Gregory Szorc +License-Expression: BSD-3-Clause +Project-URL: Homepage, https://github.com/indygreg/python-zstandard +Project-URL: Documentation, https://python-zstandard.readthedocs.io/en/latest/ +Keywords: zstandard,zstd,compression +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: C +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 :: Free Threading :: 1 - Unstable +Requires-Python: >=3.9 +Description-Content-Type: text/x-rst +License-File: LICENSE +Provides-Extra: cffi +Requires-Dist: cffi~=1.17; (platform_python_implementation != "PyPy" and python_version < "3.14") and extra == "cffi" +Requires-Dist: cffi>=2.0.0b; (platform_python_implementation != "PyPy" and python_version >= "3.14") and extra == "cffi" +Dynamic: license-file + +================ +python-zstandard +================ + +| |ci-test| |ci-wheel| |ci-typing| |ci-sdist| |ci-anaconda| |ci-sphinx| + +This project provides Python bindings for interfacing with the +`Zstandard `_ compression library. A C extension +and CFFI interface are provided. + +The primary goal of the project is to provide a rich interface to the +underlying C API through a Pythonic interface while not sacrificing +performance. This means exposing most of the features and flexibility +of the C API while not sacrificing usability or safety that Python provides. + +The canonical home for this project is +https://github.com/indygreg/python-zstandard. + +For usage documentation, see https://python-zstandard.readthedocs.org/. + +.. |ci-test| image:: https://github.com/indygreg/python-zstandard/workflows/.github/workflows/test.yml/badge.svg + :target: https://github.com/indygreg/python-zstandard/blob/main/.github/workflows/test.yml + +.. |ci-wheel| image:: https://github.com/indygreg/python-zstandard/workflows/.github/workflows/wheel.yml/badge.svg + :target: https://github.com/indygreg/python-zstandard/blob/main/.github/workflows/wheel.yml + +.. |ci-typing| image:: https://github.com/indygreg/python-zstandard/workflows/.github/workflows/typing.yml/badge.svg + :target: https://github.com/indygreg/python-zstandard/blob/main/.github/workflows/typing.yml + +.. |ci-sdist| image:: https://github.com/indygreg/python-zstandard/workflows/.github/workflows/sdist.yml/badge.svg + :target: https://github.com/indygreg/python-zstandard/blob/main/.github/workflows/sdist.yml + +.. |ci-anaconda| image:: https://github.com/indygreg/python-zstandard/workflows/.github/workflows/anaconda.yml/badge.svg + :target: https://github.com/indygreg/python-zstandard/blob/main/.github/workflows/anaconda.yml + +.. |ci-sphinx| image:: https://github.com/indygreg/python-zstandard/workflows/.github/workflows/sphinx.yml/badge.svg + :target: https://github.com/indygreg/python-zstandard/blob/main/.github/workflows/sphinx.yml diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard-0.25.0.dist-info/RECORD b/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard-0.25.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..6d2d2587960d2fcf1785a0e6117136079a41aeec --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard-0.25.0.dist-info/RECORD @@ -0,0 +1,14 @@ +zstandard-0.25.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +zstandard-0.25.0.dist-info/METADATA,sha256=u_jLYxcSdIVMcndzcjdtMde1JEc1mlOMHCtHquScKzw,3339 +zstandard-0.25.0.dist-info/RECORD,, +zstandard-0.25.0.dist-info/WHEEL,sha256=JLOMsP7F5qtkAkINx5UnzbFguf8CqZeraV8o04b0I8I,101 +zstandard-0.25.0.dist-info/licenses/LICENSE,sha256=wVso-IZlAL09YHxznodxCqXEdieqMKBXOUhBRWT_HaI,1511 +zstandard-0.25.0.dist-info/top_level.txt,sha256=J-wj94pPadY4ipFaanrYBlrMblOSegEYS8o_LdogrpU,10 +zstandard/__init__.py,sha256=XCKdk3s_hCAjTzuqwI2KvAreNKF7v7usmPzU-TSUktY,7452 +zstandard/__init__.pyi,sha256=_HpiKlmu2PnKSI-hONoKqdz1Cd7zUST7YM0fVpsI0MA,14454 +zstandard/__pycache__/__init__.cpython-311.pyc,, +zstandard/__pycache__/backend_cffi.cpython-311.pyc,, +zstandard/_cffi.cp311-win_amd64.pyd,sha256=9rdFCpU8xvD6zYmZLR0VsiuU94NCpM9Z8VFC9x-NvkY,667136 +zstandard/backend_c.cp311-win_amd64.pyd,sha256=Nfe_6NGWX8M8CQ_r0hak71w6iyLOAqaJImo3dswpUxc,524800 +zstandard/backend_cffi.py,sha256=CACC_Nz6fjab_zIoEpEW7xBJP1Nrryln0_9gFjmJPpQ,157105 +zstandard/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard-0.25.0.dist-info/WHEEL b/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard-0.25.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..8f98e0aeebdc2c0a3b9b5f83d43db0ef8dbc186b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard-0.25.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp311-cp311-win_amd64 + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard-0.25.0.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard-0.25.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b52955427bd6f4a2a397d05fb13fc88231b0f421 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard-0.25.0.dist-info/licenses/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2016, Gregory Szorc +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/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard-0.25.0.dist-info/top_level.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard-0.25.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..864700d2b3e63509d1e25eff308c0a99386bb4ac --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard-0.25.0.dist-info/top_level.txt @@ -0,0 +1 @@ +zstandard diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2232722489c8051d783e7e179ee3b3160e3915d7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard/__init__.py @@ -0,0 +1,217 @@ +# Copyright (c) 2017-present, Gregory Szorc +# All rights reserved. +# +# This software may be modified and distributed under the terms +# of the BSD license. See the LICENSE file for details. + +# ruff: noqa: F403, F405 + +"""Python interface to the Zstandard (zstd) compression library.""" + +from __future__ import absolute_import, unicode_literals + +# This module serves 2 roles: +# +# 1) Export the C or CFFI "backend" through a central module. +# 2) Implement additional functionality built on top of C or CFFI backend. +import builtins +import io +import os +import platform +import sys + +if sys.version_info >= (3, 12): + from collections.abc import Buffer +else: + from typing import ByteString as Buffer + +# Some Python implementations don't support C extensions. That's why we have +# a CFFI implementation in the first place. The code here import one of our +# "backends" then re-exports the symbols from this module. For convenience, +# we support falling back to the CFFI backend if the C extension can't be +# imported. But for performance reasons, we only do this on unknown Python +# implementation. Notably, for CPython we require the C extension by default. +# Because someone will inevitably want special behavior, the behavior is +# configurable via an environment variable. A potentially better way to handle +# this is to import a special ``__importpolicy__`` module or something +# defining a variable and `setup.py` could write the file with whatever +# policy was specified at build time. Until someone needs it, we go with +# the hacky but simple environment variable approach. +_module_policy = os.environ.get( + "PYTHON_ZSTANDARD_IMPORT_POLICY", "default" +).strip() + +if _module_policy == "default": + if platform.python_implementation() in ("CPython",): + from .backend_c import * # type: ignore + + backend = "cext" + elif platform.python_implementation() in ("PyPy",): + from .backend_cffi import * # type: ignore + + backend = "cffi" + else: + try: + from .backend_c import * + + backend = "cext" + except ImportError: + from .backend_cffi import * + + backend = "cffi" +elif _module_policy == "cffi_fallback": + try: + from .backend_c import * + + backend = "cext" + except ImportError: + from .backend_cffi import * + + backend = "cffi" +elif _module_policy == "rust": + from .backend_rust import * # type: ignore + + backend = "rust" +elif _module_policy == "cext": + from .backend_c import * + + backend = "cext" +elif _module_policy == "cffi": + from .backend_cffi import * + + backend = "cffi" +else: + raise ImportError( + "unknown module import policy: %s; use default, cffi_fallback, " + "cext, or cffi" % _module_policy + ) + +# Keep this in sync with python-zstandard.h, rust-ext/src/lib.rs, and debian/changelog. +__version__ = "0.25.0" + +_MODE_CLOSED = 0 +_MODE_READ = 1 +_MODE_WRITE = 2 + + +def open( + filename, + mode="rb", + cctx=None, + dctx=None, + encoding=None, + errors=None, + newline=None, + closefd=None, +): + """Create a file object with zstd (de)compression. + + The object returned from this function will be a + :py:class:`ZstdDecompressionReader` if opened for reading in binary mode, + a :py:class:`ZstdCompressionWriter` if opened for writing in binary mode, + or an ``io.TextIOWrapper`` if opened for reading or writing in text mode. + + :param filename: + ``bytes``, ``str``, or ``os.PathLike`` defining a file to open or a + file object (with a ``read()`` or ``write()`` method). + :param mode: + ``str`` File open mode. Accepts any of the open modes recognized by + ``open()``. + :param cctx: + ``ZstdCompressor`` to use for compression. If not specified and file + is opened for writing, the default ``ZstdCompressor`` will be used. + :param dctx: + ``ZstdDecompressor`` to use for decompression. If not specified and file + is opened for reading, the default ``ZstdDecompressor`` will be used. + :param encoding: + ``str`` that defines text encoding to use when file is opened in text + mode. + :param errors: + ``str`` defining text encoding error handling mode. + :param newline: + ``str`` defining newline to use in text mode. + :param closefd: + ``bool`` whether to close the file when the returned object is closed. + Only used if a file object is passed. If a filename is specified, the + opened file is always closed when the returned object is closed. + """ + normalized_mode = mode.replace("t", "") + + if normalized_mode in ("r", "rb"): + dctx = dctx or ZstdDecompressor() + open_mode = "r" + raw_open_mode = "rb" + elif normalized_mode in ("w", "wb", "a", "ab", "x", "xb"): + cctx = cctx or ZstdCompressor() + open_mode = "w" + raw_open_mode = normalized_mode + if not raw_open_mode.endswith("b"): + raw_open_mode = raw_open_mode + "b" + else: + raise ValueError("Invalid mode: {!r}".format(mode)) + + if hasattr(os, "PathLike"): + types = (str, bytes, os.PathLike) + else: + types = (str, bytes) + + if isinstance(filename, types): # type: ignore + inner_fh = builtins.open(filename, raw_open_mode) + closefd = True + elif hasattr(filename, "read") or hasattr(filename, "write"): + inner_fh = filename + closefd = bool(closefd) + else: + raise TypeError( + "filename must be a str, bytes, file or PathLike object" + ) + + if open_mode == "r": + fh = dctx.stream_reader(inner_fh, closefd=closefd) + elif open_mode == "w": + fh = cctx.stream_writer(inner_fh, closefd=closefd) + else: + raise RuntimeError("logic error in zstandard.open() handling open mode") + + if "b" not in normalized_mode: + return io.TextIOWrapper( + fh, encoding=encoding, errors=errors, newline=newline + ) + else: + return fh + + +def compress(data: Buffer, level: int = 3) -> bytes: + """Compress source data using the zstd compression format. + + This performs one-shot compression using basic/default compression + settings. + + This method is provided for convenience and is equivalent to calling + ``ZstdCompressor(level=level).compress(data)``. + + If you find yourself calling this function in a tight loop, + performance will be greater if you construct a single ``ZstdCompressor`` + and repeatedly call ``compress()`` on it. + """ + cctx = ZstdCompressor(level=level) + + return cctx.compress(data) + + +def decompress(data: Buffer, max_output_size: int = 0) -> bytes: + """Decompress a zstd frame into its original data. + + This performs one-shot decompression using basic/default compression + settings. + + This method is provided for convenience and is equivalent to calling + ``ZstdDecompressor().decompress(data, max_output_size=max_output_size)``. + + If you find yourself calling this function in a tight loop, performance + will be greater if you construct a single ``ZstdDecompressor`` and + repeatedly call ``decompress()`` on it. + """ + dctx = ZstdDecompressor() + + return dctx.decompress(data, max_output_size=max_output_size) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard/__init__.pyi b/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f1b406c2dbbe5c60afa25a7f4a0ee2e84b62c365 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard/__init__.pyi @@ -0,0 +1,481 @@ +# Copyright (c) 2016-present, Gregory Szorc +# All rights reserved. +# +# This software may be modified and distributed under the terms +# of the BSD license. See the LICENSE file for details. + +import os +from typing import ( + IO, + BinaryIO, + ByteString, + Generator, + Iterable, + List, + Optional, + Set, + Tuple, + Union, +) + +FLUSH_BLOCK: int +FLUSH_FRAME: int + +COMPRESSOBJ_FLUSH_FINISH: int +COMPRESSOBJ_FLUSH_BLOCK: int + +CONTENTSIZE_UNKNOWN: int +CONTENTSIZE_ERROR: int + +MAX_COMPRESSION_LEVEL: int + +COMPRESSION_RECOMMENDED_INPUT_SIZE: int +COMPRESSION_RECOMMENDED_OUTPUT_SIZE: int + +DECOMPRESSION_RECOMMENDED_INPUT_SIZE: int +DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE: int + +BLOCKSIZELOG_MAX: int +BLOCKSIZE_MAX: int + +WINDOWLOG_MIN: int +WINDOWLOG_MAX: int + +CHAINLOG_MIN: int +CHAINLOG_MAX: int +HASHLOG_MIN: int +HASHLOG_MAX: int +MINMATCH_MIN: int +MINMATCH_MAX: int +SEARCHLOG_MIN: int +SEARCHLOG_MAX: int +SEARCHLENGTH_MIN: int +SEARCHLENGTH_MAX: int +TARGETLENGTH_MIN: int +TARGETLENGTH_MAX: int +LDM_MINMATCH_MIN: int +LDM_MINMATCH_MAX: int +LDM_BUCKETSIZELOG_MAX: int + +STRATEGY_FAST: int +STRATEGY_DFAST: int +STRATEGY_GREEDY: int +STRATEGY_LAZY: int +STRATEGY_LAZY2: int +STRATEGY_BTLAZY2: int +STRATEGY_BTOPT: int +STRATEGY_BTULTRA: int +STRATEGY_BTULTRA2: int + +DICT_TYPE_AUTO: int +DICT_TYPE_RAWCONTENT: int +DICT_TYPE_FULLDICT: int + +FORMAT_ZSTD1: int +FORMAT_ZSTD1_MAGICLESS: int + +ZSTD_VERSION: Tuple[int, int, int] +FRAME_HEADER: bytes +MAGIC_NUMBER: int + +backend: str +backend_features: Set[str] +__version__: str + +class ZstdError(Exception): ... + +class BufferSegment(object): + offset: int + def __len__(self) -> int: ... + def tobytes(self) -> bytes: ... + +class BufferSegments(object): + def __len__(self) -> int: ... + def __getitem__(self, i: int) -> BufferSegment: ... + +class BufferWithSegments(object): + size: int + def __init__(self, data: ByteString, segments: ByteString): ... + def __len__(self) -> int: ... + def __getitem__(self, i: int) -> BufferSegment: ... + def segments(self): ... + def tobytes(self) -> bytes: ... + +class BufferWithSegmentsCollection(object): + def __init__(self, *args): ... + def __len__(self) -> int: ... + def __getitem__(self, i: int) -> BufferSegment: ... + def size(self) -> int: ... + +class ZstdCompressionParameters(object): + @staticmethod + def from_level( + level: int, source_size: int = ..., dict_size: int = ..., **kwargs + ) -> "ZstdCompressionParameters": ... + def __init__( + self, + format: int = ..., + compression_level: int = ..., + window_log: int = ..., + hash_log: int = ..., + chain_log: int = ..., + search_log: int = ..., + min_match: int = ..., + target_length: int = ..., + strategy: int = ..., + write_content_size: int = ..., + write_checksum: int = ..., + write_dict_id: int = ..., + job_size: int = ..., + overlap_log: int = ..., + force_max_window: int = ..., + enable_ldm: int = ..., + ldm_hash_log: int = ..., + ldm_min_match: int = ..., + ldm_bucket_size_log: int = ..., + ldm_hash_rate_log: int = ..., + threads: int = ..., + ): ... + @property + def format(self) -> int: ... + @property + def compression_level(self) -> int: ... + @property + def window_log(self) -> int: ... + @property + def hash_log(self) -> int: ... + @property + def chain_log(self) -> int: ... + @property + def search_log(self) -> int: ... + @property + def min_match(self) -> int: ... + @property + def target_length(self) -> int: ... + @property + def strategy(self) -> int: ... + @property + def write_content_size(self) -> int: ... + @property + def write_checksum(self) -> int: ... + @property + def write_dict_id(self) -> int: ... + @property + def job_size(self) -> int: ... + @property + def overlap_log(self) -> int: ... + @property + def force_max_window(self) -> int: ... + @property + def enable_ldm(self) -> int: ... + @property + def ldm_hash_log(self) -> int: ... + @property + def ldm_min_match(self) -> int: ... + @property + def ldm_bucket_size_log(self) -> int: ... + @property + def ldm_hash_rate_log(self) -> int: ... + @property + def threads(self) -> int: ... + def estimated_compression_context_size(self) -> int: ... + +class CompressionParameters(ZstdCompressionParameters): ... + +class ZstdCompressionDict(object): + k: int + d: int + def __init__( + self, + data: ByteString, + dict_type: int = ..., + k: int = ..., + d: int = ..., + ): ... + def __len__(self) -> int: ... + def dict_id(self) -> int: ... + def as_bytes(self) -> bytes: ... + def precompute_compress( + self, + level: int = ..., + compression_params: ZstdCompressionParameters = ..., + ): ... + +class ZstdCompressionObj(object): + def compress(self, data: ByteString) -> bytes: ... + def flush(self, flush_mode: int = ...) -> bytes: ... + +class ZstdCompressionChunker(object): + def compress(self, data: ByteString): ... + def flush(self): ... + def finish(self): ... + +class ZstdCompressionReader(BinaryIO): + def __enter__(self) -> "ZstdCompressionReader": ... + def __exit__(self, exc_type, exc_value, exc_tb): ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def seekable(self) -> bool: ... + def readline(self, limit: int = ...) -> bytes: ... + def readlines(self, hint: int = ...) -> List[bytes]: ... + def write(self, data: ByteString): ... + def writelines(self, data: Iterable[bytes]): ... + def isatty(self) -> bool: ... + def flush(self): ... + def close(self): ... + @property + def closed(self) -> bool: ... + def tell(self) -> int: ... + def readall(self) -> bytes: ... + def __iter__(self): ... + def __next__(self): ... + def next(self): ... + def read(self, size: int = ...) -> bytes: ... + def read1(self, size: int = ...) -> bytes: ... + def readinto(self, b) -> int: ... + def readinto1(self, b) -> int: ... + +class ZstdCompressionWriter(BinaryIO): + def __enter__(self) -> "ZstdCompressionWriter": ... + def __exit__(self, exc_type, exc_value, exc_tb): ... + def memory_size(self) -> int: ... + def fileno(self) -> int: ... + def close(self): ... + @property + def closed(self) -> bool: ... + def isatty(self) -> bool: ... + def readable(self) -> bool: ... + def readline(self, size: int = ...) -> bytes: ... + def readlines(self, hint: int = ...) -> List[bytes]: ... + def seek(self, offset: int, whence: int = ...): ... + def seekable(self) -> bool: ... + def truncate(self, size: int = ...): ... + def writable(self) -> bool: ... + def writelines(self, lines: Iterable[bytes]): ... + def read(self, size: int = ...) -> bytes: ... + def readall(self) -> bytes: ... + def readinto(self, b): ... + def write(self, data: ByteString) -> int: ... + def flush(self, flush_mode: int = ...) -> int: ... + def tell(self) -> int: ... + +class ZstdCompressor(object): + def __init__( + self, + level: int = ..., + dict_data: Optional[ZstdCompressionDict] = ..., + compression_params: Optional[ZstdCompressionParameters] = ..., + write_checksum: Optional[bool] = ..., + write_content_size: Optional[bool] = ..., + write_dict_id: Optional[bool] = ..., + threads: int = ..., + ): ... + def memory_size(self) -> int: ... + def compress(self, data: ByteString) -> bytes: ... + def compressobj(self, size: int = ...) -> ZstdCompressionObj: ... + def chunker( + self, size: int = ..., chunk_size: int = ... + ) -> ZstdCompressionChunker: ... + def copy_stream( + self, + ifh: IO[bytes], + ofh: IO[bytes], + size: int = ..., + read_size: int = ..., + write_size: int = ..., + ) -> Tuple[int, int]: ... + def stream_reader( + self, + source: Union[IO[bytes], ByteString], + size: int = ..., + read_size: int = ..., + *, + closefd: bool = ..., + ) -> ZstdCompressionReader: ... + def stream_writer( + self, + writer: IO[bytes], + size: int = ..., + write_size: int = ..., + write_return_read: bool = ..., + *, + closefd: bool = ..., + ) -> ZstdCompressionWriter: ... + def read_to_iter( + self, + reader: Union[IO[bytes], ByteString], + size: int = ..., + read_size: int = ..., + write_size: int = ..., + ) -> Generator[bytes, None, None]: ... + def frame_progression(self) -> Tuple[int, int, int]: ... + def multi_compress_to_buffer( + self, + data: Union[ + BufferWithSegments, + BufferWithSegmentsCollection, + List[ByteString], + ], + threads: int = ..., + ) -> BufferWithSegmentsCollection: ... + +class ZstdDecompressionObj(object): + def decompress(self, data: ByteString) -> bytes: ... + def flush(self, length: int = ...) -> bytes: ... + @property + def unused_data(self) -> bytes: ... + @property + def unconsumed_tail(self) -> bytes: ... + @property + def eof(self) -> bool: ... + +class ZstdDecompressionReader(BinaryIO): + def __enter__(self) -> "ZstdDecompressionReader": ... + def __exit__(self, exc_type, exc_value, exc_tb): ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def seekable(self) -> bool: ... + def readline(self, size: int = ...): ... + def readlines(self, hint: int = ...): ... + def write(self, data: ByteString): ... + def writelines(self, lines: Iterable[bytes]): ... + def isatty(self) -> bool: ... + def flush(self): ... + def close(self): ... + @property + def closed(self) -> bool: ... + def tell(self) -> int: ... + def readall(self) -> bytes: ... + def __iter__(self): ... + def __next__(self): ... + def next(self): ... + def read(self, size: int = ...) -> bytes: ... + def readinto(self, b) -> int: ... + def read1(self, size: int = ...) -> bytes: ... + def readinto1(self, b) -> int: ... + def seek(self, pos: int, whence: int = ...) -> int: ... + +class ZstdDecompressionWriter(BinaryIO): + def __enter__(self) -> "ZstdDecompressionWriter": ... + def __exit__(self, exc_type, exc_value, exc_tb): ... + def memory_size(self) -> int: ... + def close(self): ... + @property + def closed(self) -> bool: ... + def fileno(self) -> int: ... + def flush(self): ... + def isatty(self) -> bool: ... + def readable(self) -> bool: ... + def readline(self, size: int = ...): ... + def readlines(self, hint: int = ...): ... + def seek(self, offset: int, whence: int = ...): ... + def seekable(self) -> bool: ... + def tell(self): ... + def truncate(self, size: int = ...): ... + def writable(self) -> bool: ... + def writelines(self, lines: Iterable[bytes]): ... + def read(self, size: int = ...): ... + def readall(self): ... + def readinto(self, b): ... + def write(self, data: ByteString) -> int: ... + +class ZstdDecompressor(object): + def __init__( + self, + dict_data: Optional[ZstdCompressionDict] = ..., + max_window_size: int = ..., + format: int = ..., + ): ... + def memory_size(self) -> int: ... + def decompress( + self, + data: ByteString, + max_output_size: int = ..., + read_across_frames: bool = ..., + allow_extra_data: bool = ..., + ) -> bytes: ... + def stream_reader( + self, + source: Union[IO[bytes], ByteString], + read_size: int = ..., + read_across_frames: bool = ..., + *, + closefd=False, + ) -> ZstdDecompressionReader: ... + def decompressobj( + self, write_size: int = ..., read_across_frames: bool = False + ) -> ZstdDecompressionObj: ... + def read_to_iter( + self, + reader: Union[IO[bytes], ByteString], + read_size: int = ..., + write_size: int = ..., + skip_bytes: int = ..., + ) -> Generator[bytes, None, None]: ... + def stream_writer( + self, + writer: IO[bytes], + write_size: int = ..., + write_return_read: bool = ..., + *, + closefd: bool = ..., + ) -> ZstdDecompressionWriter: ... + def copy_stream( + self, + ifh: IO[bytes], + ofh: IO[bytes], + read_size: int = ..., + write_size: int = ..., + ) -> Tuple[int, int]: ... + def decompress_content_dict_chain( + self, frames: list[ByteString] + ) -> bytes: ... + def multi_decompress_to_buffer( + self, + frames: Union[ + BufferWithSegments, + BufferWithSegmentsCollection, + List[ByteString], + ], + decompressed_sizes: ByteString = ..., + threads: int = ..., + ) -> BufferWithSegmentsCollection: ... + +class FrameParameters(object): + content_size: int + window_size: int + dict_id: int + has_checksum: bool + +def estimate_decompression_context_size() -> int: ... +def frame_content_size(data: ByteString) -> int: ... +def frame_header_size(data: ByteString) -> int: ... +def get_frame_parameters( + data: ByteString, format: Optional[int] = None +) -> FrameParameters: ... +def train_dictionary( + dict_size: int, + samples: list[ByteString], + k: int = ..., + d: int = ..., + f: int = ..., + split_point: float = ..., + accel: int = ..., + notifications: int = ..., + dict_id: int = ..., + level: int = ..., + steps: int = ..., + threads: int = ..., +) -> ZstdCompressionDict: ... +def open( + filename: Union[bytes, str, os.PathLike, BinaryIO], + mode: str = ..., + cctx: Optional[ZstdCompressor] = ..., + dctx: Optional[ZstdDecompressor] = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., + closefd: bool = ..., +): ... +def compress(data: ByteString, level: int = ...) -> bytes: ... +def decompress(data: ByteString, max_output_size: int = ...) -> bytes: ... diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c5ce013460d30c57a2bd4d63bf259a98ad52d7f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard/backend_cffi.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard/backend_cffi.py new file mode 100644 index 0000000000000000000000000000000000000000..7de35aa1a0e814fa37c8af605db3eb16d69e23d3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard/backend_cffi.py @@ -0,0 +1,4478 @@ +# Copyright (c) 2016-present, Gregory Szorc +# All rights reserved. +# +# This software may be modified and distributed under the terms +# of the BSD license. See the LICENSE file for details. + +"""Python interface to the Zstandard (zstd) compression library.""" + +from __future__ import absolute_import, unicode_literals + +# This should match what the C extension exports. +__all__ = [ + "BufferSegment", + "BufferSegments", + "BufferWithSegments", + "BufferWithSegmentsCollection", + "ZstdCompressionChunker", + "ZstdCompressionDict", + "ZstdCompressionObj", + "ZstdCompressionParameters", + "ZstdCompressionReader", + "ZstdCompressionWriter", + "ZstdCompressor", + "ZstdDecompressionObj", + "ZstdDecompressionReader", + "ZstdDecompressionWriter", + "ZstdDecompressor", + "ZstdError", + "FrameParameters", + "backend_features", + "estimate_decompression_context_size", + "frame_content_size", + "frame_header_size", + "get_frame_parameters", + "train_dictionary", + # Constants. + "FLUSH_BLOCK", + "FLUSH_FRAME", + "COMPRESSOBJ_FLUSH_FINISH", + "COMPRESSOBJ_FLUSH_BLOCK", + "ZSTD_VERSION", + "FRAME_HEADER", + "CONTENTSIZE_UNKNOWN", + "CONTENTSIZE_ERROR", + "MAX_COMPRESSION_LEVEL", + "COMPRESSION_RECOMMENDED_INPUT_SIZE", + "COMPRESSION_RECOMMENDED_OUTPUT_SIZE", + "DECOMPRESSION_RECOMMENDED_INPUT_SIZE", + "DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE", + "MAGIC_NUMBER", + "BLOCKSIZELOG_MAX", + "BLOCKSIZE_MAX", + "WINDOWLOG_MIN", + "WINDOWLOG_MAX", + "CHAINLOG_MIN", + "CHAINLOG_MAX", + "HASHLOG_MIN", + "HASHLOG_MAX", + "MINMATCH_MIN", + "MINMATCH_MAX", + "SEARCHLOG_MIN", + "SEARCHLOG_MAX", + "SEARCHLENGTH_MIN", + "SEARCHLENGTH_MAX", + "TARGETLENGTH_MIN", + "TARGETLENGTH_MAX", + "LDM_MINMATCH_MIN", + "LDM_MINMATCH_MAX", + "LDM_BUCKETSIZELOG_MAX", + "STRATEGY_FAST", + "STRATEGY_DFAST", + "STRATEGY_GREEDY", + "STRATEGY_LAZY", + "STRATEGY_LAZY2", + "STRATEGY_BTLAZY2", + "STRATEGY_BTOPT", + "STRATEGY_BTULTRA", + "STRATEGY_BTULTRA2", + "DICT_TYPE_AUTO", + "DICT_TYPE_RAWCONTENT", + "DICT_TYPE_FULLDICT", + "FORMAT_ZSTD1", + "FORMAT_ZSTD1_MAGICLESS", +] + +import io +import os + +from ._cffi import ( # type: ignore + ffi, + lib, +) + +backend_features = set() # type: ignore + +COMPRESSION_RECOMMENDED_INPUT_SIZE = lib.ZSTD_CStreamInSize() +COMPRESSION_RECOMMENDED_OUTPUT_SIZE = lib.ZSTD_CStreamOutSize() +DECOMPRESSION_RECOMMENDED_INPUT_SIZE = lib.ZSTD_DStreamInSize() +DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE = lib.ZSTD_DStreamOutSize() + +new_nonzero = ffi.new_allocator(should_clear_after_alloc=False) + +MAX_COMPRESSION_LEVEL = lib.ZSTD_maxCLevel() +MAGIC_NUMBER = lib.ZSTD_MAGICNUMBER +FRAME_HEADER = b"\x28\xb5\x2f\xfd" +CONTENTSIZE_UNKNOWN = lib.ZSTD_CONTENTSIZE_UNKNOWN +CONTENTSIZE_ERROR = lib.ZSTD_CONTENTSIZE_ERROR +ZSTD_VERSION = ( + lib.ZSTD_VERSION_MAJOR, + lib.ZSTD_VERSION_MINOR, + lib.ZSTD_VERSION_RELEASE, +) + +BLOCKSIZELOG_MAX = lib.ZSTD_BLOCKSIZELOG_MAX +BLOCKSIZE_MAX = lib.ZSTD_BLOCKSIZE_MAX +WINDOWLOG_MIN = lib.ZSTD_WINDOWLOG_MIN +WINDOWLOG_MAX = lib.ZSTD_WINDOWLOG_MAX +CHAINLOG_MIN = lib.ZSTD_CHAINLOG_MIN +CHAINLOG_MAX = lib.ZSTD_CHAINLOG_MAX +HASHLOG_MIN = lib.ZSTD_HASHLOG_MIN +HASHLOG_MAX = lib.ZSTD_HASHLOG_MAX +MINMATCH_MIN = lib.ZSTD_MINMATCH_MIN +MINMATCH_MAX = lib.ZSTD_MINMATCH_MAX +SEARCHLOG_MIN = lib.ZSTD_SEARCHLOG_MIN +SEARCHLOG_MAX = lib.ZSTD_SEARCHLOG_MAX +SEARCHLENGTH_MIN = lib.ZSTD_MINMATCH_MIN +SEARCHLENGTH_MAX = lib.ZSTD_MINMATCH_MAX +TARGETLENGTH_MIN = lib.ZSTD_TARGETLENGTH_MIN +TARGETLENGTH_MAX = lib.ZSTD_TARGETLENGTH_MAX +LDM_MINMATCH_MIN = lib.ZSTD_LDM_MINMATCH_MIN +LDM_MINMATCH_MAX = lib.ZSTD_LDM_MINMATCH_MAX +LDM_BUCKETSIZELOG_MAX = lib.ZSTD_LDM_BUCKETSIZELOG_MAX + +STRATEGY_FAST = lib.ZSTD_fast +STRATEGY_DFAST = lib.ZSTD_dfast +STRATEGY_GREEDY = lib.ZSTD_greedy +STRATEGY_LAZY = lib.ZSTD_lazy +STRATEGY_LAZY2 = lib.ZSTD_lazy2 +STRATEGY_BTLAZY2 = lib.ZSTD_btlazy2 +STRATEGY_BTOPT = lib.ZSTD_btopt +STRATEGY_BTULTRA = lib.ZSTD_btultra +STRATEGY_BTULTRA2 = lib.ZSTD_btultra2 + +DICT_TYPE_AUTO = lib.ZSTD_dct_auto +DICT_TYPE_RAWCONTENT = lib.ZSTD_dct_rawContent +DICT_TYPE_FULLDICT = lib.ZSTD_dct_fullDict + +FORMAT_ZSTD1 = lib.ZSTD_f_zstd1 +FORMAT_ZSTD1_MAGICLESS = lib.ZSTD_f_zstd1_magicless + +FLUSH_BLOCK = 0 +FLUSH_FRAME = 1 + +COMPRESSOBJ_FLUSH_FINISH = 0 +COMPRESSOBJ_FLUSH_BLOCK = 1 + + +def _cpu_count(): + # os.cpu_count() was introducd in Python 3.4. + try: + return os.cpu_count() or 0 + except AttributeError: + pass + + # Linux. + try: + return os.sysconf("SC_NPROCESSORS_ONLN") + except (AttributeError, ValueError): + pass + + # TODO implement on other platforms. + return 0 + + +class BufferSegment: + """Represents a segment within a ``BufferWithSegments``. + + This type is essentially a reference to N bytes within a + ``BufferWithSegments``. + + The object conforms to the buffer protocol. + """ + + @property + def offset(self): + """The byte offset of this segment within its parent buffer.""" + raise NotImplementedError() + + def __len__(self): + """Obtain the length of the segment, in bytes.""" + raise NotImplementedError() + + def tobytes(self): + """Obtain bytes copy of this segment.""" + raise NotImplementedError() + + +class BufferSegments: + """Represents an array of ``(offset, length)`` integers. + + This type is effectively an index used by :py:class:`BufferWithSegments`. + + The array members are 64-bit unsigned integers using host/native bit order. + + Instances conform to the buffer protocol. + """ + + +class BufferWithSegments: + """A memory buffer containing N discrete items of known lengths. + + This type is essentially a fixed size memory address and an array + of 2-tuples of ``(offset, length)`` 64-bit unsigned native-endian + integers defining the byte offset and length of each segment within + the buffer. + + Instances behave like containers. + + Instances also conform to the buffer protocol. So a reference to the + backing bytes can be obtained via ``memoryview(o)``. A *copy* of the + backing bytes can be obtained via ``.tobytes()``. + + This type exists to facilitate operations against N>1 items without + the overhead of Python object creation and management. Used with + APIs like :py:meth:`ZstdDecompressor.multi_decompress_to_buffer`, it + is possible to decompress many objects in parallel without the GIL + held, leading to even better performance. + """ + + @property + def size(self): + """Total sizein bytes of the backing buffer.""" + raise NotImplementedError() + + def __len__(self): + raise NotImplementedError() + + def __getitem__(self, i): + """Obtains a segment within the buffer. + + The returned object references memory within this buffer. + + :param i: + Integer index of segment to retrieve. + :return: + :py:class:`BufferSegment` + """ + raise NotImplementedError() + + def segments(self): + """Obtain the array of ``(offset, length)`` segments in the buffer. + + :return: + :py:class:`BufferSegments` + """ + raise NotImplementedError() + + def tobytes(self): + """Obtain bytes copy of this instance.""" + raise NotImplementedError() + + +class BufferWithSegmentsCollection: + """A virtual spanning view over multiple BufferWithSegments. + + Instances are constructed from 1 or more :py:class:`BufferWithSegments` + instances. The resulting object behaves like an ordered sequence whose + members are the segments within each ``BufferWithSegments``. + + If the object is composed of 2 ``BufferWithSegments`` instances with the + first having 2 segments and the second have 3 segments, then ``b[0]`` + and ``b[1]`` access segments in the first object and ``b[2]``, ``b[3]``, + and ``b[4]`` access segments from the second. + """ + + def __len__(self): + """The number of segments within all ``BufferWithSegments``.""" + raise NotImplementedError() + + def __getitem__(self, i): + """Obtain the ``BufferSegment`` at an offset.""" + raise NotImplementedError() + + +class ZstdError(Exception): + pass + + +def _zstd_error(zresult): + # Resolves to bytes on Python 2 and 3. We use the string for formatting + # into error messages, which will be literal unicode. So convert it to + # unicode. + return ffi.string(lib.ZSTD_getErrorName(zresult)).decode("utf-8") + + +def _make_cctx_params(params): + res = lib.ZSTD_createCCtxParams() + if res == ffi.NULL: + raise MemoryError() + + res = ffi.gc(res, lib.ZSTD_freeCCtxParams) + + attrs = [ + (lib.ZSTD_c_format, params.format), + (lib.ZSTD_c_compressionLevel, params.compression_level), + (lib.ZSTD_c_windowLog, params.window_log), + (lib.ZSTD_c_hashLog, params.hash_log), + (lib.ZSTD_c_chainLog, params.chain_log), + (lib.ZSTD_c_searchLog, params.search_log), + (lib.ZSTD_c_minMatch, params.min_match), + (lib.ZSTD_c_targetLength, params.target_length), + (lib.ZSTD_c_strategy, params.strategy), + (lib.ZSTD_c_contentSizeFlag, params.write_content_size), + (lib.ZSTD_c_checksumFlag, params.write_checksum), + (lib.ZSTD_c_dictIDFlag, params.write_dict_id), + (lib.ZSTD_c_nbWorkers, params.threads), + (lib.ZSTD_c_jobSize, params.job_size), + (lib.ZSTD_c_overlapLog, params.overlap_log), + (lib.ZSTD_c_forceMaxWindow, params.force_max_window), + (lib.ZSTD_c_enableLongDistanceMatching, params.enable_ldm), + (lib.ZSTD_c_ldmHashLog, params.ldm_hash_log), + (lib.ZSTD_c_ldmMinMatch, params.ldm_min_match), + (lib.ZSTD_c_ldmBucketSizeLog, params.ldm_bucket_size_log), + (lib.ZSTD_c_ldmHashRateLog, params.ldm_hash_rate_log), + ] + + for param, value in attrs: + _set_compression_parameter(res, param, value) + + return res + + +class ZstdCompressionParameters(object): + """Low-level zstd compression parameters. + + This type represents a collection of parameters to control how zstd + compression is performed. + + Instances can be constructed from raw parameters or derived from a + base set of defaults specified from a compression level (recommended) + via :py:meth:`ZstdCompressionParameters.from_level`. + + >>> # Derive compression settings for compression level 7. + >>> params = zstandard.ZstdCompressionParameters.from_level(7) + + >>> # With an input size of 1MB + >>> params = zstandard.ZstdCompressionParameters.from_level(7, source_size=1048576) + + Using ``from_level()``, it is also possible to override individual compression + parameters or to define additional settings that aren't automatically derived. + e.g.: + + >>> params = zstandard.ZstdCompressionParameters.from_level(4, window_log=10) + >>> params = zstandard.ZstdCompressionParameters.from_level(5, threads=4) + + Or you can define low-level compression settings directly: + + >>> params = zstandard.ZstdCompressionParameters(window_log=12, enable_ldm=True) + + Once a ``ZstdCompressionParameters`` instance is obtained, it can be used to + configure a compressor: + + >>> cctx = zstandard.ZstdCompressor(compression_params=params) + + Some of these are very low-level settings. It may help to consult the official + zstandard documentation for their behavior. Look for the ``ZSTD_p_*`` constants + in ``zstd.h`` (https://github.com/facebook/zstd/blob/dev/lib/zstd.h). + """ + + @staticmethod + def from_level(level, source_size=0, dict_size=0, **kwargs): + """Create compression parameters from a compression level. + + :param level: + Integer compression level. + :param source_size: + Integer size in bytes of source to be compressed. + :param dict_size: + Integer size in bytes of compression dictionary to use. + :return: + :py:class:`ZstdCompressionParameters` + """ + params = lib.ZSTD_getCParams(level, source_size, dict_size) + + args = { + "window_log": "windowLog", + "chain_log": "chainLog", + "hash_log": "hashLog", + "search_log": "searchLog", + "min_match": "minMatch", + "target_length": "targetLength", + "strategy": "strategy", + } + + for arg, attr in args.items(): + if arg not in kwargs: + kwargs[arg] = getattr(params, attr) + + return ZstdCompressionParameters(**kwargs) + + def __init__( + self, + format=0, + compression_level=0, + window_log=0, + hash_log=0, + chain_log=0, + search_log=0, + min_match=0, + target_length=0, + strategy=-1, + write_content_size=1, + write_checksum=0, + write_dict_id=0, + job_size=0, + overlap_log=-1, + force_max_window=0, + enable_ldm=0, + ldm_hash_log=0, + ldm_min_match=0, + ldm_bucket_size_log=0, + ldm_hash_rate_log=-1, + threads=0, + ): + params = lib.ZSTD_createCCtxParams() + if params == ffi.NULL: + raise MemoryError() + + params = ffi.gc(params, lib.ZSTD_freeCCtxParams) + + self._params = params + + if threads < 0: + threads = _cpu_count() + + # We need to set ZSTD_c_nbWorkers before ZSTD_c_jobSize and ZSTD_c_overlapLog + # because setting ZSTD_c_nbWorkers resets the other parameters. + _set_compression_parameter(params, lib.ZSTD_c_nbWorkers, threads) + + _set_compression_parameter(params, lib.ZSTD_c_format, format) + _set_compression_parameter( + params, lib.ZSTD_c_compressionLevel, compression_level + ) + _set_compression_parameter(params, lib.ZSTD_c_windowLog, window_log) + _set_compression_parameter(params, lib.ZSTD_c_hashLog, hash_log) + _set_compression_parameter(params, lib.ZSTD_c_chainLog, chain_log) + _set_compression_parameter(params, lib.ZSTD_c_searchLog, search_log) + _set_compression_parameter(params, lib.ZSTD_c_minMatch, min_match) + _set_compression_parameter( + params, lib.ZSTD_c_targetLength, target_length + ) + + if strategy == -1: + strategy = 0 + + _set_compression_parameter(params, lib.ZSTD_c_strategy, strategy) + _set_compression_parameter( + params, lib.ZSTD_c_contentSizeFlag, write_content_size + ) + _set_compression_parameter( + params, lib.ZSTD_c_checksumFlag, write_checksum + ) + _set_compression_parameter(params, lib.ZSTD_c_dictIDFlag, write_dict_id) + _set_compression_parameter(params, lib.ZSTD_c_jobSize, job_size) + + if overlap_log == -1: + overlap_log = 0 + + _set_compression_parameter(params, lib.ZSTD_c_overlapLog, overlap_log) + _set_compression_parameter( + params, lib.ZSTD_c_forceMaxWindow, force_max_window + ) + _set_compression_parameter( + params, lib.ZSTD_c_enableLongDistanceMatching, enable_ldm + ) + _set_compression_parameter(params, lib.ZSTD_c_ldmHashLog, ldm_hash_log) + _set_compression_parameter( + params, lib.ZSTD_c_ldmMinMatch, ldm_min_match + ) + _set_compression_parameter( + params, lib.ZSTD_c_ldmBucketSizeLog, ldm_bucket_size_log + ) + + if ldm_hash_rate_log == -1: + ldm_hash_rate_log = 0 + + _set_compression_parameter( + params, lib.ZSTD_c_ldmHashRateLog, ldm_hash_rate_log + ) + + @property + def format(self): + return _get_compression_parameter(self._params, lib.ZSTD_c_format) + + @property + def compression_level(self): + return _get_compression_parameter( + self._params, lib.ZSTD_c_compressionLevel + ) + + @property + def window_log(self): + return _get_compression_parameter(self._params, lib.ZSTD_c_windowLog) + + @property + def hash_log(self): + return _get_compression_parameter(self._params, lib.ZSTD_c_hashLog) + + @property + def chain_log(self): + return _get_compression_parameter(self._params, lib.ZSTD_c_chainLog) + + @property + def search_log(self): + return _get_compression_parameter(self._params, lib.ZSTD_c_searchLog) + + @property + def min_match(self): + return _get_compression_parameter(self._params, lib.ZSTD_c_minMatch) + + @property + def target_length(self): + return _get_compression_parameter(self._params, lib.ZSTD_c_targetLength) + + @property + def strategy(self): + return _get_compression_parameter(self._params, lib.ZSTD_c_strategy) + + @property + def write_content_size(self): + return _get_compression_parameter( + self._params, lib.ZSTD_c_contentSizeFlag + ) + + @property + def write_checksum(self): + return _get_compression_parameter(self._params, lib.ZSTD_c_checksumFlag) + + @property + def write_dict_id(self): + return _get_compression_parameter(self._params, lib.ZSTD_c_dictIDFlag) + + @property + def job_size(self): + return _get_compression_parameter(self._params, lib.ZSTD_c_jobSize) + + @property + def overlap_log(self): + return _get_compression_parameter(self._params, lib.ZSTD_c_overlapLog) + + @property + def force_max_window(self): + return _get_compression_parameter( + self._params, lib.ZSTD_c_forceMaxWindow + ) + + @property + def enable_ldm(self): + return _get_compression_parameter( + self._params, lib.ZSTD_c_enableLongDistanceMatching + ) + + @property + def ldm_hash_log(self): + return _get_compression_parameter(self._params, lib.ZSTD_c_ldmHashLog) + + @property + def ldm_min_match(self): + return _get_compression_parameter(self._params, lib.ZSTD_c_ldmMinMatch) + + @property + def ldm_bucket_size_log(self): + return _get_compression_parameter( + self._params, lib.ZSTD_c_ldmBucketSizeLog + ) + + @property + def ldm_hash_rate_log(self): + return _get_compression_parameter( + self._params, lib.ZSTD_c_ldmHashRateLog + ) + + @property + def threads(self): + return _get_compression_parameter(self._params, lib.ZSTD_c_nbWorkers) + + def estimated_compression_context_size(self): + """Estimated size in bytes needed to compress with these parameters.""" + return lib.ZSTD_estimateCCtxSize_usingCCtxParams(self._params) + + +def estimate_decompression_context_size(): + """Estimate the memory size requirements for a decompressor instance. + + :return: + Integer number of bytes. + """ + return lib.ZSTD_estimateDCtxSize() + + +def _set_compression_parameter(params, param, value): + zresult = lib.ZSTD_CCtxParams_setParameter(params, param, value) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "unable to set compression context parameter: %s" + % _zstd_error(zresult) + ) + + +def _get_compression_parameter(params, param): + result = ffi.new("int *") + + zresult = lib.ZSTD_CCtxParams_getParameter(params, param, result) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "unable to get compression context parameter: %s" + % _zstd_error(zresult) + ) + + return result[0] + + +class ZstdCompressionWriter(object): + """Writable compressing stream wrapper. + + ``ZstdCompressionWriter`` is a write-only stream interface for writing + compressed data to another stream. + + This type conforms to the ``io.RawIOBase`` interface and should be usable + by any type that operates against a *file-object* (``typing.BinaryIO`` + in Python type hinting speak). Only methods that involve writing will do + useful things. + + As data is written to this stream (e.g. via ``write()``), that data + is sent to the compressor. As compressed data becomes available from + the compressor, it is sent to the underlying stream by calling its + ``write()`` method. + + Both ``write()`` and ``flush()`` return the number of bytes written to the + object's ``write()``. In many cases, small inputs do not accumulate enough + data to cause a write and ``write()`` will return ``0``. + + Calling ``close()`` will mark the stream as closed and subsequent I/O + operations will raise ``ValueError`` (per the documented behavior of + ``io.RawIOBase``). ``close()`` will also call ``close()`` on the underlying + stream if such a method exists and the instance was constructed with + ``closefd=True`` + + Instances are obtained by calling :py:meth:`ZstdCompressor.stream_writer`. + + Typically usage is as follows: + + >>> cctx = zstandard.ZstdCompressor(level=10) + >>> compressor = cctx.stream_writer(fh) + >>> compressor.write(b"chunk 0\\n") + >>> compressor.write(b"chunk 1\\n") + >>> compressor.flush() + >>> # Receiver will be able to decode ``chunk 0\\nchunk 1\\n`` at this point. + >>> # Receiver is also expecting more data in the zstd *frame*. + >>> + >>> compressor.write(b"chunk 2\\n") + >>> compressor.flush(zstandard.FLUSH_FRAME) + >>> # Receiver will be able to decode ``chunk 0\\nchunk 1\\nchunk 2``. + >>> # Receiver is expecting no more data, as the zstd frame is closed. + >>> # Any future calls to ``write()`` at this point will construct a new + >>> # zstd frame. + + Instances can be used as context managers. Exiting the context manager is + the equivalent of calling ``close()``, which is equivalent to calling + ``flush(zstandard.FLUSH_FRAME)``: + + >>> cctx = zstandard.ZstdCompressor(level=10) + >>> with cctx.stream_writer(fh) as compressor: + ... compressor.write(b'chunk 0') + ... compressor.write(b'chunk 1') + ... ... + + .. important:: + + If ``flush(FLUSH_FRAME)`` is not called, emitted data doesn't + constitute a full zstd *frame* and consumers of this data may complain + about malformed input. It is recommended to use instances as a context + manager to ensure *frames* are properly finished. + + If the size of the data being fed to this streaming compressor is known, + you can declare it before compression begins: + + >>> cctx = zstandard.ZstdCompressor() + >>> with cctx.stream_writer(fh, size=data_len) as compressor: + ... compressor.write(chunk0) + ... compressor.write(chunk1) + ... ... + + Declaring the size of the source data allows compression parameters to + be tuned. And if ``write_content_size`` is used, it also results in the + content size being written into the frame header of the output data. + + The size of chunks being ``write()`` to the destination can be specified: + + >>> cctx = zstandard.ZstdCompressor() + >>> with cctx.stream_writer(fh, write_size=32768) as compressor: + ... ... + + To see how much memory is being used by the streaming compressor: + + >>> cctx = zstandard.ZstdCompressor() + >>> with cctx.stream_writer(fh) as compressor: + ... ... + ... byte_size = compressor.memory_size() + + Thte total number of bytes written so far are exposed via ``tell()``: + + >>> cctx = zstandard.ZstdCompressor() + >>> with cctx.stream_writer(fh) as compressor: + ... ... + ... total_written = compressor.tell() + + ``stream_writer()`` accepts a ``write_return_read`` boolean argument to + control the return value of ``write()``. When ``False`` (the default), + ``write()`` returns the number of bytes that were ``write()``'en to the + underlying object. When ``True``, ``write()`` returns the number of bytes + read from the input that were subsequently written to the compressor. + ``True`` is the *proper* behavior for ``write()`` as specified by the + ``io.RawIOBase`` interface and will become the default value in a future + release. + """ + + def __init__( + self, + compressor, + writer, + source_size, + write_size, + write_return_read, + closefd=True, + ): + self._compressor = compressor + self._writer = writer + self._write_size = write_size + self._write_return_read = bool(write_return_read) + self._closefd = bool(closefd) + self._entered = False + self._closing = False + self._closed = False + self._bytes_compressed = 0 + + self._dst_buffer = ffi.new("char[]", write_size) + self._out_buffer = ffi.new("ZSTD_outBuffer *") + self._out_buffer.dst = self._dst_buffer + self._out_buffer.size = len(self._dst_buffer) + self._out_buffer.pos = 0 + + zresult = lib.ZSTD_CCtx_setPledgedSrcSize(compressor._cctx, source_size) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "error setting source size: %s" % _zstd_error(zresult) + ) + + def __enter__(self): + if self._closed: + raise ValueError("stream is closed") + + if self._entered: + raise ZstdError("cannot __enter__ multiple times") + + self._entered = True + return self + + def __exit__(self, exc_type, exc_value, exc_tb): + self._entered = False + self.close() + self._compressor = None + + return False + + def __iter__(self): + raise io.UnsupportedOperation() + + def __next__(self): + raise io.UnsupportedOperation() + + def memory_size(self): + return lib.ZSTD_sizeof_CCtx(self._compressor._cctx) + + def fileno(self): + f = getattr(self._writer, "fileno", None) + if f: + return f() + else: + raise OSError("fileno not available on underlying writer") + + def close(self): + if self._closed: + return + + try: + self._closing = True + self.flush(FLUSH_FRAME) + finally: + self._closing = False + self._closed = True + + # Call close() on underlying stream as well. + f = getattr(self._writer, "close", None) + if self._closefd and f: + f() + + @property + def closed(self): + return self._closed + + def isatty(self): + return False + + def readable(self): + return False + + def readline(self, size=-1): + raise io.UnsupportedOperation() + + def readlines(self, hint=-1): + raise io.UnsupportedOperation() + + def seek(self, offset, whence=None): + raise io.UnsupportedOperation() + + def seekable(self): + return False + + def truncate(self, size=None): + raise io.UnsupportedOperation() + + def writable(self): + return True + + def writelines(self, lines): + raise NotImplementedError("writelines() is not yet implemented") + + def read(self, size=-1): + raise io.UnsupportedOperation() + + def readall(self): + raise io.UnsupportedOperation() + + def readinto(self, b): + raise io.UnsupportedOperation() + + def write(self, data): + """Send data to the compressor and possibly to the inner stream.""" + if self._closed: + raise ValueError("stream is closed") + + total_write = 0 + + data_buffer = ffi.from_buffer(data) + + in_buffer = ffi.new("ZSTD_inBuffer *") + in_buffer.src = data_buffer + in_buffer.size = len(data_buffer) + in_buffer.pos = 0 + + out_buffer = self._out_buffer + out_buffer.pos = 0 + + while in_buffer.pos < in_buffer.size: + zresult = lib.ZSTD_compressStream2( + self._compressor._cctx, + out_buffer, + in_buffer, + lib.ZSTD_e_continue, + ) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "zstd compress error: %s" % _zstd_error(zresult) + ) + + if out_buffer.pos: + self._writer.write( + ffi.buffer(out_buffer.dst, out_buffer.pos)[:] + ) + total_write += out_buffer.pos + self._bytes_compressed += out_buffer.pos + out_buffer.pos = 0 + + if self._write_return_read: + return in_buffer.pos + else: + return total_write + + def flush(self, flush_mode=FLUSH_BLOCK): + """Evict data from compressor's internal state and write it to inner stream. + + Calling this method may result in 0 or more ``write()`` calls to the + inner stream. + + This method will also call ``flush()`` on the inner stream, if such a + method exists. + + :param flush_mode: + How to flush the zstd compressor. + + ``zstandard.FLUSH_BLOCK`` will flush data already sent to the + compressor but not emitted to the inner stream. The stream is still + writable after calling this. This is the default behavior. + + See documentation for other ``zstandard.FLUSH_*`` constants for more + flushing options. + :return: + Integer number of bytes written to the inner stream. + """ + + if flush_mode == FLUSH_BLOCK: + flush = lib.ZSTD_e_flush + elif flush_mode == FLUSH_FRAME: + flush = lib.ZSTD_e_end + else: + raise ValueError("unknown flush_mode: %r" % flush_mode) + + if self._closed: + raise ValueError("stream is closed") + + total_write = 0 + + out_buffer = self._out_buffer + out_buffer.pos = 0 + + in_buffer = ffi.new("ZSTD_inBuffer *") + in_buffer.src = ffi.NULL + in_buffer.size = 0 + in_buffer.pos = 0 + + while True: + zresult = lib.ZSTD_compressStream2( + self._compressor._cctx, out_buffer, in_buffer, flush + ) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "zstd compress error: %s" % _zstd_error(zresult) + ) + + if out_buffer.pos: + self._writer.write( + ffi.buffer(out_buffer.dst, out_buffer.pos)[:] + ) + total_write += out_buffer.pos + self._bytes_compressed += out_buffer.pos + out_buffer.pos = 0 + + if not zresult: + break + + f = getattr(self._writer, "flush", None) + if f and not self._closing: + f() + + return total_write + + def tell(self): + return self._bytes_compressed + + +class ZstdCompressionObj(object): + """A compressor conforming to the API in Python's standard library. + + This type implements an API similar to compression types in Python's + standard library such as ``zlib.compressobj`` and ``bz2.BZ2Compressor``. + This enables existing code targeting the standard library API to swap + in this type to achieve zstd compression. + + .. important:: + + The design of this API is not ideal for optimal performance. + + The reason performance is not optimal is because the API is limited to + returning a single buffer holding compressed data. When compressing + data, we don't know how much data will be emitted. So in order to + capture all this data in a single buffer, we need to perform buffer + reallocations and/or extra memory copies. This can add significant + overhead depending on the size or nature of the compressed data how + much your application calls this type. + + If performance is critical, consider an API like + :py:meth:`ZstdCompressor.stream_reader`, + :py:meth:`ZstdCompressor.stream_writer`, + :py:meth:`ZstdCompressor.chunker`, or + :py:meth:`ZstdCompressor.read_to_iter`, which result in less overhead + managing buffers. + + Instances are obtained by calling :py:meth:`ZstdCompressor.compressobj`. + + Here is how this API should be used: + + >>> cctx = zstandard.ZstdCompressor() + >>> cobj = cctx.compressobj() + >>> data = cobj.compress(b"raw input 0") + >>> data = cobj.compress(b"raw input 1") + >>> data = cobj.flush() + + Or to flush blocks: + + >>> cctx.zstandard.ZstdCompressor() + >>> cobj = cctx.compressobj() + >>> data = cobj.compress(b"chunk in first block") + >>> data = cobj.flush(zstandard.COMPRESSOBJ_FLUSH_BLOCK) + >>> data = cobj.compress(b"chunk in second block") + >>> data = cobj.flush() + + For best performance results, keep input chunks under 256KB. This avoids + extra allocations for a large output object. + + It is possible to declare the input size of the data that will be fed + into the compressor: + + >>> cctx = zstandard.ZstdCompressor() + >>> cobj = cctx.compressobj(size=6) + >>> data = cobj.compress(b"foobar") + >>> data = cobj.flush() + """ + + def __init__( + self, compressor, write_size=COMPRESSION_RECOMMENDED_OUTPUT_SIZE + ): + self._compressor = compressor + self._out = ffi.new("ZSTD_outBuffer *") + self._dst_buffer = ffi.new("char[]", write_size) + self._out.dst = self._dst_buffer + self._out.size = write_size + self._out.pos = 0 + self._finished = False + + def compress(self, data): + """Send data to the compressor. + + This method receives bytes to feed to the compressor and returns + bytes constituting zstd compressed data. + + The zstd compressor accumulates bytes and the returned bytes may be + substantially smaller or larger than the size of the input data on + any given call. The returned value may be the empty byte string + (``b""``). + + :param data: + Data to write to the compressor. + :return: + Compressed data. + """ + if self._finished: + raise ZstdError("cannot call compress() after compressor finished") + + data_buffer = ffi.from_buffer(data) + source = ffi.new("ZSTD_inBuffer *") + source.src = data_buffer + source.size = len(data_buffer) + source.pos = 0 + + chunks = [] + + while source.pos < len(data): + zresult = lib.ZSTD_compressStream2( + self._compressor._cctx, self._out, source, lib.ZSTD_e_continue + ) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "zstd compress error: %s" % _zstd_error(zresult) + ) + + if self._out.pos: + chunks.append(ffi.buffer(self._out.dst, self._out.pos)[:]) + self._out.pos = 0 + + return b"".join(chunks) + + def flush(self, flush_mode=COMPRESSOBJ_FLUSH_FINISH): + """Emit data accumulated in the compressor that hasn't been outputted yet. + + The ``flush_mode`` argument controls how to end the stream. + + ``zstandard.COMPRESSOBJ_FLUSH_FINISH`` (the default) ends the + compression stream and finishes a zstd frame. Once this type of flush + is performed, ``compress()`` and ``flush()`` can no longer be called. + This type of flush **must** be called to end the compression context. If + not called, the emitted data may be incomplete and may not be readable + by a decompressor. + + ``zstandard.COMPRESSOBJ_FLUSH_BLOCK`` will flush a zstd block. This + ensures that all data fed to this instance will have been omitted and + can be decoded by a decompressor. Flushes of this type can be performed + multiple times. The next call to ``compress()`` will begin a new zstd + block. + + :param flush_mode: + How to flush the zstd compressor. + :return: + Compressed data. + """ + if flush_mode not in ( + COMPRESSOBJ_FLUSH_FINISH, + COMPRESSOBJ_FLUSH_BLOCK, + ): + raise ValueError("flush mode not recognized") + + if self._finished: + raise ZstdError("compressor object already finished") + + if flush_mode == COMPRESSOBJ_FLUSH_BLOCK: + z_flush_mode = lib.ZSTD_e_flush + elif flush_mode == COMPRESSOBJ_FLUSH_FINISH: + z_flush_mode = lib.ZSTD_e_end + self._finished = True + else: + raise ZstdError("unhandled flush mode") + + assert self._out.pos == 0 + + in_buffer = ffi.new("ZSTD_inBuffer *") + in_buffer.src = ffi.NULL + in_buffer.size = 0 + in_buffer.pos = 0 + + chunks = [] + + while True: + zresult = lib.ZSTD_compressStream2( + self._compressor._cctx, self._out, in_buffer, z_flush_mode + ) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "error ending compression stream: %s" % _zstd_error(zresult) + ) + + if self._out.pos: + chunks.append(ffi.buffer(self._out.dst, self._out.pos)[:]) + self._out.pos = 0 + + if not zresult: + break + + return b"".join(chunks) + + +class ZstdCompressionChunker(object): + """Compress data to uniformly sized chunks. + + This type allows you to iteratively feed chunks of data into a compressor + and produce output chunks of uniform size. + + ``compress()``, ``flush()``, and ``finish()`` all return an iterator of + ``bytes`` instances holding compressed data. The iterator may be empty. + Callers MUST iterate through all elements of the returned iterator before + performing another operation on the object or else the compressor's + internal state may become confused. This can result in an exception being + raised or malformed data being emitted. + + All chunks emitted by ``compress()`` will have a length of the configured + chunk size. + + ``flush()`` and ``finish()`` may return a final chunk smaller than + the configured chunk size. + + Instances are obtained by calling :py:meth:`ZstdCompressor.chunker`. + + Here is how the API should be used: + + >>> cctx = zstandard.ZstdCompressor() + >>> chunker = cctx.chunker(chunk_size=32768) + >>> + >>> with open(path, 'rb') as fh: + ... while True: + ... in_chunk = fh.read(32768) + ... if not in_chunk: + ... break + ... + ... for out_chunk in chunker.compress(in_chunk): + ... # Do something with output chunk of size 32768. + ... + ... for out_chunk in chunker.finish(): + ... # Do something with output chunks that finalize the zstd frame. + + This compressor type is often a better alternative to + :py:class:`ZstdCompressor.compressobj` because it has better performance + properties. + + ``compressobj()`` will emit output data as it is available. This results + in a *stream* of output chunks of varying sizes. The consistency of the + output chunk size with ``chunker()`` is more appropriate for many usages, + such as sending compressed data to a socket. + + ``compressobj()`` may also perform extra memory reallocations in order + to dynamically adjust the sizes of the output chunks. Since ``chunker()`` + output chunks are all the same size (except for flushed or final chunks), + there is less memory allocation/copying overhead. + """ + + def __init__(self, compressor, chunk_size): + self._compressor = compressor + self._out = ffi.new("ZSTD_outBuffer *") + self._dst_buffer = ffi.new("char[]", chunk_size) + self._out.dst = self._dst_buffer + self._out.size = chunk_size + self._out.pos = 0 + + self._in = ffi.new("ZSTD_inBuffer *") + self._in.src = ffi.NULL + self._in.size = 0 + self._in.pos = 0 + self._finished = False + + def compress(self, data): + """Feed new input data into the compressor. + + :param data: + Data to feed to compressor. + :return: + Iterator of ``bytes`` representing chunks of compressed data. + """ + if self._finished: + raise ZstdError("cannot call compress() after compression finished") + + if self._in.src != ffi.NULL: + raise ZstdError( + "cannot perform operation before consuming output " + "from previous operation" + ) + + data_buffer = ffi.from_buffer(data) + + if not len(data_buffer): + return + + self._in.src = data_buffer + self._in.size = len(data_buffer) + self._in.pos = 0 + + while self._in.pos < self._in.size: + zresult = lib.ZSTD_compressStream2( + self._compressor._cctx, self._out, self._in, lib.ZSTD_e_continue + ) + + if self._in.pos == self._in.size: + self._in.src = ffi.NULL + self._in.size = 0 + self._in.pos = 0 + + if lib.ZSTD_isError(zresult): + raise ZstdError( + "zstd compress error: %s" % _zstd_error(zresult) + ) + + if self._out.pos == self._out.size: + yield ffi.buffer(self._out.dst, self._out.pos)[:] + self._out.pos = 0 + + def flush(self): + """Flushes all data currently in the compressor. + + :return: + Iterator of ``bytes`` of compressed data. + """ + if self._finished: + raise ZstdError("cannot call flush() after compression finished") + + if self._in.src != ffi.NULL: + raise ZstdError( + "cannot call flush() before consuming output from " + "previous operation" + ) + + while True: + zresult = lib.ZSTD_compressStream2( + self._compressor._cctx, self._out, self._in, lib.ZSTD_e_flush + ) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "zstd compress error: %s" % _zstd_error(zresult) + ) + + if self._out.pos: + yield ffi.buffer(self._out.dst, self._out.pos)[:] + self._out.pos = 0 + + if not zresult: + return + + def finish(self): + """Signals the end of input data. + + No new data can be compressed after this method is called. + + This method will flush buffered data and finish the zstd frame. + + :return: + Iterator of ``bytes`` of compressed data. + """ + if self._finished: + raise ZstdError("cannot call finish() after compression finished") + + if self._in.src != ffi.NULL: + raise ZstdError( + "cannot call finish() before consuming output from " + "previous operation" + ) + + while True: + zresult = lib.ZSTD_compressStream2( + self._compressor._cctx, self._out, self._in, lib.ZSTD_e_end + ) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "zstd compress error: %s" % _zstd_error(zresult) + ) + + if self._out.pos: + yield ffi.buffer(self._out.dst, self._out.pos)[:] + self._out.pos = 0 + + if not zresult: + self._finished = True + return + + +class ZstdCompressionReader(object): + """Readable compressing stream wrapper. + + ``ZstdCompressionReader`` is a read-only stream interface for obtaining + compressed data from a source. + + This type conforms to the ``io.RawIOBase`` interface and should be usable + by any type that operates against a *file-object* (``typing.BinaryIO`` + in Python type hinting speak). + + Instances are neither writable nor seekable (even if the underlying + source is seekable). ``readline()`` and ``readlines()`` are not implemented + because they don't make sense for compressed data. ``tell()`` returns the + number of compressed bytes emitted so far. + + Instances are obtained by calling :py:meth:`ZstdCompressor.stream_reader`. + + In this example, we open a file for reading and then wrap that file + handle with a stream from which compressed data can be ``read()``. + + >>> with open(path, 'rb') as fh: + ... cctx = zstandard.ZstdCompressor() + ... reader = cctx.stream_reader(fh) + ... while True: + ... chunk = reader.read(16384) + ... if not chunk: + ... break + ... + ... # Do something with compressed chunk. + + Instances can also be used as context managers: + + >>> with open(path, 'rb') as fh: + ... cctx = zstandard.ZstdCompressor() + ... with cctx.stream_reader(fh) as reader: + ... while True: + ... chunk = reader.read(16384) + ... if not chunk: + ... break + ... + ... # Do something with compressed chunk. + + When the context manager exits or ``close()`` is called, the stream is + closed, underlying resources are released, and future operations against + the compression stream will fail. + + ``stream_reader()`` accepts a ``size`` argument specifying how large the + input stream is. This is used to adjust compression parameters so they are + tailored to the source size. e.g. + + >>> with open(path, 'rb') as fh: + ... cctx = zstandard.ZstdCompressor() + ... with cctx.stream_reader(fh, size=os.stat(path).st_size) as reader: + ... ... + + If the ``source`` is a stream, you can specify how large ``read()`` + requests to that stream should be via the ``read_size`` argument. + It defaults to ``zstandard.COMPRESSION_RECOMMENDED_INPUT_SIZE``. e.g. + + >>> with open(path, 'rb') as fh: + ... cctx = zstandard.ZstdCompressor() + ... # Will perform fh.read(8192) when obtaining data to feed into the + ... # compressor. + ... with cctx.stream_reader(fh, read_size=8192) as reader: + ... ... + """ + + def __init__(self, compressor, source, read_size, closefd=True): + self._compressor = compressor + self._source = source + self._read_size = read_size + self._closefd = closefd + self._entered = False + self._closed = False + self._bytes_compressed = 0 + self._finished_input = False + self._finished_output = False + + self._in_buffer = ffi.new("ZSTD_inBuffer *") + # Holds a ref so backing bytes in self._in_buffer stay alive. + self._source_buffer = None + + def __enter__(self): + if self._entered: + raise ValueError("cannot __enter__ multiple times") + + if self._closed: + raise ValueError("stream is closed") + + self._entered = True + return self + + def __exit__(self, exc_type, exc_value, exc_tb): + self._entered = False + self._compressor = None + self.close() + self._source = None + + return False + + def readable(self): + return True + + def writable(self): + return False + + def seekable(self): + return False + + def readline(self): + raise io.UnsupportedOperation() + + def readlines(self): + raise io.UnsupportedOperation() + + def write(self, data): + raise OSError("stream is not writable") + + def writelines(self, ignored): + raise OSError("stream is not writable") + + def isatty(self): + return False + + def flush(self): + return None + + def close(self): + if self._closed: + return + + self._closed = True + + f = getattr(self._source, "close", None) + if self._closefd and f: + f() + + @property + def closed(self): + return self._closed + + def tell(self): + return self._bytes_compressed + + def readall(self): + chunks = [] + + while True: + chunk = self.read(1048576) + if not chunk: + break + + chunks.append(chunk) + + return b"".join(chunks) + + def __iter__(self): + raise io.UnsupportedOperation() + + def __next__(self): + raise io.UnsupportedOperation() + + next = __next__ + + def _read_input(self): + if self._finished_input: + return + + if hasattr(self._source, "read"): + data = self._source.read(self._read_size) + + if not data: + self._finished_input = True + return + + self._source_buffer = ffi.from_buffer(data) + self._in_buffer.src = self._source_buffer + self._in_buffer.size = len(self._source_buffer) + self._in_buffer.pos = 0 + else: + self._source_buffer = ffi.from_buffer(self._source) + self._in_buffer.src = self._source_buffer + self._in_buffer.size = len(self._source_buffer) + self._in_buffer.pos = 0 + + def _compress_into_buffer(self, out_buffer): + if self._in_buffer.pos >= self._in_buffer.size: + return + + old_pos = out_buffer.pos + + zresult = lib.ZSTD_compressStream2( + self._compressor._cctx, + out_buffer, + self._in_buffer, + lib.ZSTD_e_continue, + ) + + self._bytes_compressed += out_buffer.pos - old_pos + + if self._in_buffer.pos == self._in_buffer.size: + self._in_buffer.src = ffi.NULL + self._in_buffer.pos = 0 + self._in_buffer.size = 0 + self._source_buffer = None + + if not hasattr(self._source, "read"): + self._finished_input = True + + if lib.ZSTD_isError(zresult): + raise ZstdError("zstd compress error: %s", _zstd_error(zresult)) + + return out_buffer.pos and out_buffer.pos == out_buffer.size + + def read(self, size=-1): + if self._closed: + raise ValueError("stream is closed") + + if size < -1: + raise ValueError("cannot read negative amounts less than -1") + + if size == -1: + return self.readall() + + if self._finished_output or size == 0: + return b"" + + # Need a dedicated ref to dest buffer otherwise it gets collected. + dst_buffer = ffi.new("char[]", size) + out_buffer = ffi.new("ZSTD_outBuffer *") + out_buffer.dst = dst_buffer + out_buffer.size = size + out_buffer.pos = 0 + + if self._compress_into_buffer(out_buffer): + return ffi.buffer(out_buffer.dst, out_buffer.pos)[:] + + while not self._finished_input: + self._read_input() + + if self._compress_into_buffer(out_buffer): + return ffi.buffer(out_buffer.dst, out_buffer.pos)[:] + + # EOF + old_pos = out_buffer.pos + + zresult = lib.ZSTD_compressStream2( + self._compressor._cctx, out_buffer, self._in_buffer, lib.ZSTD_e_end + ) + + self._bytes_compressed += out_buffer.pos - old_pos + + if lib.ZSTD_isError(zresult): + raise ZstdError( + "error ending compression stream: %s", _zstd_error(zresult) + ) + + if zresult == 0: + self._finished_output = True + + return ffi.buffer(out_buffer.dst, out_buffer.pos)[:] + + def read1(self, size=-1): + if self._closed: + raise ValueError("stream is closed") + + if size < -1: + raise ValueError("cannot read negative amounts less than -1") + + if self._finished_output or size == 0: + return b"" + + # -1 returns arbitrary number of bytes. + if size == -1: + size = COMPRESSION_RECOMMENDED_OUTPUT_SIZE + + dst_buffer = ffi.new("char[]", size) + out_buffer = ffi.new("ZSTD_outBuffer *") + out_buffer.dst = dst_buffer + out_buffer.size = size + out_buffer.pos = 0 + + # read1() dictates that we can perform at most 1 call to the + # underlying stream to get input. However, we can't satisfy this + # restriction with compression because not all input generates output. + # It is possible to perform a block flush in order to ensure output. + # But this may not be desirable behavior. So we allow multiple read() + # to the underlying stream. But unlike read(), we stop once we have + # any output. + + self._compress_into_buffer(out_buffer) + if out_buffer.pos: + return ffi.buffer(out_buffer.dst, out_buffer.pos)[:] + + while not self._finished_input: + self._read_input() + + # If we've filled the output buffer, return immediately. + if self._compress_into_buffer(out_buffer): + return ffi.buffer(out_buffer.dst, out_buffer.pos)[:] + + # If we've populated the output buffer and we're not at EOF, + # also return, as we've satisfied the read1() limits. + if out_buffer.pos and not self._finished_input: + return ffi.buffer(out_buffer.dst, out_buffer.pos)[:] + + # Else if we're at EOS and we have room left in the buffer, + # fall through to below and try to add more data to the output. + + # EOF. + old_pos = out_buffer.pos + + zresult = lib.ZSTD_compressStream2( + self._compressor._cctx, out_buffer, self._in_buffer, lib.ZSTD_e_end + ) + + self._bytes_compressed += out_buffer.pos - old_pos + + if lib.ZSTD_isError(zresult): + raise ZstdError( + "error ending compression stream: %s" % _zstd_error(zresult) + ) + + if zresult == 0: + self._finished_output = True + + return ffi.buffer(out_buffer.dst, out_buffer.pos)[:] + + def readinto(self, b): + if self._closed: + raise ValueError("stream is closed") + + if self._finished_output: + return 0 + + # TODO use writable=True once we require CFFI >= 1.12. + dest_buffer = ffi.from_buffer(b) + ffi.memmove(b, b"", 0) + out_buffer = ffi.new("ZSTD_outBuffer *") + out_buffer.dst = dest_buffer + out_buffer.size = len(dest_buffer) + out_buffer.pos = 0 + + if self._compress_into_buffer(out_buffer): + return out_buffer.pos + + while not self._finished_input: + self._read_input() + if self._compress_into_buffer(out_buffer): + return out_buffer.pos + + # EOF. + old_pos = out_buffer.pos + zresult = lib.ZSTD_compressStream2( + self._compressor._cctx, out_buffer, self._in_buffer, lib.ZSTD_e_end + ) + + self._bytes_compressed += out_buffer.pos - old_pos + + if lib.ZSTD_isError(zresult): + raise ZstdError( + "error ending compression stream: %s", _zstd_error(zresult) + ) + + if zresult == 0: + self._finished_output = True + + return out_buffer.pos + + def readinto1(self, b): + if self._closed: + raise ValueError("stream is closed") + + if self._finished_output: + return 0 + + # TODO use writable=True once we require CFFI >= 1.12. + dest_buffer = ffi.from_buffer(b) + ffi.memmove(b, b"", 0) + + out_buffer = ffi.new("ZSTD_outBuffer *") + out_buffer.dst = dest_buffer + out_buffer.size = len(dest_buffer) + out_buffer.pos = 0 + + self._compress_into_buffer(out_buffer) + if out_buffer.pos: + return out_buffer.pos + + while not self._finished_input: + self._read_input() + + if self._compress_into_buffer(out_buffer): + return out_buffer.pos + + if out_buffer.pos and not self._finished_input: + return out_buffer.pos + + # EOF. + old_pos = out_buffer.pos + + zresult = lib.ZSTD_compressStream2( + self._compressor._cctx, out_buffer, self._in_buffer, lib.ZSTD_e_end + ) + + self._bytes_compressed += out_buffer.pos - old_pos + + if lib.ZSTD_isError(zresult): + raise ZstdError( + "error ending compression stream: %s" % _zstd_error(zresult) + ) + + if zresult == 0: + self._finished_output = True + + return out_buffer.pos + + +class ZstdCompressor(object): + """ + Create an object used to perform Zstandard compression. + + Each instance is essentially a wrapper around a ``ZSTD_CCtx`` from + zstd's C API. + + An instance can compress data various ways. Instances can be used + multiple times. Each compression operation will use the compression + parameters defined at construction time. + + .. note: + + When using a compression dictionary and multiple compression + operations are performed, the ``ZstdCompressionParameters`` derived + from an integer compression ``level`` and the first compressed data's + size will be reused for all subsequent operations. This may not be + desirable if source data sizes vary significantly. + + ``compression_params`` is mutually exclusive with ``level``, + ``write_checksum``, ``write_content_size``, ``write_dict_id``, and + ``threads``. + + Assume that each ``ZstdCompressor`` instance can only handle a single + logical compression operation at the same time. i.e. if you call a method + like ``stream_reader()`` to obtain multiple objects derived from the same + ``ZstdCompressor`` instance and attempt to use them simultaneously, errors + will likely occur. + + If you need to perform multiple logical compression operations and you + can't guarantee those operations are temporally non-overlapping, you need + to obtain multiple ``ZstdCompressor`` instances. + + Unless specified otherwise, assume that no two methods of + ``ZstdCompressor`` instances can be called from multiple Python + threads simultaneously. In other words, assume instances are not thread safe + unless stated otherwise. + + :param level: + Integer compression level. Valid values are all negative integers + through 22. Lower values generally yield faster operations with lower + compression ratios. Higher values are generally slower but compress + better. The default is 3, which is what the ``zstd`` CLI uses. Negative + levels effectively engage ``--fast`` mode from the ``zstd`` CLI. + :param dict_data: + A ``ZstdCompressionDict`` to be used to compress with dictionary + data. + :param compression_params: + A ``ZstdCompressionParameters`` instance defining low-level compression + parameters. If defined, this will overwrite the ``level`` argument. + :param write_checksum: + If True, a 4 byte content checksum will be written with the compressed + data, allowing the decompressor to perform content verification. + :param write_content_size: + If True (the default), the decompressed content size will be included + in the header of the compressed data. This data will only be written if + the compressor knows the size of the input data. + :param write_dict_id: + Determines whether the dictionary ID will be written into the compressed + data. Defaults to True. Only adds content to the compressed data if + a dictionary is being used. + :param threads: + Number of threads to use to compress data concurrently. When set, + compression operations are performed on multiple threads. The default + value (0) disables multi-threaded compression. A value of ``-1`` means + to set the number of threads to the number of detected logical CPUs. + """ + + def __init__( + self, + level=3, + dict_data=None, + compression_params=None, + write_checksum=None, + write_content_size=None, + write_dict_id=None, + threads=0, + ): + if level > lib.ZSTD_maxCLevel(): + raise ValueError( + "level must be less than %d" % lib.ZSTD_maxCLevel() + ) + + if threads < 0: + threads = _cpu_count() + + if compression_params and write_checksum is not None: + raise ValueError( + "cannot define compression_params and write_checksum" + ) + + if compression_params and write_content_size is not None: + raise ValueError( + "cannot define compression_params and write_content_size" + ) + + if compression_params and write_dict_id is not None: + raise ValueError( + "cannot define compression_params and write_dict_id" + ) + + if compression_params and threads: + raise ValueError("cannot define compression_params and threads") + + if compression_params: + self._params = _make_cctx_params(compression_params) + else: + if write_dict_id is None: + write_dict_id = True + + params = lib.ZSTD_createCCtxParams() + if params == ffi.NULL: + raise MemoryError() + + self._params = ffi.gc(params, lib.ZSTD_freeCCtxParams) + + _set_compression_parameter( + self._params, lib.ZSTD_c_compressionLevel, level + ) + + _set_compression_parameter( + self._params, + lib.ZSTD_c_contentSizeFlag, + write_content_size if write_content_size is not None else 1, + ) + + _set_compression_parameter( + self._params, + lib.ZSTD_c_checksumFlag, + 1 if write_checksum else 0, + ) + + _set_compression_parameter( + self._params, lib.ZSTD_c_dictIDFlag, 1 if write_dict_id else 0 + ) + + if threads: + _set_compression_parameter( + self._params, lib.ZSTD_c_nbWorkers, threads + ) + + cctx = lib.ZSTD_createCCtx() + if cctx == ffi.NULL: + raise MemoryError() + + self._cctx = cctx + self._dict_data = dict_data + + # We defer setting up garbage collection until after calling + # _setup_cctx() to ensure the memory size estimate is more accurate. + try: + self._setup_cctx() + finally: + self._cctx = ffi.gc( + cctx, lib.ZSTD_freeCCtx, size=lib.ZSTD_sizeof_CCtx(cctx) + ) + + def _setup_cctx(self): + zresult = lib.ZSTD_CCtx_setParametersUsingCCtxParams( + self._cctx, self._params + ) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "could not set compression parameters: %s" + % _zstd_error(zresult) + ) + + dict_data = self._dict_data + + if dict_data: + if dict_data._cdict: + zresult = lib.ZSTD_CCtx_refCDict(self._cctx, dict_data._cdict) + else: + zresult = lib.ZSTD_CCtx_loadDictionary_advanced( + self._cctx, + dict_data.as_bytes(), + len(dict_data), + lib.ZSTD_dlm_byRef, + dict_data._dict_type, + ) + + if lib.ZSTD_isError(zresult): + raise ZstdError( + "could not load compression dictionary: %s" + % _zstd_error(zresult) + ) + + def memory_size(self): + """Obtain the memory usage of this compressor, in bytes. + + >>> cctx = zstandard.ZstdCompressor() + >>> memory = cctx.memory_size() + """ + return lib.ZSTD_sizeof_CCtx(self._cctx) + + def compress(self, data): + """ + Compress data in a single operation. + + This is the simplest mechanism to perform compression: simply pass in a + value and get a compressed value back. It is almost the most prone to + abuse. + + The input and output values must fit in memory, so passing in very large + values can result in excessive memory usage. For this reason, one of the + streaming based APIs is preferred for larger values. + + :param data: + Source data to compress + :return: + Compressed data + + >>> cctx = zstandard.ZstdCompressor() + >>> compressed = cctx.compress(b"data to compress") + """ + lib.ZSTD_CCtx_reset(self._cctx, lib.ZSTD_reset_session_only) + + data_buffer = ffi.from_buffer(data) + + dest_size = lib.ZSTD_compressBound(len(data_buffer)) + out = new_nonzero("char[]", dest_size) + + zresult = lib.ZSTD_CCtx_setPledgedSrcSize(self._cctx, len(data_buffer)) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "error setting source size: %s" % _zstd_error(zresult) + ) + + out_buffer = ffi.new("ZSTD_outBuffer *") + in_buffer = ffi.new("ZSTD_inBuffer *") + + out_buffer.dst = out + out_buffer.size = dest_size + out_buffer.pos = 0 + + in_buffer.src = data_buffer + in_buffer.size = len(data_buffer) + in_buffer.pos = 0 + + zresult = lib.ZSTD_compressStream2( + self._cctx, out_buffer, in_buffer, lib.ZSTD_e_end + ) + + if lib.ZSTD_isError(zresult): + raise ZstdError("cannot compress: %s" % _zstd_error(zresult)) + elif zresult: + raise ZstdError("unexpected partial frame flush") + + return ffi.buffer(out, out_buffer.pos)[:] + + def compressobj(self, size=-1): + """ + Obtain a compressor exposing the Python standard library compression API. + + See :py:class:`ZstdCompressionObj` for the full documentation. + + :param size: + Size in bytes of data that will be compressed. + :return: + :py:class:`ZstdCompressionObj` + """ + lib.ZSTD_CCtx_reset(self._cctx, lib.ZSTD_reset_session_only) + + if size < 0: + size = lib.ZSTD_CONTENTSIZE_UNKNOWN + + zresult = lib.ZSTD_CCtx_setPledgedSrcSize(self._cctx, size) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "error setting source size: %s" % _zstd_error(zresult) + ) + + cobj = ZstdCompressionObj(self, COMPRESSION_RECOMMENDED_OUTPUT_SIZE) + + return cobj + + def chunker(self, size=-1, chunk_size=COMPRESSION_RECOMMENDED_OUTPUT_SIZE): + """ + Create an object for iterative compressing to same-sized chunks. + + This API is similar to :py:meth:`ZstdCompressor.compressobj` but has + better performance properties. + + :param size: + Size in bytes of data that will be compressed. + :param chunk_size: + Size of compressed chunks. + :return: + :py:class:`ZstdCompressionChunker` + """ + lib.ZSTD_CCtx_reset(self._cctx, lib.ZSTD_reset_session_only) + + if size < 0: + size = lib.ZSTD_CONTENTSIZE_UNKNOWN + + zresult = lib.ZSTD_CCtx_setPledgedSrcSize(self._cctx, size) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "error setting source size: %s" % _zstd_error(zresult) + ) + + return ZstdCompressionChunker(self, chunk_size=chunk_size) + + def copy_stream( + self, + ifh, + ofh, + size=-1, + read_size=COMPRESSION_RECOMMENDED_INPUT_SIZE, + write_size=COMPRESSION_RECOMMENDED_OUTPUT_SIZE, + ): + """ + Copy data between 2 streams while compressing it. + + Data will be read from ``ifh``, compressed, and written to ``ofh``. + ``ifh`` must have a ``read(size)`` method. ``ofh`` must have a + ``write(data)`` + method. + + >>> cctx = zstandard.ZstdCompressor() + >>> with open(input_path, "rb") as ifh, open(output_path, "wb") as ofh: + ... cctx.copy_stream(ifh, ofh) + + It is also possible to declare the size of the source stream: + + >>> cctx = zstandard.ZstdCompressor() + >>> cctx.copy_stream(ifh, ofh, size=len_of_input) + + You can also specify how large the chunks that are ``read()`` + and ``write()`` from and to the streams: + + >>> cctx = zstandard.ZstdCompressor() + >>> cctx.copy_stream(ifh, ofh, read_size=32768, write_size=16384) + + The stream copier returns a 2-tuple of bytes read and written: + + >>> cctx = zstandard.ZstdCompressor() + >>> read_count, write_count = cctx.copy_stream(ifh, ofh) + + :param ifh: + Source stream to read from + :param ofh: + Destination stream to write to + :param size: + Size in bytes of the source stream. If defined, compression + parameters will be tuned for this size. + :param read_size: + Chunk sizes that source stream should be ``read()`` from. + :param write_size: + Chunk sizes that destination stream should be ``write()`` to. + :return: + 2-tuple of ints of bytes read and written, respectively. + """ + + if not hasattr(ifh, "read"): + raise ValueError("first argument must have a read() method") + if not hasattr(ofh, "write"): + raise ValueError("second argument must have a write() method") + + lib.ZSTD_CCtx_reset(self._cctx, lib.ZSTD_reset_session_only) + + if size < 0: + size = lib.ZSTD_CONTENTSIZE_UNKNOWN + + zresult = lib.ZSTD_CCtx_setPledgedSrcSize(self._cctx, size) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "error setting source size: %s" % _zstd_error(zresult) + ) + + in_buffer = ffi.new("ZSTD_inBuffer *") + out_buffer = ffi.new("ZSTD_outBuffer *") + + dst_buffer = ffi.new("char[]", write_size) + out_buffer.dst = dst_buffer + out_buffer.size = write_size + out_buffer.pos = 0 + + total_read, total_write = 0, 0 + + while True: + data = ifh.read(read_size) + if not data: + break + + data_buffer = ffi.from_buffer(data) + total_read += len(data_buffer) + in_buffer.src = data_buffer + in_buffer.size = len(data_buffer) + in_buffer.pos = 0 + + while in_buffer.pos < in_buffer.size: + zresult = lib.ZSTD_compressStream2( + self._cctx, out_buffer, in_buffer, lib.ZSTD_e_continue + ) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "zstd compress error: %s" % _zstd_error(zresult) + ) + + if out_buffer.pos: + ofh.write(ffi.buffer(out_buffer.dst, out_buffer.pos)) + total_write += out_buffer.pos + out_buffer.pos = 0 + + # We've finished reading. Flush the compressor. + while True: + zresult = lib.ZSTD_compressStream2( + self._cctx, out_buffer, in_buffer, lib.ZSTD_e_end + ) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "error ending compression stream: %s" % _zstd_error(zresult) + ) + + if out_buffer.pos: + ofh.write(ffi.buffer(out_buffer.dst, out_buffer.pos)) + total_write += out_buffer.pos + out_buffer.pos = 0 + + if zresult == 0: + break + + return total_read, total_write + + def stream_reader( + self, + source, + size=-1, + read_size=COMPRESSION_RECOMMENDED_INPUT_SIZE, + closefd=True, + ): + """ + Wrap a readable source with a stream that can read compressed data. + + This will produce an object conforming to the ``io.RawIOBase`` + interface which can be ``read()`` from to retrieve compressed data + from a source. + + The source object can be any object with a ``read(size)`` method + or an object that conforms to the buffer protocol. + + See :py:class:`ZstdCompressionReader` for type documentation and usage + examples. + + :param source: + Object to read source data from + :param size: + Size in bytes of source object. + :param read_size: + How many bytes to request when ``read()``'ing from the source. + :param closefd: + Whether to close the source stream when the returned stream is + closed. + :return: + :py:class:`ZstdCompressionReader` + """ + lib.ZSTD_CCtx_reset(self._cctx, lib.ZSTD_reset_session_only) + + try: + size = len(source) + except Exception: + pass + + if size < 0: + size = lib.ZSTD_CONTENTSIZE_UNKNOWN + + zresult = lib.ZSTD_CCtx_setPledgedSrcSize(self._cctx, size) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "error setting source size: %s" % _zstd_error(zresult) + ) + + return ZstdCompressionReader(self, source, read_size, closefd=closefd) + + def stream_writer( + self, + writer, + size=-1, + write_size=COMPRESSION_RECOMMENDED_OUTPUT_SIZE, + write_return_read=True, + closefd=True, + ): + """ + Create a stream that will write compressed data into another stream. + + The argument to ``stream_writer()`` must have a ``write(data)`` method. + As compressed data is available, ``write()`` will be called with the + compressed data as its argument. Many common Python types implement + ``write()``, including open file handles and ``io.BytesIO``. + + See :py:class:`ZstdCompressionWriter` for more documentation, including + usage examples. + + :param writer: + Stream to write compressed data to. + :param size: + Size in bytes of data to be compressed. If set, it will be used + to influence compression parameter tuning and could result in the + size being written into the header of the compressed data. + :param write_size: + How much data to ``write()`` to ``writer`` at a time. + :param write_return_read: + Whether ``write()`` should return the number of bytes that were + consumed from the input. + :param closefd: + Whether to ``close`` the ``writer`` when this stream is closed. + :return: + :py:class:`ZstdCompressionWriter` + """ + if not hasattr(writer, "write"): + raise ValueError("must pass an object with a write() method") + + lib.ZSTD_CCtx_reset(self._cctx, lib.ZSTD_reset_session_only) + + if size < 0: + size = lib.ZSTD_CONTENTSIZE_UNKNOWN + + return ZstdCompressionWriter( + self, writer, size, write_size, write_return_read, closefd=closefd + ) + + def read_to_iter( + self, + reader, + size=-1, + read_size=COMPRESSION_RECOMMENDED_INPUT_SIZE, + write_size=COMPRESSION_RECOMMENDED_OUTPUT_SIZE, + ): + """ + Read uncompressed data from a reader and return an iterator + + Returns an iterator of compressed data produced from reading from + ``reader``. + + This method provides a mechanism to stream compressed data out of a + source as an iterator of data chunks. + + Uncompressed data will be obtained from ``reader`` by calling the + ``read(size)`` method of it or by reading a slice (if ``reader`` + conforms to the *buffer protocol*). The source data will be streamed + into a compressor. As compressed data is available, it will be exposed + to the iterator. + + Data is read from the source in chunks of ``read_size``. Compressed + chunks are at most ``write_size`` bytes. Both values default to the + zstd input and and output defaults, respectively. + + If reading from the source via ``read()``, ``read()`` will be called + until it raises or returns an empty bytes (``b""``). It is perfectly + valid for the source to deliver fewer bytes than were what requested + by ``read(size)``. + + The caller is partially in control of how fast data is fed into the + compressor by how it consumes the returned iterator. The compressor + will not consume from the reader unless the caller consumes from the + iterator. + + >>> cctx = zstandard.ZstdCompressor() + >>> for chunk in cctx.read_to_iter(fh): + ... # Do something with emitted data. + + ``read_to_iter()`` accepts a ``size`` argument declaring the size of + the input stream: + + >>> cctx = zstandard.ZstdCompressor() + >>> for chunk in cctx.read_to_iter(fh, size=some_int): + >>> pass + + You can also control the size that data is ``read()`` from the source + and the ideal size of output chunks: + + >>> cctx = zstandard.ZstdCompressor() + >>> for chunk in cctx.read_to_iter(fh, read_size=16384, write_size=8192): + >>> pass + + ``read_to_iter()`` does not give direct control over the sizes of chunks + fed into the compressor. Instead, chunk sizes will be whatever the object + being read from delivers. These will often be of a uniform size. + + :param reader: + Stream providing data to be compressed. + :param size: + Size in bytes of input data. + :param read_size: + Controls how many bytes are ``read()`` from the source. + :param write_size: + Controls the output size of emitted chunks. + :return: + Iterator of ``bytes``. + """ + + if hasattr(reader, "read"): + have_read = True + elif hasattr(reader, "__getitem__"): + have_read = False + buffer_offset = 0 + size = len(reader) + else: + raise ValueError( + "must pass an object with a read() method or " + "conforms to buffer protocol" + ) + + lib.ZSTD_CCtx_reset(self._cctx, lib.ZSTD_reset_session_only) + + if size < 0: + size = lib.ZSTD_CONTENTSIZE_UNKNOWN + + zresult = lib.ZSTD_CCtx_setPledgedSrcSize(self._cctx, size) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "error setting source size: %s" % _zstd_error(zresult) + ) + + in_buffer = ffi.new("ZSTD_inBuffer *") + out_buffer = ffi.new("ZSTD_outBuffer *") + + in_buffer.src = ffi.NULL + in_buffer.size = 0 + in_buffer.pos = 0 + + dst_buffer = ffi.new("char[]", write_size) + out_buffer.dst = dst_buffer + out_buffer.size = write_size + out_buffer.pos = 0 + + while True: + # We should never have output data sitting around after a previous + # iteration. + assert out_buffer.pos == 0 + + # Collect input data. + if have_read: + read_result = reader.read(read_size) + else: + remaining = len(reader) - buffer_offset + slice_size = min(remaining, read_size) + read_result = reader[buffer_offset : buffer_offset + slice_size] + buffer_offset += slice_size + + # No new input data. Break out of the read loop. + if not read_result: + break + + # Feed all read data into the compressor and emit output until + # exhausted. + read_buffer = ffi.from_buffer(read_result) + in_buffer.src = read_buffer + in_buffer.size = len(read_buffer) + in_buffer.pos = 0 + + while in_buffer.pos < in_buffer.size: + zresult = lib.ZSTD_compressStream2( + self._cctx, out_buffer, in_buffer, lib.ZSTD_e_continue + ) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "zstd compress error: %s" % _zstd_error(zresult) + ) + + if out_buffer.pos: + data = ffi.buffer(out_buffer.dst, out_buffer.pos)[:] + out_buffer.pos = 0 + yield data + + assert out_buffer.pos == 0 + + # And repeat the loop to collect more data. + continue + + # If we get here, input is exhausted. End the stream and emit what + # remains. + while True: + assert out_buffer.pos == 0 + zresult = lib.ZSTD_compressStream2( + self._cctx, out_buffer, in_buffer, lib.ZSTD_e_end + ) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "error ending compression stream: %s" % _zstd_error(zresult) + ) + + if out_buffer.pos: + data = ffi.buffer(out_buffer.dst, out_buffer.pos)[:] + out_buffer.pos = 0 + yield data + + if zresult == 0: + break + + def multi_compress_to_buffer(self, data, threads=-1): + """ + Compress multiple pieces of data as a single function call. + + (Experimental. Not yet supported by CFFI backend.) + + This function is optimized to perform multiple compression operations + as as possible with as little overhead as possible. + + Data to be compressed can be passed as a ``BufferWithSegmentsCollection``, + a ``BufferWithSegments``, or a list containing byte like objects. Each + element of the container will be compressed individually using the + configured parameters on the ``ZstdCompressor`` instance. + + The ``threads`` argument controls how many threads to use for + compression. The default is ``0`` which means to use a single thread. + Negative values use the number of logical CPUs in the machine. + + The function returns a ``BufferWithSegmentsCollection``. This type + represents N discrete memory allocations, each holding 1 or more + compressed frames. + + Output data is written to shared memory buffers. This means that unlike + regular Python objects, a reference to *any* object within the collection + keeps the shared buffer and therefore memory backing it alive. This can + have undesirable effects on process memory usage. + + The API and behavior of this function is experimental and will likely + change. Known deficiencies include: + + * If asked to use multiple threads, it will always spawn that many + threads, even if the input is too small to use them. It should + automatically lower the thread count when the extra threads would + just add overhead. + * The buffer allocation strategy is fixed. There is room to make it + dynamic, perhaps even to allow one output buffer per input, + facilitating a variation of the API to return a list without the + adverse effects of shared memory buffers. + + :param data: + Source to read discrete pieces of data to compress. + + Can be a ``BufferWithSegmentsCollection``, a ``BufferWithSegments``, + or a ``list[bytes]``. + :return: + BufferWithSegmentsCollection holding compressed data. + """ + raise NotImplementedError() + + def frame_progression(self): + """ + Return information on how much work the compressor has done. + + Returns a 3-tuple of (ingested, consumed, produced). + + >>> cctx = zstandard.ZstdCompressor() + >>> (ingested, consumed, produced) = cctx.frame_progression() + """ + progression = lib.ZSTD_getFrameProgression(self._cctx) + + return progression.ingested, progression.consumed, progression.produced + + +class FrameParameters(object): + """Information about a zstd frame. + + Instances have the following attributes: + + ``content_size`` + Integer size of original, uncompressed content. This will be ``0`` if the + original content size isn't written to the frame (controlled with the + ``write_content_size`` argument to ``ZstdCompressor``) or if the input + content size was ``0``. + + ``window_size`` + Integer size of maximum back-reference distance in compressed data. + + ``dict_id`` + Integer of dictionary ID used for compression. ``0`` if no dictionary + ID was used or if the dictionary ID was ``0``. + + ``has_checksum`` + Bool indicating whether a 4 byte content checksum is stored at the end + of the frame. + """ + + def __init__(self, fparams): + self.content_size = fparams.frameContentSize + self.window_size = fparams.windowSize + self.dict_id = fparams.dictID + self.has_checksum = bool(fparams.checksumFlag) + + +def frame_content_size(data): + """Obtain the decompressed size of a frame. + + The returned value is usually accurate. But strictly speaking it should + not be trusted. + + :return: + ``-1`` if size unknown and a non-negative integer otherwise. + """ + data_buffer = ffi.from_buffer(data) + + size = lib.ZSTD_getFrameContentSize(data_buffer, len(data_buffer)) + + if size == lib.ZSTD_CONTENTSIZE_ERROR: + raise ZstdError("error when determining content size") + elif size == lib.ZSTD_CONTENTSIZE_UNKNOWN: + return -1 + else: + return size + + +def frame_header_size(data): + """Obtain the size of a frame header. + + :return: + Integer size in bytes. + """ + data_buffer = ffi.from_buffer(data) + + zresult = lib.ZSTD_frameHeaderSize(data_buffer, len(data_buffer)) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "could not determine frame header size: %s" % _zstd_error(zresult) + ) + + return zresult + + +def get_frame_parameters(data, format=FORMAT_ZSTD1): + """ + Parse a zstd frame header into frame parameters. + + Depending on which fields are present in the frame and their values, the + length of the frame parameters varies. If insufficient bytes are passed + in to fully parse the frame parameters, ``ZstdError`` is raised. To ensure + frame parameters can be parsed, pass in at least 18 bytes. + + :param data: + Data from which to read frame parameters. + :param format: + Set the format of data for the decoder. + :return: + :py:class:`FrameParameters` + """ + params = ffi.new("ZSTD_FrameHeader *") + + data_buffer = ffi.from_buffer(data) + zresult = lib.ZSTD_getFrameHeader_advanced( + params, data_buffer, len(data_buffer), format + ) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "cannot get frame parameters: %s" % _zstd_error(zresult) + ) + + if zresult: + raise ZstdError( + "not enough data for frame parameters; need %d bytes" % zresult + ) + + return FrameParameters(params[0]) + + +class ZstdCompressionDict(object): + """Represents a computed compression dictionary. + + Instances are obtained by calling :py:func:`train_dictionary` or by + passing bytes obtained from another source into the constructor. + + Instances can be constructed from bytes: + + >>> dict_data = zstandard.ZstdCompressionDict(data) + + It is possible to construct a dictionary from *any* data. If the data + doesn't begin with a magic header, it will be treated as a *prefix* + dictionary. *Prefix* dictionaries allow compression operations to + reference raw data within the dictionary. + + It is possible to force the use of *prefix* dictionaries or to require + a dictionary header: + + >>> dict_data = zstandard.ZstdCompressionDict(data, dict_type=zstandard.DICT_TYPE_RAWCONTENT) + >>> dict_data = zstandard.ZstdCompressionDict(data, dict_type=zstandard.DICT_TYPE_FULLDICT) + + You can see how many bytes are in the dictionary by calling ``len()``: + + >>> dict_data = zstandard.train_dictionary(size, samples) + >>> dict_size = len(dict_data) # will not be larger than ``size`` + + Once you have a dictionary, you can pass it to the objects performing + compression and decompression: + + >>> dict_data = zstandard.train_dictionary(131072, samples) + >>> cctx = zstandard.ZstdCompressor(dict_data=dict_data) + >>> for source_data in input_data: + ... compressed = cctx.compress(source_data) + ... # Do something with compressed data. + ... + >>> dctx = zstandard.ZstdDecompressor(dict_data=dict_data) + >>> for compressed_data in input_data: + ... buffer = io.BytesIO() + ... with dctx.stream_writer(buffer) as decompressor: + ... decompressor.write(compressed_data) + ... # Do something with raw data in ``buffer``. + + Dictionaries have unique integer IDs. You can retrieve this ID via: + + >>> dict_id = dict_data.dict_id() + + You can obtain the raw data in the dict (useful for persisting and constructing + a ``ZstdCompressionDict`` later) via ``as_bytes()``: + + >>> dict_data = zstandard.train_dictionary(size, samples) + >>> raw_data = dict_data.as_bytes() + + By default, when a ``ZstdCompressionDict`` is *attached* to a + ``ZstdCompressor``, each ``ZstdCompressor`` performs work to prepare the + dictionary for use. This is fine if only 1 compression operation is being + performed or if the ``ZstdCompressor`` is being reused for multiple operations. + But if multiple ``ZstdCompressor`` instances are being used with the dictionary, + this can add overhead. + + It is possible to *precompute* the dictionary so it can readily be consumed + by multiple ``ZstdCompressor`` instances: + + >>> d = zstandard.ZstdCompressionDict(data) + >>> # Precompute for compression level 3. + >>> d.precompute_compress(level=3) + >>> # Precompute with specific compression parameters. + >>> params = zstandard.ZstdCompressionParameters(...) + >>> d.precompute_compress(compression_params=params) + + .. note:: + + When a dictionary is precomputed, the compression parameters used to + precompute the dictionary overwrite some of the compression parameters + specified to ``ZstdCompressor``. + + :param data: + Dictionary data. + :param dict_type: + Type of dictionary. One of the ``DICT_TYPE_*`` constants. + """ + + def __init__(self, data, dict_type=DICT_TYPE_AUTO, k=0, d=0): + assert isinstance(data, bytes) + self._data = data + self.k = k + self.d = d + + if dict_type not in ( + DICT_TYPE_AUTO, + DICT_TYPE_RAWCONTENT, + DICT_TYPE_FULLDICT, + ): + raise ValueError( + "invalid dictionary load mode: %d; must use " + "DICT_TYPE_* constants" + ) + + self._dict_type = dict_type + self._cdict = None + + def __len__(self): + return len(self._data) + + def dict_id(self): + """Obtain the integer ID of the dictionary.""" + return int(lib.ZDICT_getDictID(self._data, len(self._data))) + + def as_bytes(self): + """Obtain the ``bytes`` representation of the dictionary.""" + return self._data + + def precompute_compress(self, level=0, compression_params=None): + """Precompute a dictionary os it can be used by multiple compressors. + + Calling this method on an instance that will be used by multiple + :py:class:`ZstdCompressor` instances will improve performance. + """ + if level and compression_params: + raise ValueError( + "must only specify one of level or compression_params" + ) + + if not level and not compression_params: + raise ValueError("must specify one of level or compression_params") + + if level: + cparams = lib.ZSTD_getCParams(level, 0, len(self._data)) + else: + cparams = ffi.new("ZSTD_compressionParameters") + cparams.chainLog = compression_params.chain_log + cparams.hashLog = compression_params.hash_log + cparams.minMatch = compression_params.min_match + cparams.searchLog = compression_params.search_log + cparams.strategy = compression_params.strategy + cparams.targetLength = compression_params.target_length + cparams.windowLog = compression_params.window_log + + cdict = lib.ZSTD_createCDict_advanced( + self._data, + len(self._data), + lib.ZSTD_dlm_byRef, + self._dict_type, + cparams, + lib.ZSTD_defaultCMem, + ) + if cdict == ffi.NULL: + raise ZstdError("unable to precompute dictionary") + + self._cdict = ffi.gc( + cdict, lib.ZSTD_freeCDict, size=lib.ZSTD_sizeof_CDict(cdict) + ) + + @property + def _ddict(self): + ddict = lib.ZSTD_createDDict_advanced( + self._data, + len(self._data), + lib.ZSTD_dlm_byRef, + self._dict_type, + lib.ZSTD_defaultCMem, + ) + + if ddict == ffi.NULL: + raise ZstdError("could not create decompression dict") + + ddict = ffi.gc( + ddict, lib.ZSTD_freeDDict, size=lib.ZSTD_sizeof_DDict(ddict) + ) + self.__dict__["_ddict"] = ddict + + return ddict + + +def train_dictionary( + dict_size, + samples, + k=0, + d=0, + f=0, + split_point=0.0, + accel=0, + notifications=0, + dict_id=0, + level=0, + steps=0, + threads=0, +): + """Train a dictionary from sample data using the COVER algorithm. + + A compression dictionary of size ``dict_size`` will be created from the + iterable of ``samples``. The raw dictionary bytes will be returned. + + The dictionary training mechanism is known as *cover*. More details about it + are available in the paper *Effective Construction of Relative Lempel-Ziv + Dictionaries* (authors: Liao, Petri, Moffat, Wirth). + + The cover algorithm takes parameters ``k`` and ``d``. These are the + *segment size* and *dmer size*, respectively. The returned dictionary + instance created by this function has ``k`` and ``d`` attributes + containing the values for these parameters. If a ``ZstdCompressionDict`` + is constructed from raw bytes data (a content-only dictionary), the + ``k`` and ``d`` attributes will be ``0``. + + The segment and dmer size parameters to the cover algorithm can either be + specified manually or ``train_dictionary()`` can try multiple values + and pick the best one, where *best* means the smallest compressed data size. + This later mode is called *optimization* mode. + + Under the hood, this function always calls + ``ZDICT_optimizeTrainFromBuffer_fastCover()``. See the corresponding C library + documentation for more. + + If neither ``steps`` nor ``threads`` is defined, defaults for ``d``, ``steps``, + and ``level`` will be used that are equivalent with what + ``ZDICT_trainFromBuffer()`` would use. + + + :param dict_size: + Target size in bytes of the dictionary to generate. + :param samples: + A list of bytes holding samples the dictionary will be trained from. + :param k: + Segment size : constraint: 0 < k : Reasonable range [16, 2048+] + :param d: + dmer size : constraint: 0 < d <= k : Reasonable range [6, 16] + :param f: + log of size of frequency array : constraint: 0 < f <= 31 : 1 means + default(20) + :param split_point: + Percentage of samples used for training: Only used for optimization. + The first # samples * ``split_point`` samples will be used to training. + The last # samples * (1 - split_point) samples will be used for testing. + 0 means default (0.75), 1.0 when all samples are used for both training + and testing. + :param accel: + Acceleration level: constraint: 0 < accel <= 10. Higher means faster + and less accurate, 0 means default(1). + :param dict_id: + Integer dictionary ID for the produced dictionary. Default is 0, which uses + a random value. + :param steps: + Number of steps through ``k`` values to perform when trying parameter + variations. + :param threads: + Number of threads to use when trying parameter variations. Default is 0, + which means to use a single thread. A negative value can be specified to + use as many threads as there are detected logical CPUs. + :param level: + Integer target compression level when trying parameter variations. + :param notifications: + Controls writing of informational messages to ``stderr``. ``0`` (the + default) means to write nothing. ``1`` writes errors. ``2`` writes + progression info. ``3`` writes more details. And ``4`` writes all info. + """ + + if not isinstance(samples, list): + raise TypeError("samples must be a list") + + if threads < 0: + threads = _cpu_count() + + if not steps and not threads: + d = d or 8 + steps = steps or 4 + level = level or 3 + + total_size = sum(map(len, samples)) + + samples_buffer = new_nonzero("char[]", total_size) + sample_sizes = new_nonzero("size_t[]", len(samples)) + + offset = 0 + for i, sample in enumerate(samples): + if not isinstance(sample, bytes): + raise ValueError("samples must be bytes") + + sample_len = len(sample) + ffi.memmove(samples_buffer + offset, sample, sample_len) + offset += sample_len + sample_sizes[i] = sample_len + + dict_data = new_nonzero("char[]", dict_size) + + dparams = ffi.new("ZDICT_fastCover_params_t *")[0] + dparams.k = k + dparams.d = d + dparams.f = f + dparams.steps = steps + dparams.nbThreads = threads + dparams.splitPoint = split_point + dparams.accel = accel + dparams.zParams.notificationLevel = notifications + dparams.zParams.dictID = dict_id + dparams.zParams.compressionLevel = level + + zresult = lib.ZDICT_optimizeTrainFromBuffer_fastCover( + ffi.addressof(dict_data), + dict_size, + ffi.addressof(samples_buffer), + ffi.addressof(sample_sizes, 0), + len(samples), + ffi.addressof(dparams), + ) + + if lib.ZDICT_isError(zresult): + msg = ffi.string(lib.ZDICT_getErrorName(zresult)).decode("utf-8") + raise ZstdError("cannot train dict: %s" % msg) + + return ZstdCompressionDict( + ffi.buffer(dict_data, zresult)[:], + dict_type=DICT_TYPE_FULLDICT, + k=dparams.k, + d=dparams.d, + ) + + +class ZstdDecompressionObj(object): + """A standard library API compatible decompressor. + + This type implements a compressor that conforms to the API by other + decompressors in Python's standard library. e.g. ``zlib.decompressobj`` + or ``bz2.BZ2Decompressor``. This allows callers to use zstd compression + while conforming to a similar API. + + Compressed data chunks are fed into ``decompress(data)`` and + uncompressed output (or an empty bytes) is returned. Output from + subsequent calls needs to be concatenated to reassemble the full + decompressed byte sequence. + + If ``read_across_frames=False``, each instance is single use: once an + input frame is decoded, ``decompress()`` will raise an exception. If + ``read_across_frames=True``, instances can decode multiple frames. + + >>> dctx = zstandard.ZstdDecompressor() + >>> dobj = dctx.decompressobj() + >>> data = dobj.decompress(compressed_chunk_0) + >>> data = dobj.decompress(compressed_chunk_1) + + By default, calls to ``decompress()`` write output data in chunks of size + ``DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE``. These chunks are concatenated + before being returned to the caller. It is possible to define the size of + these temporary chunks by passing ``write_size`` to ``decompressobj()``: + + >>> dctx = zstandard.ZstdDecompressor() + >>> dobj = dctx.decompressobj(write_size=1048576) + + .. note:: + + Because calls to ``decompress()`` may need to perform multiple + memory (re)allocations, this streaming decompression API isn't as + efficient as other APIs. + """ + + def __init__(self, decompressor, write_size, read_across_frames): + self._decompressor = decompressor + self._write_size = write_size + self._finished = False + self._read_across_frames = read_across_frames + self._unused_input = b"" + + def decompress(self, data): + """Send compressed data to the decompressor and obtain decompressed data. + + :param data: + Data to feed into the decompressor. + :return: + Decompressed bytes. + """ + if self._finished: + raise ZstdError("cannot use a decompressobj multiple times") + + in_buffer = ffi.new("ZSTD_inBuffer *") + out_buffer = ffi.new("ZSTD_outBuffer *") + + data_buffer = ffi.from_buffer(data) + + if len(data_buffer) == 0: + return b"" + + in_buffer.src = data_buffer + in_buffer.size = len(data_buffer) + in_buffer.pos = 0 + + dst_buffer = ffi.new("char[]", self._write_size) + out_buffer.dst = dst_buffer + out_buffer.size = len(dst_buffer) + out_buffer.pos = 0 + + chunks = [] + + while True: + zresult = lib.ZSTD_decompressStream( + self._decompressor._dctx, out_buffer, in_buffer + ) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "zstd decompressor error: %s" % _zstd_error(zresult) + ) + + # Always record any output from decompressor. + if out_buffer.pos: + chunks.append(ffi.buffer(out_buffer.dst, out_buffer.pos)[:]) + + # 0 is only seen when a frame is fully decoded *and* fully flushed. + # Behavior depends on whether we're in single or multiple frame + # mode. + if zresult == 0 and not self._read_across_frames: + # Mark the instance as done and make any unconsumed input available + # for retrieval. + self._finished = True + self._decompressor = None + self._unused_input = data[in_buffer.pos : in_buffer.size] + break + elif zresult == 0 and self._read_across_frames: + # We're at the end of a fully flushed frame and we can read more. + # Try to read more if there's any more input. + if in_buffer.pos == in_buffer.size: + break + else: + out_buffer.pos = 0 + + # We're not at the end of the frame *or* we're not fully flushed. + + # The decompressor will write out all the bytes it can to the output + # buffer. So if the output buffer is partially filled and the input + # is exhausted, there's nothing more to write. So we've done all we + # can. + elif ( + in_buffer.pos == in_buffer.size + and out_buffer.pos < out_buffer.size + ): + break + else: + out_buffer.pos = 0 + + return b"".join(chunks) + + def flush(self, length=0): + """Effectively a no-op. + + Implemented for compatibility with the standard library APIs. + + Safe to call at any time. + + :return: + Empty bytes. + """ + return b"" + + @property + def unused_data(self): + """Bytes past the end of compressed data. + + If ``decompress()`` is fed additional data beyond the end of a zstd + frame, this value will be non-empty once ``decompress()`` fully decodes + the input frame. + """ + return self._unused_input + + @property + def unconsumed_tail(self): + """Data that has not yet been fed into the decompressor.""" + return b"" + + @property + def eof(self): + """Whether the end of the compressed data stream has been reached.""" + return self._finished + + +class ZstdDecompressionReader(object): + """Read only decompressor that pull uncompressed data from another stream. + + This type provides a read-only stream interface for performing transparent + decompression from another stream or data source. It conforms to the + ``io.RawIOBase`` interface. Only methods relevant to reading are + implemented. + + >>> with open(path, 'rb') as fh: + >>> dctx = zstandard.ZstdDecompressor() + >>> reader = dctx.stream_reader(fh) + >>> while True: + ... chunk = reader.read(16384) + ... if not chunk: + ... break + ... # Do something with decompressed chunk. + + The stream can also be used as a context manager: + + >>> with open(path, 'rb') as fh: + ... dctx = zstandard.ZstdDecompressor() + ... with dctx.stream_reader(fh) as reader: + ... ... + + When used as a context manager, the stream is closed and the underlying + resources are released when the context manager exits. Future operations + against the stream will fail. + + The ``source`` argument to ``stream_reader()`` can be any object with a + ``read(size)`` method or any object implementing the *buffer protocol*. + + If the ``source`` is a stream, you can specify how large ``read()`` requests + to that stream should be via the ``read_size`` argument. It defaults to + ``zstandard.DECOMPRESSION_RECOMMENDED_INPUT_SIZE``.: + + >>> with open(path, 'rb') as fh: + ... dctx = zstandard.ZstdDecompressor() + ... # Will perform fh.read(8192) when obtaining data for the decompressor. + ... with dctx.stream_reader(fh, read_size=8192) as reader: + ... ... + + Instances are *partially* seekable. Absolute and relative positions + (``SEEK_SET`` and ``SEEK_CUR``) forward of the current position are + allowed. Offsets behind the current read position and offsets relative + to the end of stream are not allowed and will raise ``ValueError`` + if attempted. + + ``tell()`` returns the number of decompressed bytes read so far. + + Not all I/O methods are implemented. Notably missing is support for + ``readline()``, ``readlines()``, and linewise iteration support. This is + because streams operate on binary data - not text data. If you want to + convert decompressed output to text, you can chain an ``io.TextIOWrapper`` + to the stream: + + >>> with open(path, 'rb') as fh: + ... dctx = zstandard.ZstdDecompressor() + ... stream_reader = dctx.stream_reader(fh) + ... text_stream = io.TextIOWrapper(stream_reader, encoding='utf-8') + ... for line in text_stream: + ... ... + """ + + def __init__( + self, + decompressor, + source, + read_size, + read_across_frames, + closefd=True, + ): + self._decompressor = decompressor + self._source = source + self._read_size = read_size + self._read_across_frames = bool(read_across_frames) + self._closefd = bool(closefd) + self._entered = False + self._closed = False + self._bytes_decompressed = 0 + self._finished_input = False + self._finished_output = False + self._in_buffer = ffi.new("ZSTD_inBuffer *") + # Holds a ref to self._in_buffer.src. + self._source_buffer = None + + def __enter__(self): + if self._entered: + raise ValueError("cannot __enter__ multiple times") + + if self._closed: + raise ValueError("stream is closed") + + self._entered = True + return self + + def __exit__(self, exc_type, exc_value, exc_tb): + self._entered = False + self._decompressor = None + self.close() + self._source = None + + return False + + def readable(self): + return True + + def writable(self): + return False + + def seekable(self): + return False + + def readline(self, size=-1): + raise io.UnsupportedOperation() + + def readlines(self, hint=-1): + raise io.UnsupportedOperation() + + def write(self, data): + raise io.UnsupportedOperation() + + def writelines(self, lines): + raise io.UnsupportedOperation() + + def isatty(self): + return False + + def flush(self): + return None + + def close(self): + if self._closed: + return None + + self._closed = True + + f = getattr(self._source, "close", None) + if self._closefd and f: + f() + + @property + def closed(self): + return self._closed + + def tell(self): + return self._bytes_decompressed + + def readall(self): + chunks = [] + + while True: + chunk = self.read(1048576) + if not chunk: + break + + chunks.append(chunk) + + return b"".join(chunks) + + def __iter__(self): + raise io.UnsupportedOperation() + + def __next__(self): + raise io.UnsupportedOperation() + + next = __next__ + + def _read_input(self): + # We have data left over in the input buffer. Use it. + if self._in_buffer.pos < self._in_buffer.size: + return + + # All input data exhausted. Nothing to do. + if self._finished_input: + return + + # Else populate the input buffer from our source. + if hasattr(self._source, "read"): + data = self._source.read(self._read_size) + + if not data: + self._finished_input = True + return + + self._source_buffer = ffi.from_buffer(data) + self._in_buffer.src = self._source_buffer + self._in_buffer.size = len(self._source_buffer) + self._in_buffer.pos = 0 + else: + self._source_buffer = ffi.from_buffer(self._source) + self._in_buffer.src = self._source_buffer + self._in_buffer.size = len(self._source_buffer) + self._in_buffer.pos = 0 + + def _decompress_into_buffer(self, out_buffer): + """Decompress available input into an output buffer. + + Returns True if data in output buffer should be emitted. + """ + zresult = lib.ZSTD_decompressStream( + self._decompressor._dctx, out_buffer, self._in_buffer + ) + + if self._in_buffer.pos == self._in_buffer.size: + self._in_buffer.src = ffi.NULL + self._in_buffer.pos = 0 + self._in_buffer.size = 0 + self._source_buffer = None + + if not hasattr(self._source, "read"): + self._finished_input = True + + if lib.ZSTD_isError(zresult): + raise ZstdError("zstd decompress error: %s" % _zstd_error(zresult)) + + # Emit data if there is data AND either: + # a) output buffer is full (read amount is satisfied) + # b) we're at end of a frame and not in frame spanning mode + return out_buffer.pos and ( + out_buffer.pos == out_buffer.size + or zresult == 0 + and not self._read_across_frames + ) + + def read(self, size=-1): + if self._closed: + raise ValueError("stream is closed") + + if size < -1: + raise ValueError("cannot read negative amounts less than -1") + + if size == -1: + # This is recursive. But it gets the job done. + return self.readall() + + if self._finished_output or size == 0: + return b"" + + # We /could/ call into readinto() here. But that introduces more + # overhead. + dst_buffer = ffi.new("char[]", size) + out_buffer = ffi.new("ZSTD_outBuffer *") + out_buffer.dst = dst_buffer + out_buffer.size = size + out_buffer.pos = 0 + + self._read_input() + if self._decompress_into_buffer(out_buffer): + self._bytes_decompressed += out_buffer.pos + return ffi.buffer(out_buffer.dst, out_buffer.pos)[:] + + while not self._finished_input: + self._read_input() + if self._decompress_into_buffer(out_buffer): + self._bytes_decompressed += out_buffer.pos + return ffi.buffer(out_buffer.dst, out_buffer.pos)[:] + + self._bytes_decompressed += out_buffer.pos + return ffi.buffer(out_buffer.dst, out_buffer.pos)[:] + + def readinto(self, b): + if self._closed: + raise ValueError("stream is closed") + + if self._finished_output: + return 0 + + # TODO use writable=True once we require CFFI >= 1.12. + dest_buffer = ffi.from_buffer(b) + ffi.memmove(b, b"", 0) + out_buffer = ffi.new("ZSTD_outBuffer *") + out_buffer.dst = dest_buffer + out_buffer.size = len(dest_buffer) + out_buffer.pos = 0 + + self._read_input() + if self._decompress_into_buffer(out_buffer): + self._bytes_decompressed += out_buffer.pos + return out_buffer.pos + + while not self._finished_input: + self._read_input() + if self._decompress_into_buffer(out_buffer): + self._bytes_decompressed += out_buffer.pos + return out_buffer.pos + + self._bytes_decompressed += out_buffer.pos + return out_buffer.pos + + def read1(self, size=-1): + if self._closed: + raise ValueError("stream is closed") + + if size < -1: + raise ValueError("cannot read negative amounts less than -1") + + if self._finished_output or size == 0: + return b"" + + # -1 returns arbitrary number of bytes. + if size == -1: + size = DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE + + dst_buffer = ffi.new("char[]", size) + out_buffer = ffi.new("ZSTD_outBuffer *") + out_buffer.dst = dst_buffer + out_buffer.size = size + out_buffer.pos = 0 + + # read1() dictates that we can perform at most 1 call to underlying + # stream to get input. However, we can't satisfy this restriction with + # decompression because not all input generates output. So we allow + # multiple read(). But unlike read(), we stop once we have any output. + while not self._finished_input: + self._read_input() + self._decompress_into_buffer(out_buffer) + + if out_buffer.pos: + break + + self._bytes_decompressed += out_buffer.pos + return ffi.buffer(out_buffer.dst, out_buffer.pos)[:] + + def readinto1(self, b): + if self._closed: + raise ValueError("stream is closed") + + if self._finished_output: + return 0 + + # TODO use writable=True once we require CFFI >= 1.12. + dest_buffer = ffi.from_buffer(b) + ffi.memmove(b, b"", 0) + + out_buffer = ffi.new("ZSTD_outBuffer *") + out_buffer.dst = dest_buffer + out_buffer.size = len(dest_buffer) + out_buffer.pos = 0 + + while not self._finished_input and not self._finished_output: + self._read_input() + self._decompress_into_buffer(out_buffer) + + if out_buffer.pos: + break + + self._bytes_decompressed += out_buffer.pos + return out_buffer.pos + + def seek(self, pos, whence=os.SEEK_SET): + if self._closed: + raise ValueError("stream is closed") + + read_amount = 0 + + if whence == os.SEEK_SET: + if pos < 0: + raise OSError("cannot seek to negative position with SEEK_SET") + + if pos < self._bytes_decompressed: + raise OSError("cannot seek zstd decompression stream backwards") + + read_amount = pos - self._bytes_decompressed + + elif whence == os.SEEK_CUR: + if pos < 0: + raise OSError("cannot seek zstd decompression stream backwards") + + read_amount = pos + elif whence == os.SEEK_END: + raise OSError( + "zstd decompression streams cannot be seeked with SEEK_END" + ) + + while read_amount: + result = self.read( + min(read_amount, DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE) + ) + + if not result: + break + + read_amount -= len(result) + + return self._bytes_decompressed + + +class ZstdDecompressionWriter(object): + """ + Write-only stream wrapper that performs decompression. + + This type provides a writable stream that performs decompression and writes + decompressed data to another stream. + + This type implements the ``io.RawIOBase`` interface. Only methods that + involve writing will do useful things. + + Behavior is similar to :py:meth:`ZstdCompressor.stream_writer`: compressed + data is sent to the decompressor by calling ``write(data)`` and decompressed + output is written to the inner stream by calling its ``write(data)`` + method: + + >>> dctx = zstandard.ZstdDecompressor() + >>> decompressor = dctx.stream_writer(fh) + >>> # Will call fh.write() with uncompressed data. + >>> decompressor.write(compressed_data) + + Instances can be used as context managers. However, context managers add no + extra special behavior other than automatically calling ``close()`` when + they exit. + + Calling ``close()`` will mark the stream as closed and subsequent I/O + operations will raise ``ValueError`` (per the documented behavior of + ``io.RawIOBase``). ``close()`` will also call ``close()`` on the + underlying stream if such a method exists and the instance was created with + ``closefd=True``. + + The size of chunks to ``write()`` to the destination can be specified: + + >>> dctx = zstandard.ZstdDecompressor() + >>> with dctx.stream_writer(fh, write_size=16384) as decompressor: + >>> pass + + You can see how much memory is being used by the decompressor: + + >>> dctx = zstandard.ZstdDecompressor() + >>> with dctx.stream_writer(fh) as decompressor: + >>> byte_size = decompressor.memory_size() + + ``stream_writer()`` accepts a ``write_return_read`` boolean argument to control + the return value of ``write()``. When ``True`` (the default)``, ``write()`` + returns the number of bytes that were read from the input. When ``False``, + ``write()`` returns the number of bytes that were ``write()`` to the inner + stream. + """ + + def __init__( + self, + decompressor, + writer, + write_size, + write_return_read, + closefd=True, + ): + decompressor._ensure_dctx() + + self._decompressor = decompressor + self._writer = writer + self._write_size = write_size + self._write_return_read = bool(write_return_read) + self._closefd = bool(closefd) + self._entered = False + self._closing = False + self._closed = False + + def __enter__(self): + if self._closed: + raise ValueError("stream is closed") + + if self._entered: + raise ZstdError("cannot __enter__ multiple times") + + self._entered = True + + return self + + def __exit__(self, exc_type, exc_value, exc_tb): + self._entered = False + self.close() + + return False + + def __iter__(self): + raise io.UnsupportedOperation() + + def __next__(self): + raise io.UnsupportedOperation() + + def memory_size(self): + return lib.ZSTD_sizeof_DCtx(self._decompressor._dctx) + + def close(self): + if self._closed: + return + + try: + self._closing = True + self.flush() + finally: + self._closing = False + self._closed = True + + f = getattr(self._writer, "close", None) + if self._closefd and f: + f() + + @property + def closed(self): + return self._closed + + def fileno(self): + f = getattr(self._writer, "fileno", None) + if f: + return f() + else: + raise OSError("fileno not available on underlying writer") + + def flush(self): + if self._closed: + raise ValueError("stream is closed") + + f = getattr(self._writer, "flush", None) + if f and not self._closing: + return f() + + def isatty(self): + return False + + def readable(self): + return False + + def readline(self, size=-1): + raise io.UnsupportedOperation() + + def readlines(self, hint=-1): + raise io.UnsupportedOperation() + + def seek(self, offset, whence=None): + raise io.UnsupportedOperation() + + def seekable(self): + return False + + def tell(self): + raise io.UnsupportedOperation() + + def truncate(self, size=None): + raise io.UnsupportedOperation() + + def writable(self): + return True + + def writelines(self, lines): + raise io.UnsupportedOperation() + + def read(self, size=-1): + raise io.UnsupportedOperation() + + def readall(self): + raise io.UnsupportedOperation() + + def readinto(self, b): + raise io.UnsupportedOperation() + + def write(self, data): + if self._closed: + raise ValueError("stream is closed") + + total_write = 0 + + in_buffer = ffi.new("ZSTD_inBuffer *") + out_buffer = ffi.new("ZSTD_outBuffer *") + + data_buffer = ffi.from_buffer(data) + in_buffer.src = data_buffer + in_buffer.size = len(data_buffer) + in_buffer.pos = 0 + + dst_buffer = ffi.new("char[]", self._write_size) + out_buffer.dst = dst_buffer + out_buffer.size = len(dst_buffer) + out_buffer.pos = 0 + + dctx = self._decompressor._dctx + + while in_buffer.pos < in_buffer.size: + zresult = lib.ZSTD_decompressStream(dctx, out_buffer, in_buffer) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "zstd decompress error: %s" % _zstd_error(zresult) + ) + + if out_buffer.pos: + self._writer.write( + ffi.buffer(out_buffer.dst, out_buffer.pos)[:] + ) + total_write += out_buffer.pos + out_buffer.pos = 0 + + if self._write_return_read: + return in_buffer.pos + else: + return total_write + + +class ZstdDecompressor(object): + """ + Context for performing zstandard decompression. + + Each instance is essentially a wrapper around a ``ZSTD_DCtx`` from zstd's + C API. + + An instance can compress data various ways. Instances can be used multiple + times. + + The interface of this class is very similar to + :py:class:`zstandard.ZstdCompressor` (by design). + + Assume that each ``ZstdDecompressor`` instance can only handle a single + logical compression operation at the same time. i.e. if you call a method + like ``decompressobj()`` to obtain multiple objects derived from the same + ``ZstdDecompressor`` instance and attempt to use them simultaneously, errors + will likely occur. + + If you need to perform multiple logical decompression operations and you + can't guarantee those operations are temporally non-overlapping, you need + to obtain multiple ``ZstdDecompressor`` instances. + + Unless specified otherwise, assume that no two methods of + ``ZstdDecompressor`` instances can be called from multiple Python + threads simultaneously. In other words, assume instances are not thread safe + unless stated otherwise. + + :param dict_data: + Compression dictionary to use. + :param max_window_size: + Sets an upper limit on the window size for decompression operations in + kibibytes. This setting can be used to prevent large memory allocations + for inputs using large compression windows. + :param format: + Set the format of data for the decoder. + + By default this is ``zstandard.FORMAT_ZSTD1``. It can be set to + ``zstandard.FORMAT_ZSTD1_MAGICLESS`` to allow decoding frames without + the 4 byte magic header. Not all decompression APIs support this mode. + """ + + def __init__(self, dict_data=None, max_window_size=0, format=FORMAT_ZSTD1): + self._dict_data = dict_data + self._max_window_size = max_window_size + self._format = format + + dctx = lib.ZSTD_createDCtx() + if dctx == ffi.NULL: + raise MemoryError() + + self._dctx = dctx + + # Defer setting up garbage collection until full state is loaded so + # the memory size is more accurate. + try: + self._ensure_dctx() + finally: + self._dctx = ffi.gc( + dctx, lib.ZSTD_freeDCtx, size=lib.ZSTD_sizeof_DCtx(dctx) + ) + + def memory_size(self): + """Size of decompression context, in bytes. + + >>> dctx = zstandard.ZstdDecompressor() + >>> size = dctx.memory_size() + """ + return lib.ZSTD_sizeof_DCtx(self._dctx) + + def decompress( + self, + data, + max_output_size=0, + read_across_frames=False, + allow_extra_data=True, + ): + """ + Decompress data in a single operation. + + This method will decompress the input data in a single operation and + return the decompressed data. + + The input bytes are expected to contain at least 1 full Zstandard frame + (something compressed with :py:meth:`ZstdCompressor.compress` or + similar). If the input does not contain a full frame, an exception will + be raised. + + ``read_across_frames`` controls whether to read multiple zstandard + frames in the input. When False, decompression stops after reading the + first frame. This feature is not yet implemented but the argument is + provided for forward API compatibility when the default is changed to + True in a future release. For now, if you need to decompress multiple + frames, use an API like :py:meth:`ZstdCompressor.stream_reader` with + ``read_across_frames=True``. + + ``allow_extra_data`` controls how to handle extra input data after a + fully decoded frame. If False, any extra data (which could be a valid + zstd frame) will result in ``ZstdError`` being raised. If True, extra + data is silently ignored. The default will likely change to False in a + future release when ``read_across_frames`` defaults to True. + + If the input contains extra data after a full frame, that extra input + data is silently ignored. This behavior is undesirable in many scenarios + and will likely be changed or controllable in a future release (see + #181). + + If the frame header of the compressed data does not contain the content + size, ``max_output_size`` must be specified or ``ZstdError`` will be + raised. An allocation of size ``max_output_size`` will be performed and an + attempt will be made to perform decompression into that buffer. If the + buffer is too small or cannot be allocated, ``ZstdError`` will be + raised. The buffer will be resized if it is too large. + + Uncompressed data could be much larger than compressed data. As a result, + calling this function could result in a very large memory allocation + being performed to hold the uncompressed data. This could potentially + result in ``MemoryError`` or system memory swapping. If you don't need + the full output data in a single contiguous array in memory, consider + using streaming decompression for more resilient memory behavior. + + Usage: + + >>> dctx = zstandard.ZstdDecompressor() + >>> decompressed = dctx.decompress(data) + + If the compressed data doesn't have its content size embedded within it, + decompression can be attempted by specifying the ``max_output_size`` + argument: + + >>> dctx = zstandard.ZstdDecompressor() + >>> uncompressed = dctx.decompress(data, max_output_size=1048576) + + Ideally, ``max_output_size`` will be identical to the decompressed + output size. + + .. important:: + + If the exact size of decompressed data is unknown (not passed in + explicitly and not stored in the zstd frame), for performance + reasons it is encouraged to use a streaming API. + + :param data: + Compressed data to decompress. + :param max_output_size: + Integer max size of response. + + If ``0``, there is no limit and we can attempt to allocate an output + buffer of infinite size. + :return: + ``bytes`` representing decompressed output. + """ + + if read_across_frames: + raise ZstdError( + "ZstdDecompressor.read_across_frames=True is not yet implemented" + ) + + self._ensure_dctx() + + data_buffer = ffi.from_buffer(data) + + params = ffi.new("ZSTD_FrameHeader *") + zresult = lib.ZSTD_getFrameHeader_advanced( + params, data_buffer, len(data_buffer), self._format + ) + if zresult != 0: + raise ZstdError("error determining content size from frame header") + output_size = params.frameContentSize + if output_size == 0: + return b"" + elif output_size == lib.ZSTD_CONTENTSIZE_UNKNOWN: + if not max_output_size: + raise ZstdError( + "could not determine content size in frame header" + ) + + result_buffer = ffi.new("char[]", max_output_size) + result_size = max_output_size + output_size = 0 + else: + result_buffer = ffi.new("char[]", output_size) + result_size = output_size + + out_buffer = ffi.new("ZSTD_outBuffer *") + out_buffer.dst = result_buffer + out_buffer.size = result_size + out_buffer.pos = 0 + + in_buffer = ffi.new("ZSTD_inBuffer *") + in_buffer.src = data_buffer + in_buffer.size = len(data_buffer) + in_buffer.pos = 0 + + zresult = lib.ZSTD_decompressStream(self._dctx, out_buffer, in_buffer) + if lib.ZSTD_isError(zresult): + raise ZstdError("decompression error: %s" % _zstd_error(zresult)) + elif zresult: + raise ZstdError( + "decompression error: did not decompress full frame" + ) + elif output_size and out_buffer.pos != output_size: + raise ZstdError( + "decompression error: decompressed %d bytes; expected %d" + % (zresult, output_size) + ) + elif not allow_extra_data and in_buffer.pos < in_buffer.size: + count = in_buffer.size - in_buffer.pos + + raise ZstdError( + "compressed input contains %d bytes of unused data, which is disallowed" + % count + ) + + return ffi.buffer(result_buffer, out_buffer.pos)[:] + + def stream_reader( + self, + source, + read_size=DECOMPRESSION_RECOMMENDED_INPUT_SIZE, + read_across_frames=False, + closefd=True, + ): + """ + Read-only stream wrapper that performs decompression. + + This method obtains an object that conforms to the ``io.RawIOBase`` + interface and performs transparent decompression via ``read()`` + operations. Source data is obtained by calling ``read()`` on a + source stream or object implementing the buffer protocol. + + See :py:class:`zstandard.ZstdDecompressionReader` for more documentation + and usage examples. + + :param source: + Source of compressed data to decompress. Can be any object + with a ``read(size)`` method or that conforms to the buffer protocol. + :param read_size: + Integer number of bytes to read from the source and feed into the + compressor at a time. + :param read_across_frames: + Whether to read data across multiple zstd frames. If False, + decompression is stopped at frame boundaries. + :param closefd: + Whether to close the source stream when this instance is closed. + :return: + :py:class:`zstandard.ZstdDecompressionReader`. + """ + self._ensure_dctx() + return ZstdDecompressionReader( + self, source, read_size, read_across_frames, closefd=closefd + ) + + def decompressobj( + self, + write_size=DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE, + read_across_frames=False, + ): + """Obtain a standard library compatible incremental decompressor. + + See :py:class:`ZstdDecompressionObj` for more documentation + and usage examples. + + :param write_size: size of internal output buffer to collect decompressed + chunks in. + :param read_across_frames: whether to read across multiple zstd frames. + If False, reading stops after 1 frame and subsequent decompress + attempts will raise an exception. + :return: + :py:class:`zstandard.ZstdDecompressionObj` + """ + if write_size < 1: + raise ValueError("write_size must be positive") + + self._ensure_dctx() + return ZstdDecompressionObj( + self, write_size=write_size, read_across_frames=read_across_frames + ) + + def read_to_iter( + self, + reader, + read_size=DECOMPRESSION_RECOMMENDED_INPUT_SIZE, + write_size=DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE, + skip_bytes=0, + ): + """Read compressed data to an iterator of uncompressed chunks. + + This method will read data from ``reader``, feed it to a decompressor, + and emit ``bytes`` chunks representing the decompressed result. + + >>> dctx = zstandard.ZstdDecompressor() + >>> for chunk in dctx.read_to_iter(fh): + ... # Do something with original data. + + ``read_to_iter()`` accepts an object with a ``read(size)`` method that + will return compressed bytes or an object conforming to the buffer + protocol. + + ``read_to_iter()`` returns an iterator whose elements are chunks of the + decompressed data. + + The size of requested ``read()`` from the source can be specified: + + >>> dctx = zstandard.ZstdDecompressor() + >>> for chunk in dctx.read_to_iter(fh, read_size=16384): + ... pass + + It is also possible to skip leading bytes in the input data: + + >>> dctx = zstandard.ZstdDecompressor() + >>> for chunk in dctx.read_to_iter(fh, skip_bytes=1): + ... pass + + .. tip:: + + Skipping leading bytes is useful if the source data contains extra + *header* data. Traditionally, you would need to create a slice or + ``memoryview`` of the data you want to decompress. This would create + overhead. It is more efficient to pass the offset into this API. + + Similarly to :py:meth:`ZstdCompressor.read_to_iter`, the consumer of the + iterator controls when data is decompressed. If the iterator isn't consumed, + decompression is put on hold. + + When ``read_to_iter()`` is passed an object conforming to the buffer protocol, + the behavior may seem similar to what occurs when the simple decompression + API is used. However, this API works when the decompressed size is unknown. + Furthermore, if feeding large inputs, the decompressor will work in chunks + instead of performing a single operation. + + :param reader: + Source of compressed data. Can be any object with a + ``read(size)`` method or any object conforming to the buffer + protocol. + :param read_size: + Integer size of data chunks to read from ``reader`` and feed into + the decompressor. + :param write_size: + Integer size of data chunks to emit from iterator. + :param skip_bytes: + Integer number of bytes to skip over before sending data into + the decompressor. + :return: + Iterator of ``bytes`` representing uncompressed data. + """ + + if skip_bytes >= read_size: + raise ValueError("skip_bytes must be smaller than read_size") + + if hasattr(reader, "read"): + have_read = True + elif hasattr(reader, "__getitem__"): + have_read = False + buffer_offset = 0 + size = len(reader) + else: + raise ValueError( + "must pass an object with a read() method or " + "conforms to buffer protocol" + ) + + if skip_bytes: + if have_read: + reader.read(skip_bytes) + else: + if skip_bytes > size: + raise ValueError("skip_bytes larger than first input chunk") + + buffer_offset = skip_bytes + + self._ensure_dctx() + + in_buffer = ffi.new("ZSTD_inBuffer *") + out_buffer = ffi.new("ZSTD_outBuffer *") + + dst_buffer = ffi.new("char[]", write_size) + out_buffer.dst = dst_buffer + out_buffer.size = len(dst_buffer) + out_buffer.pos = 0 + + while True: + assert out_buffer.pos == 0 + + if have_read: + read_result = reader.read(read_size) + else: + remaining = size - buffer_offset + slice_size = min(remaining, read_size) + read_result = reader[buffer_offset : buffer_offset + slice_size] + buffer_offset += slice_size + + # No new input. Break out of read loop. + if not read_result: + break + + # Feed all read data into decompressor and emit output until + # exhausted. + read_buffer = ffi.from_buffer(read_result) + in_buffer.src = read_buffer + in_buffer.size = len(read_buffer) + in_buffer.pos = 0 + + while in_buffer.pos < in_buffer.size: + assert out_buffer.pos == 0 + + zresult = lib.ZSTD_decompressStream( + self._dctx, out_buffer, in_buffer + ) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "zstd decompress error: %s" % _zstd_error(zresult) + ) + + if out_buffer.pos: + data = ffi.buffer(out_buffer.dst, out_buffer.pos)[:] + out_buffer.pos = 0 + yield data + + if zresult == 0: + return + + # Repeat loop to collect more input data. + continue + + # If we get here, input is exhausted. + + def stream_writer( + self, + writer, + write_size=DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE, + write_return_read=True, + closefd=True, + ): + """ + Push-based stream wrapper that performs decompression. + + This method constructs a stream wrapper that conforms to the + ``io.RawIOBase`` interface and performs transparent decompression + when writing to a wrapper stream. + + See :py:class:`zstandard.ZstdDecompressionWriter` for more documentation + and usage examples. + + :param writer: + Destination for decompressed output. Can be any object with a + ``write(data)``. + :param write_size: + Integer size of chunks to ``write()`` to ``writer``. + :param write_return_read: + Whether ``write()`` should return the number of bytes of input + consumed. If False, ``write()`` returns the number of bytes sent + to the inner stream. + :param closefd: + Whether to ``close()`` the inner stream when this stream is closed. + :return: + :py:class:`zstandard.ZstdDecompressionWriter` + """ + if not hasattr(writer, "write"): + raise ValueError("must pass an object with a write() method") + + return ZstdDecompressionWriter( + self, + writer, + write_size, + write_return_read, + closefd=closefd, + ) + + def copy_stream( + self, + ifh, + ofh, + read_size=DECOMPRESSION_RECOMMENDED_INPUT_SIZE, + write_size=DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE, + ): + """ + Copy data between streams, decompressing in the process. + + Compressed data will be read from ``ifh``, decompressed, and written + to ``ofh``. + + >>> dctx = zstandard.ZstdDecompressor() + >>> dctx.copy_stream(ifh, ofh) + + e.g. to decompress a file to another file: + + >>> dctx = zstandard.ZstdDecompressor() + >>> with open(input_path, 'rb') as ifh, open(output_path, 'wb') as ofh: + ... dctx.copy_stream(ifh, ofh) + + The size of chunks being ``read()`` and ``write()`` from and to the + streams can be specified: + + >>> dctx = zstandard.ZstdDecompressor() + >>> dctx.copy_stream(ifh, ofh, read_size=8192, write_size=16384) + + :param ifh: + Source stream to read compressed data from. + + Must have a ``read()`` method. + :param ofh: + Destination stream to write uncompressed data to. + + Must have a ``write()`` method. + :param read_size: + The number of bytes to ``read()`` from the source in a single + operation. + :param write_size: + The number of bytes to ``write()`` to the destination in a single + operation. + :return: + 2-tuple of integers representing the number of bytes read and + written, respectively. + """ + + if not hasattr(ifh, "read"): + raise ValueError("first argument must have a read() method") + if not hasattr(ofh, "write"): + raise ValueError("second argument must have a write() method") + + self._ensure_dctx() + + in_buffer = ffi.new("ZSTD_inBuffer *") + out_buffer = ffi.new("ZSTD_outBuffer *") + + dst_buffer = ffi.new("char[]", write_size) + out_buffer.dst = dst_buffer + out_buffer.size = write_size + out_buffer.pos = 0 + + total_read, total_write = 0, 0 + + # Read all available input. + while True: + data = ifh.read(read_size) + if not data: + break + + data_buffer = ffi.from_buffer(data) + total_read += len(data_buffer) + in_buffer.src = data_buffer + in_buffer.size = len(data_buffer) + in_buffer.pos = 0 + + # Flush all read data to output. + while in_buffer.pos < in_buffer.size: + zresult = lib.ZSTD_decompressStream( + self._dctx, out_buffer, in_buffer + ) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "zstd decompressor error: %s" % _zstd_error(zresult) + ) + + if out_buffer.pos: + ofh.write(ffi.buffer(out_buffer.dst, out_buffer.pos)) + total_write += out_buffer.pos + out_buffer.pos = 0 + + # Continue loop to keep reading. + + return total_read, total_write + + def decompress_content_dict_chain(self, frames): + """ + Decompress a series of frames using the content dictionary chaining technique. + + Such a list of frames is produced by compressing discrete inputs where + each non-initial input is compressed with a *prefix* dictionary consisting + of the content of the previous input. + + For example, say you have the following inputs: + + >>> inputs = [b"input 1", b"input 2", b"input 3"] + + The zstd frame chain consists of: + + 1. ``b"input 1"`` compressed in standalone/discrete mode + 2. ``b"input 2"`` compressed using ``b"input 1"`` as a *prefix* dictionary + 3. ``b"input 3"`` compressed using ``b"input 2"`` as a *prefix* dictionary + + Each zstd frame **must** have the content size written. + + The following Python code can be used to produce a *prefix dictionary chain*: + + >>> def make_chain(inputs): + ... frames = [] + ... + ... # First frame is compressed in standalone/discrete mode. + ... zctx = zstandard.ZstdCompressor() + ... frames.append(zctx.compress(inputs[0])) + ... + ... # Subsequent frames use the previous fulltext as a prefix dictionary + ... for i, raw in enumerate(inputs[1:]): + ... dict_data = zstandard.ZstdCompressionDict( + ... inputs[i], dict_type=zstandard.DICT_TYPE_RAWCONTENT) + ... zctx = zstandard.ZstdCompressor(dict_data=dict_data) + ... frames.append(zctx.compress(raw)) + ... + ... return frames + + ``decompress_content_dict_chain()`` returns the uncompressed data of the last + element in the input chain. + + .. note:: + + It is possible to implement *prefix dictionary chain* decompression + on top of other APIs. However, this function will likely be faster - + especially for long input chains - as it avoids the overhead of + instantiating and passing around intermediate objects between + multiple functions. + + :param frames: + List of ``bytes`` holding compressed zstd frames. + :return: + """ + if not isinstance(frames, list): + raise TypeError("argument must be a list") + + if not frames: + raise ValueError("empty input chain") + + # First chunk should not be using a dictionary. We handle it specially. + chunk = frames[0] + if not isinstance(chunk, bytes): + raise ValueError("chunk 0 must be bytes") + + # All chunks should be zstd frames and should have content size set. + chunk_buffer = ffi.from_buffer(chunk) + params = ffi.new("ZSTD_FrameHeader *") + zresult = lib.ZSTD_getFrameHeader( + params, chunk_buffer, len(chunk_buffer) + ) + if lib.ZSTD_isError(zresult): + raise ValueError("chunk 0 is not a valid zstd frame") + elif zresult: + raise ValueError("chunk 0 is too small to contain a zstd frame") + + if params.frameContentSize == lib.ZSTD_CONTENTSIZE_UNKNOWN: + raise ValueError("chunk 0 missing content size in frame") + + self._ensure_dctx(load_dict=False) + + last_buffer = ffi.new("char[]", params.frameContentSize) + + out_buffer = ffi.new("ZSTD_outBuffer *") + out_buffer.dst = last_buffer + out_buffer.size = len(last_buffer) + out_buffer.pos = 0 + + in_buffer = ffi.new("ZSTD_inBuffer *") + in_buffer.src = chunk_buffer + in_buffer.size = len(chunk_buffer) + in_buffer.pos = 0 + + zresult = lib.ZSTD_decompressStream(self._dctx, out_buffer, in_buffer) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "could not decompress chunk 0: %s" % _zstd_error(zresult) + ) + elif zresult: + raise ZstdError("chunk 0 did not decompress full frame") + + # Special case of chain length of 1 + if len(frames) == 1: + return ffi.buffer(last_buffer, len(last_buffer))[:] + + i = 1 + while i < len(frames): + chunk = frames[i] + if not isinstance(chunk, bytes): + raise ValueError("chunk %d must be bytes" % i) + + chunk_buffer = ffi.from_buffer(chunk) + zresult = lib.ZSTD_getFrameHeader( + params, chunk_buffer, len(chunk_buffer) + ) + if lib.ZSTD_isError(zresult): + raise ValueError("chunk %d is not a valid zstd frame" % i) + elif zresult: + raise ValueError( + "chunk %d is too small to contain a zstd frame" % i + ) + + if params.frameContentSize == lib.ZSTD_CONTENTSIZE_UNKNOWN: + raise ValueError("chunk %d missing content size in frame" % i) + + dest_buffer = ffi.new("char[]", params.frameContentSize) + + out_buffer.dst = dest_buffer + out_buffer.size = len(dest_buffer) + out_buffer.pos = 0 + + in_buffer.src = chunk_buffer + in_buffer.size = len(chunk_buffer) + in_buffer.pos = 0 + + zresult = lib.ZSTD_decompressStream( + self._dctx, out_buffer, in_buffer + ) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "could not decompress chunk %d: %s" % _zstd_error(zresult) + ) + elif zresult: + raise ZstdError("chunk %d did not decompress full frame" % i) + + last_buffer = dest_buffer + i += 1 + + return ffi.buffer(last_buffer, len(last_buffer))[:] + + def multi_decompress_to_buffer( + self, frames, decompressed_sizes=None, threads=0 + ): + """ + Decompress multiple zstd frames to output buffers as a single operation. + + (Experimental. Not available in CFFI backend.) + + Compressed frames can be passed to the function as a + ``BufferWithSegments``, a ``BufferWithSegmentsCollection``, or as a + list containing objects that conform to the buffer protocol. For best + performance, pass a ``BufferWithSegmentsCollection`` or a + ``BufferWithSegments``, as minimal input validation will be done for + that type. If calling from Python (as opposed to C), constructing one + of these instances may add overhead cancelling out the performance + overhead of validation for list inputs. + + Returns a ``BufferWithSegmentsCollection`` containing the decompressed + data. All decompressed data is allocated in a single memory buffer. The + ``BufferWithSegments`` instance tracks which objects are at which offsets + and their respective lengths. + + >>> dctx = zstandard.ZstdDecompressor() + >>> results = dctx.multi_decompress_to_buffer([b'...', b'...']) + + The decompressed size of each frame MUST be discoverable. It can either be + embedded within the zstd frame or passed in via the ``decompressed_sizes`` + argument. + + The ``decompressed_sizes`` argument is an object conforming to the buffer + protocol which holds an array of 64-bit unsigned integers in the machine's + native format defining the decompressed sizes of each frame. If this argument + is passed, it avoids having to scan each frame for its decompressed size. + This frame scanning can add noticeable overhead in some scenarios. + + >>> frames = [...] + >>> sizes = struct.pack('=QQQQ', len0, len1, len2, len3) + >>> + >>> dctx = zstandard.ZstdDecompressor() + >>> results = dctx.multi_decompress_to_buffer(frames, decompressed_sizes=sizes) + + .. note:: + + It is possible to pass a ``mmap.mmap()`` instance into this function by + wrapping it with a ``BufferWithSegments`` instance (which will define the + offsets of frames within the memory mapped region). + + This function is logically equivalent to performing + :py:meth:`ZstdCompressor.decompress` on each input frame and returning the + result. + + This function exists to perform decompression on multiple frames as fast + as possible by having as little overhead as possible. Since decompression is + performed as a single operation and since the decompressed output is stored in + a single buffer, extra memory allocations, Python objects, and Python function + calls are avoided. This is ideal for scenarios where callers know up front that + they need to access data for multiple frames, such as when *delta chains* are + being used. + + Currently, the implementation always spawns multiple threads when requested, + even if the amount of work to do is small. In the future, it will be smarter + about avoiding threads and their associated overhead when the amount of + work to do is small. + + :param frames: + Source defining zstd frames to decompress. + :param decompressed_sizes: + Array of integers representing sizes of decompressed zstd frames. + :param threads: + How many threads to use for decompression operations. + + Negative values will use the same number of threads as logical CPUs + on the machine. Values ``0`` or ``1`` use a single thread. + :return: + ``BufferWithSegmentsCollection`` + """ + raise NotImplementedError() + + def _ensure_dctx(self, load_dict=True): + lib.ZSTD_DCtx_reset(self._dctx, lib.ZSTD_reset_session_only) + + if self._max_window_size: + zresult = lib.ZSTD_DCtx_setMaxWindowSize( + self._dctx, self._max_window_size + ) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "unable to set max window size: %s" % _zstd_error(zresult) + ) + + zresult = lib.ZSTD_DCtx_setParameter( + self._dctx, lib.ZSTD_d_format, self._format + ) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "unable to set decoding format: %s" % _zstd_error(zresult) + ) + + if self._dict_data and load_dict: + zresult = lib.ZSTD_DCtx_refDDict(self._dctx, self._dict_data._ddict) + if lib.ZSTD_isError(zresult): + raise ZstdError( + "unable to reference prepared dictionary: %s" + % _zstd_error(zresult) + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard/py.typed b/micromamba_root/envs/pytorch_env/Lib/site-packages/zstandard/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391