Matt300209 commited on
Commit
0b6a987
·
verified ·
1 Parent(s): 582a013

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. requirements.txt +257 -0
  2. venv/lib/python3.10/site-packages/cpplint.py +0 -0
  3. venv/lib/python3.10/site-packages/cython.py +29 -0
  4. venv/lib/python3.10/site-packages/decorator.py +459 -0
  5. venv/lib/python3.10/site-packages/google_auth_httplib2.py +307 -0
  6. venv/lib/python3.10/site-packages/isympy.py +342 -0
  7. venv/lib/python3.10/site-packages/nest_asyncio.py +219 -0
  8. venv/lib/python3.10/site-packages/package_readme.md +97 -0
  9. venv/lib/python3.10/site-packages/pkg_resources/__init__.py +0 -0
  10. venv/lib/python3.10/site-packages/pkg_resources/_vendor/__init__.py +0 -0
  11. venv/lib/python3.10/site-packages/pkg_resources/_vendor/__pycache__/__init__.cpython-310.pyc +0 -0
  12. venv/lib/python3.10/site-packages/pkg_resources/_vendor/appdirs.py +608 -0
  13. venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/__about__.py +26 -0
  14. venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/__init__.py +25 -0
  15. venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/__pycache__/__about__.cpython-310.pyc +0 -0
  16. venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/__pycache__/_musllinux.cpython-310.pyc +0 -0
  17. venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/__pycache__/_structures.cpython-310.pyc +0 -0
  18. venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/__pycache__/markers.cpython-310.pyc +0 -0
  19. venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/__pycache__/requirements.cpython-310.pyc +0 -0
  20. venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/__pycache__/specifiers.cpython-310.pyc +0 -0
  21. venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/__pycache__/tags.cpython-310.pyc +0 -0
  22. venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/__pycache__/utils.cpython-310.pyc +0 -0
  23. venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/_manylinux.py +301 -0
  24. venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/_musllinux.py +136 -0
  25. venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/_structures.py +67 -0
  26. venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/requirements.py +146 -0
  27. venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/specifiers.py +828 -0
  28. venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/utils.py +136 -0
  29. venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/version.py +504 -0
  30. venv/lib/python3.10/site-packages/pkg_resources/_vendor/pyparsing.py +0 -0
  31. venv/lib/python3.10/site-packages/pkg_resources/extern/__init__.py +73 -0
  32. venv/lib/python3.10/site-packages/pkg_resources/extern/__pycache__/__init__.cpython-310.pyc +0 -0
  33. venv/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-source/__pycache__/setup.cpython-310.pyc +0 -0
  34. venv/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-source/setup.py +6 -0
  35. venv/lib/python3.10/site-packages/py.py +15 -0
  36. venv/lib/python3.10/site-packages/setuptools/__init__.py +242 -0
  37. venv/lib/python3.10/site-packages/setuptools/_deprecation_warning.py +7 -0
  38. venv/lib/python3.10/site-packages/setuptools/_imp.py +82 -0
  39. venv/lib/python3.10/site-packages/setuptools/archive_util.py +205 -0
  40. venv/lib/python3.10/site-packages/setuptools/build_meta.py +290 -0
  41. venv/lib/python3.10/site-packages/setuptools/cli-32.exe +0 -0
  42. venv/lib/python3.10/site-packages/setuptools/cli-64.exe +0 -0
  43. venv/lib/python3.10/site-packages/setuptools/cli.exe +0 -0
  44. venv/lib/python3.10/site-packages/setuptools/config.py +751 -0
  45. venv/lib/python3.10/site-packages/six.py +1003 -0
  46. venv/lib/python3.10/site-packages/sqlitedict.py +697 -0
  47. venv/lib/python3.10/site-packages/threadpoolctl.py +1292 -0
  48. venv/lib/python3.10/site-packages/typing_extensions.py +0 -0
  49. venv/pyvenv.cfg +3 -0
  50. venv/requirements.txt +23 -0
requirements.txt ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ absl-py==2.3.1
2
+ accelerate==1.10.0
3
+ ai2-olmo==0.2.1
4
+ aiohappyeyeballs==2.6.1
5
+ aiohttp==3.12.15
6
+ aiosignal==1.4.0
7
+ airportsdata==20250811
8
+ alpaca-eval==0.2.6
9
+ annotated-types==0.7.0
10
+ antlr4-python3-runtime==4.11.0
11
+ anyio==4.10.0
12
+ astor==0.8.1
13
+ async-timeout==5.0.1
14
+ attrs==25.3.0
15
+ beaker-gantry==3.0.0
16
+ beaker-py==2.4.7
17
+ bitsandbytes==0.43.1
18
+ blake3==1.0.5
19
+ boltons==25.0.0
20
+ boto3==1.34.113
21
+ botocore==1.34.162
22
+ cached_path==1.7.3
23
+ cachetools==5.5.2
24
+ certifi==2025.8.3
25
+ chardet==5.2.0
26
+ charset-normalizer==3.4.3
27
+ click==8.2.1
28
+ click-help-colors==0.9.4
29
+ click-option-group==0.5.7
30
+ cloudpickle==3.0.0
31
+ colorama==0.4.6
32
+ compressed-tensors==0.9.3
33
+ cupy-cuda12x==13.5.1
34
+ DataProperty==1.1.0
35
+ datasets==4.0.0
36
+ Deprecated==1.2.18
37
+ depyf==0.18.0
38
+ dill==0.3.8
39
+ diskcache==5.6.3
40
+ distro==1.9.0
41
+ dnspython==2.7.0
42
+ einops==0.7.0
43
+ email_validator==2.2.0
44
+ evaluate==0.4.5
45
+ exceptiongroup==1.3.0
46
+ face==24.0.0
47
+ fastapi==0.116.1
48
+ fastapi-cli==0.0.8
49
+ fastapi-cloud-cli==0.1.5
50
+ fastrlock==0.8.3
51
+ filelock==3.18.0
52
+ fire==0.7.0
53
+ frozenlist==1.7.0
54
+ fsspec==2023.5.0
55
+ ftfy==6.3.1
56
+ gguf==0.17.1
57
+ gitdb==4.0.12
58
+ GitPython==3.1.45
59
+ glom==24.11.0
60
+ google-api-core==2.25.1
61
+ google-api-python-client==2.178.0
62
+ google-auth==2.40.3
63
+ google-auth-httplib2==0.2.0
64
+ google-auth-oauthlib==1.2.2
65
+ google-cloud-core==2.4.3
66
+ google-cloud-storage==2.19.0
67
+ google-crc32c==1.7.1
68
+ google-resumable-media==2.7.2
69
+ googleapis-common-protos==1.70.0
70
+ gradio_client==1.11.0
71
+ grpcio==1.74.0
72
+ h11==0.16.0
73
+ hf-xet==1.1.7
74
+ httpcore==1.0.9
75
+ httplib2==0.22.0
76
+ httptools==0.6.4
77
+ httpx==0.28.1
78
+ huggingface-hub==0.34.4
79
+ idna==3.10
80
+ immutabledict==2.2.5
81
+ importlib_metadata==8.0.0
82
+ interegular==0.3.3
83
+ Jinja2==3.1.6
84
+ jiter==0.10.0
85
+ jmespath==1.0.1
86
+ joblib==1.5.1
87
+ jsonlines==4.0.0
88
+ jsonschema==4.25.0
89
+ jsonschema-specifications==2025.4.1
90
+ langdetect==1.0.9
91
+ lark==1.2.2
92
+ lightning-utilities==0.15.2
93
+ litellm==1.74.3
94
+ llguidance==0.7.30
95
+ llvmlite==0.44.0
96
+ lm-format-enforcer==0.10.12
97
+ lm_eval==0.4.3
98
+ logzio-python-handler==4.1.4
99
+ lxml==6.0.0
100
+ markdown-it-py==4.0.0
101
+ MarkupSafe==3.0.2
102
+ mbstrdecoder==1.1.4
103
+ mdurl==0.1.2
104
+ mistral_common==1.8.3
105
+ more-itertools==10.7.0
106
+ mpmath==1.3.0
107
+ msgpack==1.1.1
108
+ msgspec==0.19.0
109
+ multidict==6.6.4
110
+ multiprocess==0.70.16
111
+ necessary==0.4.3
112
+ nest-asyncio==1.6.0
113
+ networkx==3.4.2
114
+ ninja==1.13.0
115
+ nltk==3.9.1
116
+ numba==0.61.2
117
+ numexpr==2.11.0
118
+ numpy==2.2.6
119
+ nvidia-cublas-cu12==12.4.5.8
120
+ nvidia-cuda-cupti-cu12==12.4.127
121
+ nvidia-cuda-nvrtc-cu12==12.4.127
122
+ nvidia-cuda-runtime-cu12==12.4.127
123
+ nvidia-cudnn-cu12==9.1.0.70
124
+ nvidia-cufft-cu12==11.2.1.3
125
+ nvidia-cufile-cu12==1.13.1.3
126
+ nvidia-curand-cu12==10.3.5.147
127
+ nvidia-cusolver-cu12==11.6.1.9
128
+ nvidia-cusparse-cu12==12.3.1.170
129
+ nvidia-cusparselt-cu12==0.6.2
130
+ nvidia-nccl-cu12==2.21.5
131
+ nvidia-nvjitlink-cu12==12.4.127
132
+ nvidia-nvtx-cu12==12.4.127
133
+ oauthlib==3.3.1
134
+ omegaconf==2.4.0.dev3
135
+ openai==1.99.9
136
+ opencv-python-headless==4.12.0.88
137
+ opentelemetry-api==1.26.0
138
+ opentelemetry-exporter-otlp==1.26.0
139
+ opentelemetry-exporter-otlp-proto-common==1.26.0
140
+ opentelemetry-exporter-otlp-proto-grpc==1.26.0
141
+ opentelemetry-exporter-otlp-proto-http==1.26.0
142
+ opentelemetry-proto==1.26.0
143
+ opentelemetry-sdk==1.26.0
144
+ opentelemetry-semantic-conventions==0.47b0
145
+ opentelemetry-semantic-conventions-ai==0.4.12
146
+ outlines==0.1.11
147
+ outlines_core==0.1.26
148
+ packaging==25.0
149
+ pandas==2.3.1
150
+ partial-json-parser==0.2.1.1.post6
151
+ pathvalidate==3.3.1
152
+ patsy==1.0.1
153
+ peft==0.17.0
154
+ petname==2.6
155
+ pillow==11.3.0
156
+ pip==25.2
157
+ platformdirs==4.3.8
158
+ portalocker==3.2.0
159
+ prometheus-fastapi-instrumentator==7.1.0
160
+ prometheus_client==0.22.1
161
+ propcache==0.3.2
162
+ proto-plus==1.26.1
163
+ protobuf==4.25.8
164
+ psutil==7.0.0
165
+ py-cpuinfo==9.0.0
166
+ pyarrow==21.0.0
167
+ pyasn1==0.6.1
168
+ pyasn1_modules==0.4.2
169
+ pybind11==3.0.0
170
+ pycountry==24.6.1
171
+ pydantic==2.11.7
172
+ pydantic-extra-types==2.10.5
173
+ pydantic_core==2.33.2
174
+ Pygments==2.19.2
175
+ pygsheets==2.0.6
176
+ pyparsing==3.2.3
177
+ pytablewriter==1.2.1
178
+ python-dateutil==2.9.0.post0
179
+ python-dotenv==1.1.1
180
+ python-json-logger==3.3.0
181
+ python-multipart==0.0.20
182
+ pytrec-eval==0.5
183
+ pytz==2025.2
184
+ PyYAML==6.0.2
185
+ pyzmq==27.0.1
186
+ ray==2.48.0
187
+ referencing==0.36.2
188
+ regex==2025.7.34
189
+ requests==2.32.4
190
+ requests-oauthlib==2.0.0
191
+ requirements-parser==0.13.0
192
+ rich==13.9.4
193
+ rich-toolkit==0.15.0
194
+ rignore==0.6.4
195
+ rouge-score==0.1.2
196
+ rpds-py==0.27.0
197
+ rsa==4.9.1
198
+ s3transfer==0.10.4
199
+ sacrebleu==2.5.1
200
+ safetensors==0.6.2
201
+ scikit-learn==1.7.1
202
+ scipy==1.15.3
203
+ sentencepiece==0.2.1
204
+ sentry-sdk==2.34.1
205
+ setuptools==59.6.0
206
+ shellingham==1.5.4
207
+ six==1.17.0
208
+ smart-open==6.4.0
209
+ smashed==0.21.5
210
+ smmap==5.0.2
211
+ sniffio==1.3.1
212
+ sqlitedict==2.1.0
213
+ starlette==0.47.2
214
+ statsmodels==0.14.1
215
+ sympy==1.13.1
216
+ tabledata==1.3.4
217
+ tabulate==0.9.0
218
+ tcolorpy==0.1.7
219
+ tenacity==8.3.0
220
+ termcolor==3.1.0
221
+ threadpoolctl==3.6.0
222
+ tiktoken==0.11.0
223
+ tokenizers==0.21.4
224
+ torch==2.6.0
225
+ torchaudio==2.6.0
226
+ torchmetrics==1.8.1
227
+ torchvision==0.21.0
228
+ tqdm==4.67.1
229
+ tqdm-multiprocess==0.0.11
230
+ transformers==4.55.1
231
+ tree-sitter==0.24.0
232
+ tree-sitter-python==0.23.6
233
+ triton==3.2.0
234
+ trouting==0.3.3
235
+ typepy==1.3.4
236
+ typer==0.16.0
237
+ typing-inspection==0.4.1
238
+ typing_extensions==4.14.1
239
+ tzdata==2025.2
240
+ uritemplate==4.2.0
241
+ urllib3==2.5.0
242
+ uvicorn==0.35.0
243
+ uvloop==0.21.0
244
+ vllm==0.8.5
245
+ wandb==0.21.1
246
+ watchfiles==1.1.0
247
+ wcwidth==0.2.13
248
+ websockets==15.0.1
249
+ wheel==0.45.1
250
+ word2number==1.1
251
+ wrapt==1.17.3
252
+ xformers==0.0.29.post2
253
+ xgrammar==0.1.18
254
+ xxhash==3.5.0
255
+ yarl==1.20.1
256
+ zipp==3.23.0
257
+ zstandard==0.23.0
venv/lib/python3.10/site-packages/cpplint.py ADDED
The diff for this file is too large to render. See raw diff
 
venv/lib/python3.10/site-packages/cython.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ #
4
+ # Cython -- Main Program, generic
5
+ #
6
+
7
+ try:
8
+ from typing import TYPE_CHECKING
9
+ except ImportError:
10
+ TYPE_CHECKING = False
11
+
12
+ if not TYPE_CHECKING and __name__ == '__main__':
13
+
14
+ import os
15
+ import sys
16
+
17
+ # Make sure we import the right Cython
18
+ cythonpath, _ = os.path.split(os.path.realpath(__file__))
19
+ sys.path.insert(0, cythonpath)
20
+
21
+ from Cython.Compiler.Main import main
22
+ main(command_line = 1)
23
+
24
+ else:
25
+ # Void cython.* directives.
26
+ from Cython.Shadow import *
27
+ ## and bring in the __version__
28
+ from Cython import __version__
29
+ from Cython import load_ipython_extension
venv/lib/python3.10/site-packages/decorator.py ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ######################### LICENSE ############################ #
2
+
3
+ # Copyright (c) 2005-2025, Michele Simionato
4
+ # All rights reserved.
5
+
6
+ # Redistribution and use in source and binary forms, with or without
7
+ # modification, are permitted provided that the following conditions are
8
+ # met:
9
+
10
+ # Redistributions of source code must retain the above copyright
11
+ # notice, this list of conditions and the following disclaimer.
12
+ # Redistributions in bytecode form must reproduce the above copyright
13
+ # notice, this list of conditions and the following disclaimer in
14
+ # the documentation and/or other materials provided with the
15
+ # distribution.
16
+
17
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
+ # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
+ # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20
+ # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21
+ # HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22
+ # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23
+ # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
24
+ # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25
+ # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
26
+ # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
27
+ # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
28
+ # DAMAGE.
29
+
30
+ """
31
+ Decorator module, see
32
+ https://github.com/micheles/decorator/blob/master/docs/documentation.md
33
+ for the documentation.
34
+ """
35
+ import re
36
+ import sys
37
+ import inspect
38
+ import operator
39
+ import itertools
40
+ import functools
41
+ from contextlib import _GeneratorContextManager
42
+ from inspect import getfullargspec, iscoroutinefunction, isgeneratorfunction
43
+
44
+ __version__ = '5.2.1'
45
+
46
+ DEF = re.compile(r'\s*def\s*([_\w][_\w\d]*)\s*\(')
47
+ POS = inspect.Parameter.POSITIONAL_OR_KEYWORD
48
+ EMPTY = inspect.Parameter.empty
49
+
50
+
51
+ # this is not used anymore in the core, but kept for backward compatibility
52
+ class FunctionMaker(object):
53
+ """
54
+ An object with the ability to create functions with a given signature.
55
+ It has attributes name, doc, module, signature, defaults, dict and
56
+ methods update and make.
57
+ """
58
+
59
+ # Atomic get-and-increment provided by the GIL
60
+ _compile_count = itertools.count()
61
+
62
+ # make pylint happy
63
+ args = varargs = varkw = defaults = kwonlyargs = kwonlydefaults = ()
64
+
65
+ def __init__(self, func=None, name=None, signature=None,
66
+ defaults=None, doc=None, module=None, funcdict=None):
67
+ self.shortsignature = signature
68
+ if func:
69
+ # func can be a class or a callable, but not an instance method
70
+ self.name = func.__name__
71
+ if self.name == '<lambda>': # small hack for lambda functions
72
+ self.name = '_lambda_'
73
+ self.doc = func.__doc__
74
+ self.module = func.__module__
75
+ if inspect.isroutine(func) or isinstance(func, functools.partial):
76
+ argspec = getfullargspec(func)
77
+ self.annotations = getattr(func, '__annotations__', {})
78
+ for a in ('args', 'varargs', 'varkw', 'defaults', 'kwonlyargs',
79
+ 'kwonlydefaults'):
80
+ setattr(self, a, getattr(argspec, a))
81
+ for i, arg in enumerate(self.args):
82
+ setattr(self, 'arg%d' % i, arg)
83
+ allargs = list(self.args)
84
+ allshortargs = list(self.args)
85
+ if self.varargs:
86
+ allargs.append('*' + self.varargs)
87
+ allshortargs.append('*' + self.varargs)
88
+ elif self.kwonlyargs:
89
+ allargs.append('*') # single star syntax
90
+ for a in self.kwonlyargs:
91
+ allargs.append('%s=None' % a)
92
+ allshortargs.append('%s=%s' % (a, a))
93
+ if self.varkw:
94
+ allargs.append('**' + self.varkw)
95
+ allshortargs.append('**' + self.varkw)
96
+ self.signature = ', '.join(allargs)
97
+ self.shortsignature = ', '.join(allshortargs)
98
+ self.dict = func.__dict__.copy()
99
+ # func=None happens when decorating a caller
100
+ if name:
101
+ self.name = name
102
+ if signature is not None:
103
+ self.signature = signature
104
+ if defaults:
105
+ self.defaults = defaults
106
+ if doc:
107
+ self.doc = doc
108
+ if module:
109
+ self.module = module
110
+ if funcdict:
111
+ self.dict = funcdict
112
+ # check existence required attributes
113
+ assert hasattr(self, 'name')
114
+ if not hasattr(self, 'signature'):
115
+ raise TypeError('You are decorating a non function: %s' % func)
116
+
117
+ def update(self, func, **kw):
118
+ """
119
+ Update the signature of func with the data in self
120
+ """
121
+ func.__name__ = self.name
122
+ func.__doc__ = getattr(self, 'doc', None)
123
+ func.__dict__ = getattr(self, 'dict', {})
124
+ func.__defaults__ = self.defaults
125
+ func.__kwdefaults__ = self.kwonlydefaults or None
126
+ func.__annotations__ = getattr(self, 'annotations', None)
127
+ try:
128
+ frame = sys._getframe(3)
129
+ except AttributeError: # for IronPython and similar implementations
130
+ callermodule = '?'
131
+ else:
132
+ callermodule = frame.f_globals.get('__name__', '?')
133
+ func.__module__ = getattr(self, 'module', callermodule)
134
+ func.__dict__.update(kw)
135
+
136
+ def make(self, src_templ, evaldict=None, addsource=False, **attrs):
137
+ """
138
+ Make a new function from a given template and update the signature
139
+ """
140
+ src = src_templ % vars(self) # expand name and signature
141
+ evaldict = evaldict or {}
142
+ mo = DEF.search(src)
143
+ if mo is None:
144
+ raise SyntaxError('not a valid function template\n%s' % src)
145
+ name = mo.group(1) # extract the function name
146
+ names = set([name] + [arg.strip(' *') for arg in
147
+ self.shortsignature.split(',')])
148
+ for n in names:
149
+ if n in ('_func_', '_call_'):
150
+ raise NameError('%s is overridden in\n%s' % (n, src))
151
+
152
+ if not src.endswith('\n'): # add a newline for old Pythons
153
+ src += '\n'
154
+
155
+ # Ensure each generated function has a unique filename for profilers
156
+ # (such as cProfile) that depend on the tuple of (<filename>,
157
+ # <definition line>, <function name>) being unique.
158
+ filename = '<decorator-gen-%d>' % next(self._compile_count)
159
+ try:
160
+ code = compile(src, filename, 'single')
161
+ exec(code, evaldict)
162
+ except Exception:
163
+ print('Error in generated code:', file=sys.stderr)
164
+ print(src, file=sys.stderr)
165
+ raise
166
+ func = evaldict[name]
167
+ if addsource:
168
+ attrs['__source__'] = src
169
+ self.update(func, **attrs)
170
+ return func
171
+
172
+ @classmethod
173
+ def create(cls, obj, body, evaldict, defaults=None,
174
+ doc=None, module=None, addsource=True, **attrs):
175
+ """
176
+ Create a function from the strings name, signature and body.
177
+ evaldict is the evaluation dictionary. If addsource is true an
178
+ attribute __source__ is added to the result. The attributes attrs
179
+ are added, if any.
180
+ """
181
+ if isinstance(obj, str): # "name(signature)"
182
+ name, rest = obj.strip().split('(', 1)
183
+ signature = rest[:-1] # strip a right parens
184
+ func = None
185
+ else: # a function
186
+ name = None
187
+ signature = None
188
+ func = obj
189
+ self = cls(func, name, signature, defaults, doc, module)
190
+ ibody = '\n'.join(' ' + line for line in body.splitlines())
191
+ caller = evaldict.get('_call_') # when called from `decorate`
192
+ if caller and iscoroutinefunction(caller):
193
+ body = ('async def %(name)s(%(signature)s):\n' + ibody).replace(
194
+ 'return', 'return await')
195
+ else:
196
+ body = 'def %(name)s(%(signature)s):\n' + ibody
197
+ return self.make(body, evaldict, addsource, **attrs)
198
+
199
+
200
+ def fix(args, kwargs, sig):
201
+ """
202
+ Fix args and kwargs to be consistent with the signature
203
+ """
204
+ ba = sig.bind(*args, **kwargs)
205
+ ba.apply_defaults() # needed for test_dan_schult
206
+ return ba.args, ba.kwargs
207
+
208
+
209
+ def decorate(func, caller, extras=(), kwsyntax=False):
210
+ """
211
+ Decorates a function/generator/coroutine using a caller.
212
+ If kwsyntax is True calling the decorated functions with keyword
213
+ syntax will pass the named arguments inside the ``kw`` dictionary,
214
+ even if such argument are positional, similarly to what functools.wraps
215
+ does. By default kwsyntax is False and the the arguments are untouched.
216
+ """
217
+ sig = inspect.signature(func)
218
+ if isinstance(func, functools.partial):
219
+ func = functools.update_wrapper(func, func.func)
220
+ if iscoroutinefunction(caller):
221
+ async def fun(*args, **kw):
222
+ if not kwsyntax:
223
+ args, kw = fix(args, kw, sig)
224
+ return await caller(func, *(extras + args), **kw)
225
+ elif isgeneratorfunction(caller):
226
+ def fun(*args, **kw):
227
+ if not kwsyntax:
228
+ args, kw = fix(args, kw, sig)
229
+ for res in caller(func, *(extras + args), **kw):
230
+ yield res
231
+ else:
232
+ def fun(*args, **kw):
233
+ if not kwsyntax:
234
+ args, kw = fix(args, kw, sig)
235
+ return caller(func, *(extras + args), **kw)
236
+
237
+ fun.__name__ = func.__name__
238
+ fun.__doc__ = func.__doc__
239
+ fun.__wrapped__ = func
240
+ fun.__signature__ = sig
241
+ fun.__qualname__ = func.__qualname__
242
+ # builtin functions like defaultdict.__setitem__ lack many attributes
243
+ try:
244
+ fun.__defaults__ = func.__defaults__
245
+ except AttributeError:
246
+ pass
247
+ try:
248
+ fun.__kwdefaults__ = func.__kwdefaults__
249
+ except AttributeError:
250
+ pass
251
+ try:
252
+ fun.__annotations__ = func.__annotations__
253
+ except AttributeError:
254
+ pass
255
+ try:
256
+ fun.__module__ = func.__module__
257
+ except AttributeError:
258
+ pass
259
+ try:
260
+ fun.__name__ = func.__name__
261
+ except AttributeError: # happens with old versions of numpy.vectorize
262
+ func.__name__ == 'noname'
263
+ try:
264
+ fun.__dict__.update(func.__dict__)
265
+ except AttributeError:
266
+ pass
267
+ return fun
268
+
269
+
270
+ def decoratorx(caller):
271
+ """
272
+ A version of "decorator" implemented via "exec" and not via the
273
+ Signature object. Use this if you are want to preserve the `.__code__`
274
+ object properties (https://github.com/micheles/decorator/issues/129).
275
+ """
276
+ def dec(func):
277
+ return FunctionMaker.create(
278
+ func,
279
+ "return _call_(_func_, %(shortsignature)s)",
280
+ dict(_call_=caller, _func_=func),
281
+ __wrapped__=func, __qualname__=func.__qualname__)
282
+ return dec
283
+
284
+
285
+ def decorator(caller, _func=None, kwsyntax=False):
286
+ """
287
+ decorator(caller) converts a caller function into a decorator
288
+ """
289
+ if _func is not None: # return a decorated function
290
+ # this is obsolete behavior; you should use decorate instead
291
+ return decorate(_func, caller, (), kwsyntax)
292
+ # else return a decorator function
293
+ sig = inspect.signature(caller)
294
+ dec_params = [p for p in sig.parameters.values() if p.kind is POS]
295
+
296
+ def dec(func=None, *args, **kw):
297
+ na = len(args) + 1
298
+ extras = args + tuple(kw.get(p.name, p.default)
299
+ for p in dec_params[na:]
300
+ if p.default is not EMPTY)
301
+ if func is None:
302
+ return lambda func: decorate(func, caller, extras, kwsyntax)
303
+ else:
304
+ return decorate(func, caller, extras, kwsyntax)
305
+ dec.__signature__ = sig.replace(parameters=dec_params)
306
+ dec.__name__ = caller.__name__
307
+ dec.__doc__ = caller.__doc__
308
+ dec.__wrapped__ = caller
309
+ dec.__qualname__ = caller.__qualname__
310
+ dec.__kwdefaults__ = getattr(caller, '__kwdefaults__', None)
311
+ dec.__dict__.update(caller.__dict__)
312
+ return dec
313
+
314
+
315
+ # ####################### contextmanager ####################### #
316
+
317
+
318
+ class ContextManager(_GeneratorContextManager):
319
+ def __init__(self, g, *a, **k):
320
+ _GeneratorContextManager.__init__(self, g, a, k)
321
+
322
+ def __call__(self, func):
323
+ def caller(f, *a, **k):
324
+ with self.__class__(self.func, *self.args, **self.kwds):
325
+ return f(*a, **k)
326
+ return decorate(func, caller)
327
+
328
+
329
+ _contextmanager = decorator(ContextManager)
330
+
331
+
332
+ def contextmanager(func):
333
+ # Enable Pylint config: contextmanager-decorators=decorator.contextmanager
334
+ return _contextmanager(func)
335
+
336
+
337
+ # ############################ dispatch_on ############################ #
338
+
339
+ def append(a, vancestors):
340
+ """
341
+ Append ``a`` to the list of the virtual ancestors, unless it is already
342
+ included.
343
+ """
344
+ add = True
345
+ for j, va in enumerate(vancestors):
346
+ if issubclass(va, a):
347
+ add = False
348
+ break
349
+ if issubclass(a, va):
350
+ vancestors[j] = a
351
+ add = False
352
+ if add:
353
+ vancestors.append(a)
354
+
355
+
356
+ # inspired from simplegeneric by P.J. Eby and functools.singledispatch
357
+ def dispatch_on(*dispatch_args):
358
+ """
359
+ Factory of decorators turning a function into a generic function
360
+ dispatching on the given arguments.
361
+ """
362
+ assert dispatch_args, 'No dispatch args passed'
363
+ dispatch_str = '(%s,)' % ', '.join(dispatch_args)
364
+
365
+ def check(arguments, wrong=operator.ne, msg=''):
366
+ """Make sure one passes the expected number of arguments"""
367
+ if wrong(len(arguments), len(dispatch_args)):
368
+ raise TypeError('Expected %d arguments, got %d%s' %
369
+ (len(dispatch_args), len(arguments), msg))
370
+
371
+ def gen_func_dec(func):
372
+ """Decorator turning a function into a generic function"""
373
+
374
+ # first check the dispatch arguments
375
+ argset = set(getfullargspec(func).args)
376
+ if not set(dispatch_args) <= argset:
377
+ raise NameError('Unknown dispatch arguments %s' % dispatch_str)
378
+
379
+ typemap = {}
380
+
381
+ def vancestors(*types):
382
+ """
383
+ Get a list of sets of virtual ancestors for the given types
384
+ """
385
+ check(types)
386
+ ras = [[] for _ in range(len(dispatch_args))]
387
+ for types_ in typemap:
388
+ for t, type_, ra in zip(types, types_, ras):
389
+ if issubclass(t, type_) and type_ not in t.mro():
390
+ append(type_, ra)
391
+ return [set(ra) for ra in ras]
392
+
393
+ def ancestors(*types):
394
+ """
395
+ Get a list of virtual MROs, one for each type
396
+ """
397
+ check(types)
398
+ lists = []
399
+ for t, vas in zip(types, vancestors(*types)):
400
+ n_vas = len(vas)
401
+ if n_vas > 1:
402
+ raise RuntimeError(
403
+ 'Ambiguous dispatch for %s: %s' % (t, vas))
404
+ elif n_vas == 1:
405
+ va, = vas
406
+ mro = type('t', (t, va), {}).mro()[1:]
407
+ else:
408
+ mro = t.mro()
409
+ lists.append(mro[:-1]) # discard t and object
410
+ return lists
411
+
412
+ def register(*types):
413
+ """
414
+ Decorator to register an implementation for the given types
415
+ """
416
+ check(types)
417
+
418
+ def dec(f):
419
+ check(getfullargspec(f).args, operator.lt, ' in ' + f.__name__)
420
+ typemap[types] = f
421
+ return f
422
+ return dec
423
+
424
+ def dispatch_info(*types):
425
+ """
426
+ An utility to introspect the dispatch algorithm
427
+ """
428
+ check(types)
429
+ lst = []
430
+ for ancs in itertools.product(*ancestors(*types)):
431
+ lst.append(tuple(a.__name__ for a in ancs))
432
+ return lst
433
+
434
+ def _dispatch(dispatch_args, *args, **kw):
435
+ types = tuple(type(arg) for arg in dispatch_args)
436
+ try: # fast path
437
+ f = typemap[types]
438
+ except KeyError:
439
+ pass
440
+ else:
441
+ return f(*args, **kw)
442
+ combinations = itertools.product(*ancestors(*types))
443
+ next(combinations) # the first one has been already tried
444
+ for types_ in combinations:
445
+ f = typemap.get(types_)
446
+ if f is not None:
447
+ return f(*args, **kw)
448
+
449
+ # else call the default implementation
450
+ return func(*args, **kw)
451
+
452
+ return FunctionMaker.create(
453
+ func, 'return _f_(%s, %%(shortsignature)s)' % dispatch_str,
454
+ dict(_f_=_dispatch), register=register, default=func,
455
+ typemap=typemap, vancestors=vancestors, ancestors=ancestors,
456
+ dispatch_info=dispatch_info, __wrapped__=func)
457
+
458
+ gen_func_dec.__name__ = 'dispatch_on' + dispatch_str
459
+ return gen_func_dec
venv/lib/python3.10/site-packages/google_auth_httplib2.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 Google Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Transport adapter for httplib2."""
16
+
17
+ from __future__ import absolute_import
18
+
19
+ import http.client
20
+ import logging
21
+
22
+ from google.auth import exceptions
23
+ from google.auth import transport
24
+ import httplib2
25
+
26
+
27
+ _LOGGER = logging.getLogger(__name__)
28
+ # Properties present in file-like streams / buffers.
29
+ _STREAM_PROPERTIES = ("read", "seek", "tell")
30
+
31
+
32
+ class _Response(transport.Response):
33
+ """httplib2 transport response adapter.
34
+
35
+ Args:
36
+ response (httplib2.Response): The raw httplib2 response.
37
+ data (bytes): The response body.
38
+ """
39
+
40
+ def __init__(self, response, data):
41
+ self._response = response
42
+ self._data = data
43
+
44
+ @property
45
+ def status(self):
46
+ """int: The HTTP status code."""
47
+ return self._response.status
48
+
49
+ @property
50
+ def headers(self):
51
+ """Mapping[str, str]: The HTTP response headers."""
52
+ return dict(self._response)
53
+
54
+ @property
55
+ def data(self):
56
+ """bytes: The response body."""
57
+ return self._data
58
+
59
+
60
+ class Request(transport.Request):
61
+ """httplib2 request adapter.
62
+
63
+ This class is used internally for making requests using various transports
64
+ in a consistent way. If you use :class:`AuthorizedHttp` you do not need
65
+ to construct or use this class directly.
66
+
67
+ This class can be useful if you want to manually refresh a
68
+ :class:`~google.auth.credentials.Credentials` instance::
69
+
70
+ import google_auth_httplib2
71
+ import httplib2
72
+
73
+ http = httplib2.Http()
74
+ request = google_auth_httplib2.Request(http)
75
+
76
+ credentials.refresh(request)
77
+
78
+ Args:
79
+ http (httplib2.Http): The underlying http object to use to make
80
+ requests.
81
+
82
+ .. automethod:: __call__
83
+ """
84
+
85
+ def __init__(self, http):
86
+ self.http = http
87
+
88
+ def __call__(
89
+ self, url, method="GET", body=None, headers=None, timeout=None, **kwargs
90
+ ):
91
+ """Make an HTTP request using httplib2.
92
+
93
+ Args:
94
+ url (str): The URI to be requested.
95
+ method (str): The HTTP method to use for the request. Defaults
96
+ to 'GET'.
97
+ body (bytes): The payload / body in HTTP request.
98
+ headers (Mapping[str, str]): Request headers.
99
+ timeout (Optional[int]): The number of seconds to wait for a
100
+ response from the server. This is ignored by httplib2 and will
101
+ issue a warning.
102
+ kwargs: Additional arguments passed throught to the underlying
103
+ :meth:`httplib2.Http.request` method.
104
+
105
+ Returns:
106
+ google.auth.transport.Response: The HTTP response.
107
+
108
+ Raises:
109
+ google.auth.exceptions.TransportError: If any exception occurred.
110
+ """
111
+ if timeout is not None:
112
+ _LOGGER.warning(
113
+ "httplib2 transport does not support per-request timeout. "
114
+ "Set the timeout when constructing the httplib2.Http instance."
115
+ )
116
+
117
+ try:
118
+ _LOGGER.debug("Making request: %s %s", method, url)
119
+ response, data = self.http.request(
120
+ url, method=method, body=body, headers=headers, **kwargs
121
+ )
122
+ return _Response(response, data)
123
+ # httplib2 should catch the lower http error, this is a bug and
124
+ # needs to be fixed there. Catch the error for the meanwhile.
125
+ except (httplib2.HttpLib2Error, http.client.HTTPException) as exc:
126
+ raise exceptions.TransportError(exc)
127
+
128
+
129
+ def _make_default_http():
130
+ """Returns a default httplib2.Http instance."""
131
+ return httplib2.Http()
132
+
133
+
134
+ class AuthorizedHttp(object):
135
+ """A httplib2 HTTP class with credentials.
136
+
137
+ This class is used to perform requests to API endpoints that require
138
+ authorization::
139
+
140
+ from google.auth.transport._httplib2 import AuthorizedHttp
141
+
142
+ authed_http = AuthorizedHttp(credentials)
143
+
144
+ response = authed_http.request(
145
+ 'https://www.googleapis.com/storage/v1/b')
146
+
147
+ This class implements :meth:`request` in the same way as
148
+ :class:`httplib2.Http` and can usually be used just like any other
149
+ instance of :class:``httplib2.Http`.
150
+
151
+ The underlying :meth:`request` implementation handles adding the
152
+ credentials' headers to the request and refreshing credentials as needed.
153
+ """
154
+
155
+ def __init__(
156
+ self,
157
+ credentials,
158
+ http=None,
159
+ refresh_status_codes=transport.DEFAULT_REFRESH_STATUS_CODES,
160
+ max_refresh_attempts=transport.DEFAULT_MAX_REFRESH_ATTEMPTS,
161
+ ):
162
+ """
163
+ Args:
164
+ credentials (google.auth.credentials.Credentials): The credentials
165
+ to add to the request.
166
+ http (httplib2.Http): The underlying HTTP object to
167
+ use to make requests. If not specified, a
168
+ :class:`httplib2.Http` instance will be constructed.
169
+ refresh_status_codes (Sequence[int]): Which HTTP status codes
170
+ indicate that credentials should be refreshed and the request
171
+ should be retried.
172
+ max_refresh_attempts (int): The maximum number of times to attempt
173
+ to refresh the credentials and retry the request.
174
+ """
175
+
176
+ if http is None:
177
+ http = _make_default_http()
178
+
179
+ self.http = http
180
+ self.credentials = credentials
181
+ self._refresh_status_codes = refresh_status_codes
182
+ self._max_refresh_attempts = max_refresh_attempts
183
+ # Request instance used by internal methods (for example,
184
+ # credentials.refresh).
185
+ self._request = Request(self.http)
186
+
187
+ def close(self):
188
+ """Calls httplib2's Http.close"""
189
+ self.http.close()
190
+
191
+ def request(
192
+ self,
193
+ uri,
194
+ method="GET",
195
+ body=None,
196
+ headers=None,
197
+ redirections=httplib2.DEFAULT_MAX_REDIRECTS,
198
+ connection_type=None,
199
+ **kwargs
200
+ ):
201
+ """Implementation of httplib2's Http.request."""
202
+
203
+ _credential_refresh_attempt = kwargs.pop("_credential_refresh_attempt", 0)
204
+
205
+ # Make a copy of the headers. They will be modified by the credentials
206
+ # and we want to pass the original headers if we recurse.
207
+ request_headers = headers.copy() if headers is not None else {}
208
+
209
+ self.credentials.before_request(self._request, method, uri, request_headers)
210
+
211
+ # Check if the body is a file-like stream, and if so, save the body
212
+ # stream position so that it can be restored in case of refresh.
213
+ body_stream_position = None
214
+ if all(getattr(body, stream_prop, None) for stream_prop in _STREAM_PROPERTIES):
215
+ body_stream_position = body.tell()
216
+
217
+ # Make the request.
218
+ response, content = self.http.request(
219
+ uri,
220
+ method,
221
+ body=body,
222
+ headers=request_headers,
223
+ redirections=redirections,
224
+ connection_type=connection_type,
225
+ **kwargs
226
+ )
227
+
228
+ # If the response indicated that the credentials needed to be
229
+ # refreshed, then refresh the credentials and re-attempt the
230
+ # request.
231
+ # A stored token may expire between the time it is retrieved and
232
+ # the time the request is made, so we may need to try twice.
233
+ if (
234
+ response.status in self._refresh_status_codes
235
+ and _credential_refresh_attempt < self._max_refresh_attempts
236
+ ):
237
+
238
+ _LOGGER.info(
239
+ "Refreshing credentials due to a %s response. Attempt %s/%s.",
240
+ response.status,
241
+ _credential_refresh_attempt + 1,
242
+ self._max_refresh_attempts,
243
+ )
244
+
245
+ self.credentials.refresh(self._request)
246
+
247
+ # Restore the body's stream position if needed.
248
+ if body_stream_position is not None:
249
+ body.seek(body_stream_position)
250
+
251
+ # Recurse. Pass in the original headers, not our modified set.
252
+ return self.request(
253
+ uri,
254
+ method,
255
+ body=body,
256
+ headers=headers,
257
+ redirections=redirections,
258
+ connection_type=connection_type,
259
+ _credential_refresh_attempt=_credential_refresh_attempt + 1,
260
+ **kwargs
261
+ )
262
+
263
+ return response, content
264
+
265
+ def add_certificate(self, key, cert, domain, password=None):
266
+ """Proxy to httplib2.Http.add_certificate."""
267
+ self.http.add_certificate(key, cert, domain, password=password)
268
+
269
+ @property
270
+ def connections(self):
271
+ """Proxy to httplib2.Http.connections."""
272
+ return self.http.connections
273
+
274
+ @connections.setter
275
+ def connections(self, value):
276
+ """Proxy to httplib2.Http.connections."""
277
+ self.http.connections = value
278
+
279
+ @property
280
+ def follow_redirects(self):
281
+ """Proxy to httplib2.Http.follow_redirects."""
282
+ return self.http.follow_redirects
283
+
284
+ @follow_redirects.setter
285
+ def follow_redirects(self, value):
286
+ """Proxy to httplib2.Http.follow_redirects."""
287
+ self.http.follow_redirects = value
288
+
289
+ @property
290
+ def timeout(self):
291
+ """Proxy to httplib2.Http.timeout."""
292
+ return self.http.timeout
293
+
294
+ @timeout.setter
295
+ def timeout(self, value):
296
+ """Proxy to httplib2.Http.timeout."""
297
+ self.http.timeout = value
298
+
299
+ @property
300
+ def redirect_codes(self):
301
+ """Proxy to httplib2.Http.redirect_codes."""
302
+ return self.http.redirect_codes
303
+
304
+ @redirect_codes.setter
305
+ def redirect_codes(self, value):
306
+ """Proxy to httplib2.Http.redirect_codes."""
307
+ self.http.redirect_codes = value
venv/lib/python3.10/site-packages/isympy.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Python shell for SymPy.
3
+
4
+ This is just a normal Python shell (IPython shell if you have the
5
+ IPython package installed), that executes the following commands for
6
+ the user:
7
+
8
+ >>> from __future__ import division
9
+ >>> from sympy import *
10
+ >>> x, y, z, t = symbols('x y z t')
11
+ >>> k, m, n = symbols('k m n', integer=True)
12
+ >>> f, g, h = symbols('f g h', cls=Function)
13
+ >>> init_printing()
14
+
15
+ So starting 'isympy' is equivalent to starting Python (or IPython) and
16
+ executing the above commands by hand. It is intended for easy and quick
17
+ experimentation with SymPy. isympy is a good way to use SymPy as an
18
+ interactive calculator. If you have IPython and Matplotlib installed, then
19
+ interactive plotting is enabled by default.
20
+
21
+ COMMAND LINE OPTIONS
22
+ --------------------
23
+
24
+ -c CONSOLE, --console=CONSOLE
25
+
26
+ Use the specified shell (Python or IPython) shell as the console
27
+ backend instead of the default one (IPython if present, Python
28
+ otherwise), e.g.:
29
+
30
+ $isympy -c python
31
+
32
+ CONSOLE must be one of 'ipython' or 'python'
33
+
34
+ -p PRETTY, --pretty PRETTY
35
+
36
+ Setup pretty-printing in SymPy. When pretty-printing is enabled,
37
+ expressions can be printed with Unicode or ASCII. The default is
38
+ to use pretty-printing (with Unicode if the terminal supports it).
39
+ When this option is 'no', expressions will not be pretty-printed
40
+ and ASCII will be used:
41
+
42
+ $isympy -p no
43
+
44
+ PRETTY must be one of 'unicode', 'ascii', or 'no'
45
+
46
+ -t TYPES, --types=TYPES
47
+
48
+ Setup the ground types for the polys. By default, gmpy ground types
49
+ are used if gmpy2 or gmpy is installed, otherwise it falls back to python
50
+ ground types, which are a little bit slower. You can manually
51
+ choose python ground types even if gmpy is installed (e.g., for
52
+ testing purposes):
53
+
54
+ $isympy -t python
55
+
56
+ TYPES must be one of 'gmpy', 'gmpy1' or 'python'
57
+
58
+ Note that the ground type gmpy1 is primarily intended for testing; it
59
+ forces the use of gmpy version 1 even if gmpy2 is available.
60
+
61
+ This is the same as setting the environment variable
62
+ SYMPY_GROUND_TYPES to the given ground type (e.g.,
63
+ SYMPY_GROUND_TYPES='gmpy')
64
+
65
+ The ground types can be determined interactively from the variable
66
+ sympy.polys.domains.GROUND_TYPES.
67
+
68
+ -o ORDER, --order ORDER
69
+
70
+ Setup the ordering of terms for printing. The default is lex, which
71
+ orders terms lexicographically (e.g., x**2 + x + 1). You can choose
72
+ other orderings, such as rev-lex, which will use reverse
73
+ lexicographic ordering (e.g., 1 + x + x**2):
74
+
75
+ $isympy -o rev-lex
76
+
77
+ ORDER must be one of 'lex', 'rev-lex', 'grlex', 'rev-grlex',
78
+ 'grevlex', 'rev-grevlex', 'old', or 'none'.
79
+
80
+ Note that for very large expressions, ORDER='none' may speed up
81
+ printing considerably but the terms will have no canonical order.
82
+
83
+ -q, --quiet
84
+
85
+ Print only Python's and SymPy's versions to stdout at startup.
86
+
87
+ -d, --doctest
88
+
89
+ Use the same format that should be used for doctests. This is
90
+ equivalent to -c python -p no.
91
+
92
+ -C, --no-cache
93
+
94
+ Disable the caching mechanism. Disabling the cache may slow certain
95
+ operations down considerably. This is useful for testing the cache,
96
+ or for benchmarking, as the cache can result in deceptive timings.
97
+
98
+ This is equivalent to setting the environment variable
99
+ SYMPY_USE_CACHE to 'no'.
100
+
101
+ -a, --auto-symbols (requires at least IPython 0.11)
102
+
103
+ Automatically create missing symbols. Normally, typing a name of a
104
+ Symbol that has not been instantiated first would raise NameError,
105
+ but with this option enabled, any undefined name will be
106
+ automatically created as a Symbol.
107
+
108
+ Note that this is intended only for interactive, calculator style
109
+ usage. In a script that uses SymPy, Symbols should be instantiated
110
+ at the top, so that it's clear what they are.
111
+
112
+ This will not override any names that are already defined, which
113
+ includes the single character letters represented by the mnemonic
114
+ QCOSINE (see the "Gotchas and Pitfalls" document in the
115
+ documentation). You can delete existing names by executing "del
116
+ name". If a name is defined, typing "'name' in dir()" will return True.
117
+
118
+ The Symbols that are created using this have default assumptions.
119
+ If you want to place assumptions on symbols, you should create them
120
+ using symbols() or var().
121
+
122
+ Finally, this only works in the top level namespace. So, for
123
+ example, if you define a function in isympy with an undefined
124
+ Symbol, it will not work.
125
+
126
+ See also the -i and -I options.
127
+
128
+ -i, --int-to-Integer (requires at least IPython 0.11)
129
+
130
+ Automatically wrap int literals with Integer. This makes it so that
131
+ things like 1/2 will come out as Rational(1, 2), rather than 0.5. This
132
+ works by preprocessing the source and wrapping all int literals with
133
+ Integer. Note that this will not change the behavior of int literals
134
+ assigned to variables, and it also won't change the behavior of functions
135
+ that return int literals.
136
+
137
+ If you want an int, you can wrap the literal in int(), e.g. int(3)/int(2)
138
+ gives 1.5 (with division imported from __future__).
139
+
140
+ -I, --interactive (requires at least IPython 0.11)
141
+
142
+ This is equivalent to --auto-symbols --int-to-Integer. Future options
143
+ designed for ease of interactive use may be added to this.
144
+
145
+ -D, --debug
146
+
147
+ Enable debugging output. This is the same as setting the
148
+ environment variable SYMPY_DEBUG to 'True'. The debug status is set
149
+ in the variable SYMPY_DEBUG within isympy.
150
+
151
+ -- IPython options
152
+
153
+ Additionally you can pass command line options directly to the IPython
154
+ interpreter (the standard Python shell is not supported). However you
155
+ need to add the '--' separator between two types of options, e.g the
156
+ startup banner option and the colors option. You need to enter the
157
+ options as required by the version of IPython that you are using, too:
158
+
159
+ in IPython 0.11,
160
+
161
+ $isympy -q -- --colors=NoColor
162
+
163
+ or older versions of IPython,
164
+
165
+ $isympy -q -- -colors NoColor
166
+
167
+ See also isympy --help.
168
+ """
169
+
170
+ import os
171
+ import sys
172
+
173
+ # DO NOT IMPORT SYMPY HERE! Or the setting of the sympy environment variables
174
+ # by the command line will break.
175
+
176
+ def main() -> None:
177
+ from argparse import ArgumentParser, RawDescriptionHelpFormatter
178
+
179
+ VERSION = None
180
+ if '--version' in sys.argv:
181
+ # We cannot import sympy before this is run, because flags like -C and
182
+ # -t set environment variables that must be set before SymPy is
183
+ # imported. The only thing we need to import it for is to get the
184
+ # version, which only matters with the --version flag.
185
+ import sympy
186
+ VERSION = sympy.__version__
187
+
188
+ usage = 'isympy [options] -- [ipython options]'
189
+ parser = ArgumentParser(
190
+ usage=usage,
191
+ description=__doc__,
192
+ formatter_class=RawDescriptionHelpFormatter,
193
+ )
194
+
195
+ parser.add_argument('--version', action='version', version=VERSION)
196
+
197
+ parser.add_argument(
198
+ '-c', '--console',
199
+ dest='console',
200
+ action='store',
201
+ default=None,
202
+ choices=['ipython', 'python'],
203
+ metavar='CONSOLE',
204
+ help='select type of interactive session: ipython | python; defaults '
205
+ 'to ipython if IPython is installed, otherwise python')
206
+
207
+ parser.add_argument(
208
+ '-p', '--pretty',
209
+ dest='pretty',
210
+ action='store',
211
+ default=None,
212
+ metavar='PRETTY',
213
+ choices=['unicode', 'ascii', 'no'],
214
+ help='setup pretty printing: unicode | ascii | no; defaults to '
215
+ 'unicode printing if the terminal supports it, otherwise ascii')
216
+
217
+ parser.add_argument(
218
+ '-t', '--types',
219
+ dest='types',
220
+ action='store',
221
+ default=None,
222
+ metavar='TYPES',
223
+ choices=['gmpy', 'gmpy1', 'python'],
224
+ help='setup ground types: gmpy | gmpy1 | python; defaults to gmpy if gmpy2 '
225
+ 'or gmpy is installed, otherwise python')
226
+
227
+ parser.add_argument(
228
+ '-o', '--order',
229
+ dest='order',
230
+ action='store',
231
+ default=None,
232
+ metavar='ORDER',
233
+ choices=['lex', 'grlex', 'grevlex', 'rev-lex', 'rev-grlex', 'rev-grevlex', 'old', 'none'],
234
+ help='setup ordering of terms: [rev-]lex | [rev-]grlex | [rev-]grevlex | old | none; defaults to lex')
235
+
236
+ parser.add_argument(
237
+ '-q', '--quiet',
238
+ dest='quiet',
239
+ action='store_true',
240
+ default=False,
241
+ help='print only version information at startup')
242
+
243
+ parser.add_argument(
244
+ '-d', '--doctest',
245
+ dest='doctest',
246
+ action='store_true',
247
+ default=False,
248
+ help='use the doctest format for output (you can just copy and paste it)')
249
+
250
+ parser.add_argument(
251
+ '-C', '--no-cache',
252
+ dest='cache',
253
+ action='store_false',
254
+ default=True,
255
+ help='disable caching mechanism')
256
+
257
+ parser.add_argument(
258
+ '-a', '--auto-symbols',
259
+ dest='auto_symbols',
260
+ action='store_true',
261
+ default=False,
262
+ help='automatically construct missing symbols')
263
+
264
+ parser.add_argument(
265
+ '-i', '--int-to-Integer',
266
+ dest='auto_int_to_Integer',
267
+ action='store_true',
268
+ default=False,
269
+ help="automatically wrap int literals with Integer")
270
+
271
+ parser.add_argument(
272
+ '-I', '--interactive',
273
+ dest='interactive',
274
+ action='store_true',
275
+ default=False,
276
+ help="equivalent to -a -i")
277
+
278
+ parser.add_argument(
279
+ '-D', '--debug',
280
+ dest='debug',
281
+ action='store_true',
282
+ default=False,
283
+ help='enable debugging output')
284
+
285
+ (options, ipy_args) = parser.parse_known_args()
286
+ if '--' in ipy_args:
287
+ ipy_args.remove('--')
288
+
289
+ if not options.cache:
290
+ os.environ['SYMPY_USE_CACHE'] = 'no'
291
+
292
+ if options.types:
293
+ os.environ['SYMPY_GROUND_TYPES'] = options.types
294
+
295
+ if options.debug:
296
+ os.environ['SYMPY_DEBUG'] = str(options.debug)
297
+
298
+ if options.doctest:
299
+ options.pretty = 'no'
300
+ options.console = 'python'
301
+
302
+ session = options.console
303
+
304
+ if session is not None:
305
+ ipython = session == 'ipython'
306
+ else:
307
+ try:
308
+ import IPython
309
+ ipython = True
310
+ except ImportError:
311
+ if not options.quiet:
312
+ from sympy.interactive.session import no_ipython
313
+ print(no_ipython)
314
+ ipython = False
315
+
316
+ args = {
317
+ 'pretty_print': True,
318
+ 'use_unicode': None,
319
+ 'use_latex': None,
320
+ 'order': None,
321
+ 'argv': ipy_args,
322
+ }
323
+
324
+ if options.pretty == 'unicode':
325
+ args['use_unicode'] = True
326
+ elif options.pretty == 'ascii':
327
+ args['use_unicode'] = False
328
+ elif options.pretty == 'no':
329
+ args['pretty_print'] = False
330
+
331
+ if options.order is not None:
332
+ args['order'] = options.order
333
+
334
+ args['quiet'] = options.quiet
335
+ args['auto_symbols'] = options.auto_symbols or options.interactive
336
+ args['auto_int_to_Integer'] = options.auto_int_to_Integer or options.interactive
337
+
338
+ from sympy.interactive import init_session
339
+ init_session(ipython, **args)
340
+
341
+ if __name__ == "__main__":
342
+ main()
venv/lib/python3.10/site-packages/nest_asyncio.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Patch asyncio to allow nested event loops."""
2
+
3
+ import asyncio
4
+ import asyncio.events as events
5
+ import os
6
+ import sys
7
+ import threading
8
+ from contextlib import contextmanager, suppress
9
+ from heapq import heappop
10
+
11
+
12
+ def apply(loop=None):
13
+ """Patch asyncio to make its event loop reentrant."""
14
+ _patch_asyncio()
15
+ _patch_policy()
16
+ _patch_tornado()
17
+
18
+ loop = loop or asyncio.get_event_loop()
19
+ _patch_loop(loop)
20
+
21
+
22
+ def _patch_asyncio():
23
+ """Patch asyncio module to use pure Python tasks and futures."""
24
+
25
+ def run(main, *, debug=False):
26
+ loop = asyncio.get_event_loop()
27
+ loop.set_debug(debug)
28
+ task = asyncio.ensure_future(main)
29
+ try:
30
+ return loop.run_until_complete(task)
31
+ finally:
32
+ if not task.done():
33
+ task.cancel()
34
+ with suppress(asyncio.CancelledError):
35
+ loop.run_until_complete(task)
36
+
37
+ def _get_event_loop(stacklevel=3):
38
+ loop = events._get_running_loop()
39
+ if loop is None:
40
+ loop = events.get_event_loop_policy().get_event_loop()
41
+ return loop
42
+
43
+ # Use module level _current_tasks, all_tasks and patch run method.
44
+ if hasattr(asyncio, '_nest_patched'):
45
+ return
46
+ if sys.version_info >= (3, 6, 0):
47
+ asyncio.Task = asyncio.tasks._CTask = asyncio.tasks.Task = \
48
+ asyncio.tasks._PyTask
49
+ asyncio.Future = asyncio.futures._CFuture = asyncio.futures.Future = \
50
+ asyncio.futures._PyFuture
51
+ if sys.version_info < (3, 7, 0):
52
+ asyncio.tasks._current_tasks = asyncio.tasks.Task._current_tasks
53
+ asyncio.all_tasks = asyncio.tasks.Task.all_tasks
54
+ if sys.version_info >= (3, 9, 0):
55
+ events._get_event_loop = events.get_event_loop = \
56
+ asyncio.get_event_loop = _get_event_loop
57
+ asyncio.run = run
58
+ asyncio._nest_patched = True
59
+
60
+
61
+ def _patch_policy():
62
+ """Patch the policy to always return a patched loop."""
63
+
64
+ def get_event_loop(self):
65
+ if self._local._loop is None:
66
+ loop = self.new_event_loop()
67
+ _patch_loop(loop)
68
+ self.set_event_loop(loop)
69
+ return self._local._loop
70
+
71
+ policy = events.get_event_loop_policy()
72
+ policy.__class__.get_event_loop = get_event_loop
73
+
74
+
75
+ def _patch_loop(loop):
76
+ """Patch loop to make it reentrant."""
77
+
78
+ def run_forever(self):
79
+ with manage_run(self), manage_asyncgens(self):
80
+ while True:
81
+ self._run_once()
82
+ if self._stopping:
83
+ break
84
+ self._stopping = False
85
+
86
+ def run_until_complete(self, future):
87
+ with manage_run(self):
88
+ f = asyncio.ensure_future(future, loop=self)
89
+ if f is not future:
90
+ f._log_destroy_pending = False
91
+ while not f.done():
92
+ self._run_once()
93
+ if self._stopping:
94
+ break
95
+ if not f.done():
96
+ raise RuntimeError(
97
+ 'Event loop stopped before Future completed.')
98
+ return f.result()
99
+
100
+ def _run_once(self):
101
+ """
102
+ Simplified re-implementation of asyncio's _run_once that
103
+ runs handles as they become ready.
104
+ """
105
+ ready = self._ready
106
+ scheduled = self._scheduled
107
+ while scheduled and scheduled[0]._cancelled:
108
+ heappop(scheduled)
109
+
110
+ timeout = (
111
+ 0 if ready or self._stopping
112
+ else min(max(
113
+ scheduled[0]._when - self.time(), 0), 86400) if scheduled
114
+ else None)
115
+ event_list = self._selector.select(timeout)
116
+ self._process_events(event_list)
117
+
118
+ end_time = self.time() + self._clock_resolution
119
+ while scheduled and scheduled[0]._when < end_time:
120
+ handle = heappop(scheduled)
121
+ ready.append(handle)
122
+
123
+ for _ in range(len(ready)):
124
+ if not ready:
125
+ break
126
+ handle = ready.popleft()
127
+ if not handle._cancelled:
128
+ # preempt the current task so that that checks in
129
+ # Task.__step do not raise
130
+ curr_task = curr_tasks.pop(self, None)
131
+
132
+ try:
133
+ handle._run()
134
+ finally:
135
+ # restore the current task
136
+ if curr_task is not None:
137
+ curr_tasks[self] = curr_task
138
+
139
+ handle = None
140
+
141
+ @contextmanager
142
+ def manage_run(self):
143
+ """Set up the loop for running."""
144
+ self._check_closed()
145
+ old_thread_id = self._thread_id
146
+ old_running_loop = events._get_running_loop()
147
+ try:
148
+ self._thread_id = threading.get_ident()
149
+ events._set_running_loop(self)
150
+ self._num_runs_pending += 1
151
+ if self._is_proactorloop:
152
+ if self._self_reading_future is None:
153
+ self.call_soon(self._loop_self_reading)
154
+ yield
155
+ finally:
156
+ self._thread_id = old_thread_id
157
+ events._set_running_loop(old_running_loop)
158
+ self._num_runs_pending -= 1
159
+ if self._is_proactorloop:
160
+ if (self._num_runs_pending == 0
161
+ and self._self_reading_future is not None):
162
+ ov = self._self_reading_future._ov
163
+ self._self_reading_future.cancel()
164
+ if ov is not None:
165
+ self._proactor._unregister(ov)
166
+ self._self_reading_future = None
167
+
168
+ @contextmanager
169
+ def manage_asyncgens(self):
170
+ if not hasattr(sys, 'get_asyncgen_hooks'):
171
+ # Python version is too old.
172
+ return
173
+ old_agen_hooks = sys.get_asyncgen_hooks()
174
+ try:
175
+ self._set_coroutine_origin_tracking(self._debug)
176
+ if self._asyncgens is not None:
177
+ sys.set_asyncgen_hooks(
178
+ firstiter=self._asyncgen_firstiter_hook,
179
+ finalizer=self._asyncgen_finalizer_hook)
180
+ yield
181
+ finally:
182
+ self._set_coroutine_origin_tracking(False)
183
+ if self._asyncgens is not None:
184
+ sys.set_asyncgen_hooks(*old_agen_hooks)
185
+
186
+ def _check_running(self):
187
+ """Do not throw exception if loop is already running."""
188
+ pass
189
+
190
+ if hasattr(loop, '_nest_patched'):
191
+ return
192
+ if not isinstance(loop, asyncio.BaseEventLoop):
193
+ raise ValueError('Can\'t patch loop of type %s' % type(loop))
194
+ cls = loop.__class__
195
+ cls.run_forever = run_forever
196
+ cls.run_until_complete = run_until_complete
197
+ cls._run_once = _run_once
198
+ cls._check_running = _check_running
199
+ cls._check_runnung = _check_running # typo in Python 3.7 source
200
+ cls._num_runs_pending = 1 if loop.is_running() else 0
201
+ cls._is_proactorloop = (
202
+ os.name == 'nt' and issubclass(cls, asyncio.ProactorEventLoop))
203
+ if sys.version_info < (3, 7, 0):
204
+ cls._set_coroutine_origin_tracking = cls._set_coroutine_wrapper
205
+ curr_tasks = asyncio.tasks._current_tasks \
206
+ if sys.version_info >= (3, 7, 0) else asyncio.Task._current_tasks
207
+ cls._nest_patched = True
208
+
209
+
210
+ def _patch_tornado():
211
+ """
212
+ If tornado is imported before nest_asyncio, make tornado aware of
213
+ the pure-Python asyncio Future.
214
+ """
215
+ if 'tornado' in sys.modules:
216
+ import tornado.concurrent as tc # type: ignore
217
+ tc.Future = asyncio.Future
218
+ if asyncio.Future not in tc.FUTURES:
219
+ tc.FUTURES += (asyncio.Future,)
venv/lib/python3.10/site-packages/package_readme.md ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+ <img src="https://i.imgur.com/RUtiVzH.png" width="600" /><br><br>
3
+ </div>
4
+
5
+ # Weights and Biases [![PyPI](https://img.shields.io/pypi/v/wandb)](https://pypi.python.org/pypi/wandb) [![Conda (channel only)](https://img.shields.io/conda/vn/conda-forge/wandb)](https://anaconda.org/conda-forge/wandb) [![CircleCI](https://img.shields.io/circleci/build/github/wandb/wandb/main)](https://circleci.com/gh/wandb/wandb) [![Codecov](https://img.shields.io/codecov/c/gh/wandb/wandb)](https://codecov.io/gh/wandb/wandb)
6
+
7
+ Use W&B to build better models faster. Track and visualize all the pieces of your machine learning pipeline, from datasets to production machine learning models. Get started with W&B today, [sign up for an account!](https://wandb.com?utm_source=github&utm_medium=code&utm_campaign=wandb&utm_content=readme)
8
+
9
+
10
+
11
+ See the [W&B Developer Guide](https://docs.wandb.ai/?utm_source=github&utm_medium=code&utm_campaign=wandb&utm_content=documentation) and [API Reference Guide](https://docs.wandb.ai/ref?utm_source=github&utm_medium=code&utm_campaign=wandb&utm_content=documentation) for a full technical description of the W&B platform.
12
+
13
+ &nbsp;
14
+
15
+ # Quickstart
16
+
17
+ Get started with W&B in four steps:
18
+
19
+ 1. First, sign up for a [W&B account](https://wandb.ai/login?utm_source=github&utm_medium=code&utm_campaign=wandb&utm_content=quickstart).
20
+
21
+ 2. Second, install the W&B SDK with [pip](https://pip.pypa.io/en/stable/). Navigate to your terminal and type the following command:
22
+
23
+ ```shell
24
+ pip install wandb
25
+ ```
26
+
27
+ 3. Third, log into W&B:
28
+
29
+ ```python
30
+ wandb.login()
31
+ ```
32
+
33
+ 4. Use the example code snippet below as a template to integrate W&B to your Python script:
34
+
35
+ ```python
36
+ import wandb
37
+
38
+ # Start a W&B Run with wandb.init
39
+ run = wandb.init(project="my_first_project")
40
+
41
+ # Save model inputs and hyperparameters in a wandb.config object
42
+ config = run.config
43
+ config.learning_rate = 0.01
44
+
45
+ # Model training code here ...
46
+
47
+ # Log metrics over time to visualize performance with wandb.log
48
+ for i in range(10):
49
+ run.log({"loss": ...})
50
+
51
+ # Mark the run as finished, and finish uploading all data
52
+ run.finish()
53
+ ```
54
+
55
+ For example, if the preceding code was stored in a script called train.py:
56
+
57
+ ```shell
58
+ python train.py
59
+ ```
60
+
61
+ You will see a URL in your terminal logs when your script starts and finishes. Data is staged locally in a directory named _wandb_ relative to your script. Navigate to the W&B App to view a dashboard of your first W&B Experiment. Use the W&B App to compare multiple experiments in a unified place, dive into the results of a single run, and much more!
62
+
63
+ &nbsp;
64
+
65
+ # Integrations
66
+
67
+ Use your favorite framework with W&B. W&B integrations make it fast and easy to set up experiment tracking and data versioning inside existing projects. For more information on how to integrate W&B with the framework of your choice, see [W&B Integrations](https://docs.wandb.ai/guides/integrations) in the W&B Developer Guide.
68
+
69
+ &nbsp;
70
+
71
+ # Python Version Support
72
+
73
+ We are committed to supporting our minimum required Python version for *at least* six months after its official end-of-life (EOL) date, as defined by the Python Software Foundation. You can find a list of Python EOL dates [here](https://devguide.python.org/versions/).
74
+
75
+ When we discontinue support for a Python version, we will increment the library’s minor version number to reflect this change.
76
+
77
+ &nbsp;
78
+
79
+ # Contribution guidelines
80
+ Weights & Biases ❤️ open source, and we welcome contributions from the community! See the [Contribution guide](https://github.com/wandb/wandb/blob/main/CONTRIBUTING.md) for more information on the development workflow and the internals of the wandb library. For wandb bugs and feature requests, visit [GitHub Issues](https://github.com/wandb/wandb/issues) or contact support@wandb.com.
81
+
82
+ &nbsp;
83
+
84
+ # Academic Researchers
85
+ Reach out to W&B Support at support@wandb.com to get a [free academic license](https://www.wandb.com/academic) for you and your research group.
86
+
87
+ &nbsp;
88
+
89
+ # W&B Community
90
+
91
+ Be a part of the growing W&B Community and interact with the W&B team in our [Discord](https://wandb.me/discord). Stay connected with the latest ML updates and tutorials with [W&B Fully Connected](https://wandb.ai/fully-connected).
92
+
93
+ &nbsp;
94
+
95
+ # License
96
+
97
+ [MIT License](https://github.com/wandb/wandb/blob/main/LICENSE)
venv/lib/python3.10/site-packages/pkg_resources/__init__.py ADDED
The diff for this file is too large to render. See raw diff
 
venv/lib/python3.10/site-packages/pkg_resources/_vendor/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/pkg_resources/_vendor/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (257 Bytes). View file
 
venv/lib/python3.10/site-packages/pkg_resources/_vendor/appdirs.py ADDED
@@ -0,0 +1,608 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ # Copyright (c) 2005-2010 ActiveState Software Inc.
4
+ # Copyright (c) 2013 Eddy Petrișor
5
+
6
+ """Utilities for determining application-specific dirs.
7
+
8
+ See <http://github.com/ActiveState/appdirs> for details and usage.
9
+ """
10
+ # Dev Notes:
11
+ # - MSDN on where to store app data files:
12
+ # http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120
13
+ # - Mac OS X: http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/index.html
14
+ # - XDG spec for Un*x: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
15
+
16
+ __version_info__ = (1, 4, 3)
17
+ __version__ = '.'.join(map(str, __version_info__))
18
+
19
+
20
+ import sys
21
+ import os
22
+
23
+ PY3 = sys.version_info[0] == 3
24
+
25
+ if PY3:
26
+ unicode = str
27
+
28
+ if sys.platform.startswith('java'):
29
+ import platform
30
+ os_name = platform.java_ver()[3][0]
31
+ if os_name.startswith('Windows'): # "Windows XP", "Windows 7", etc.
32
+ system = 'win32'
33
+ elif os_name.startswith('Mac'): # "Mac OS X", etc.
34
+ system = 'darwin'
35
+ else: # "Linux", "SunOS", "FreeBSD", etc.
36
+ # Setting this to "linux2" is not ideal, but only Windows or Mac
37
+ # are actually checked for and the rest of the module expects
38
+ # *sys.platform* style strings.
39
+ system = 'linux2'
40
+ else:
41
+ system = sys.platform
42
+
43
+
44
+
45
+ def user_data_dir(appname=None, appauthor=None, version=None, roaming=False):
46
+ r"""Return full path to the user-specific data dir for this application.
47
+
48
+ "appname" is the name of application.
49
+ If None, just the system directory is returned.
50
+ "appauthor" (only used on Windows) is the name of the
51
+ appauthor or distributing body for this application. Typically
52
+ it is the owning company name. This falls back to appname. You may
53
+ pass False to disable it.
54
+ "version" is an optional version path element to append to the
55
+ path. You might want to use this if you want multiple versions
56
+ of your app to be able to run independently. If used, this
57
+ would typically be "<major>.<minor>".
58
+ Only applied when appname is present.
59
+ "roaming" (boolean, default False) can be set True to use the Windows
60
+ roaming appdata directory. That means that for users on a Windows
61
+ network setup for roaming profiles, this user data will be
62
+ sync'd on login. See
63
+ <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
64
+ for a discussion of issues.
65
+
66
+ Typical user data directories are:
67
+ Mac OS X: ~/Library/Application Support/<AppName>
68
+ Unix: ~/.local/share/<AppName> # or in $XDG_DATA_HOME, if defined
69
+ Win XP (not roaming): C:\Documents and Settings\<username>\Application Data\<AppAuthor>\<AppName>
70
+ Win XP (roaming): C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>
71
+ Win 7 (not roaming): C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>
72
+ Win 7 (roaming): C:\Users\<username>\AppData\Roaming\<AppAuthor>\<AppName>
73
+
74
+ For Unix, we follow the XDG spec and support $XDG_DATA_HOME.
75
+ That means, by default "~/.local/share/<AppName>".
76
+ """
77
+ if system == "win32":
78
+ if appauthor is None:
79
+ appauthor = appname
80
+ const = roaming and "CSIDL_APPDATA" or "CSIDL_LOCAL_APPDATA"
81
+ path = os.path.normpath(_get_win_folder(const))
82
+ if appname:
83
+ if appauthor is not False:
84
+ path = os.path.join(path, appauthor, appname)
85
+ else:
86
+ path = os.path.join(path, appname)
87
+ elif system == 'darwin':
88
+ path = os.path.expanduser('~/Library/Application Support/')
89
+ if appname:
90
+ path = os.path.join(path, appname)
91
+ else:
92
+ path = os.getenv('XDG_DATA_HOME', os.path.expanduser("~/.local/share"))
93
+ if appname:
94
+ path = os.path.join(path, appname)
95
+ if appname and version:
96
+ path = os.path.join(path, version)
97
+ return path
98
+
99
+
100
+ def site_data_dir(appname=None, appauthor=None, version=None, multipath=False):
101
+ r"""Return full path to the user-shared data dir for this application.
102
+
103
+ "appname" is the name of application.
104
+ If None, just the system directory is returned.
105
+ "appauthor" (only used on Windows) is the name of the
106
+ appauthor or distributing body for this application. Typically
107
+ it is the owning company name. This falls back to appname. You may
108
+ pass False to disable it.
109
+ "version" is an optional version path element to append to the
110
+ path. You might want to use this if you want multiple versions
111
+ of your app to be able to run independently. If used, this
112
+ would typically be "<major>.<minor>".
113
+ Only applied when appname is present.
114
+ "multipath" is an optional parameter only applicable to *nix
115
+ which indicates that the entire list of data dirs should be
116
+ returned. By default, the first item from XDG_DATA_DIRS is
117
+ returned, or '/usr/local/share/<AppName>',
118
+ if XDG_DATA_DIRS is not set
119
+
120
+ Typical site data directories are:
121
+ Mac OS X: /Library/Application Support/<AppName>
122
+ Unix: /usr/local/share/<AppName> or /usr/share/<AppName>
123
+ Win XP: C:\Documents and Settings\All Users\Application Data\<AppAuthor>\<AppName>
124
+ Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.)
125
+ Win 7: C:\ProgramData\<AppAuthor>\<AppName> # Hidden, but writeable on Win 7.
126
+
127
+ For Unix, this is using the $XDG_DATA_DIRS[0] default.
128
+
129
+ WARNING: Do not use this on Windows. See the Vista-Fail note above for why.
130
+ """
131
+ if system == "win32":
132
+ if appauthor is None:
133
+ appauthor = appname
134
+ path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA"))
135
+ if appname:
136
+ if appauthor is not False:
137
+ path = os.path.join(path, appauthor, appname)
138
+ else:
139
+ path = os.path.join(path, appname)
140
+ elif system == 'darwin':
141
+ path = os.path.expanduser('/Library/Application Support')
142
+ if appname:
143
+ path = os.path.join(path, appname)
144
+ else:
145
+ # XDG default for $XDG_DATA_DIRS
146
+ # only first, if multipath is False
147
+ path = os.getenv('XDG_DATA_DIRS',
148
+ os.pathsep.join(['/usr/local/share', '/usr/share']))
149
+ pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)]
150
+ if appname:
151
+ if version:
152
+ appname = os.path.join(appname, version)
153
+ pathlist = [os.sep.join([x, appname]) for x in pathlist]
154
+
155
+ if multipath:
156
+ path = os.pathsep.join(pathlist)
157
+ else:
158
+ path = pathlist[0]
159
+ return path
160
+
161
+ if appname and version:
162
+ path = os.path.join(path, version)
163
+ return path
164
+
165
+
166
+ def user_config_dir(appname=None, appauthor=None, version=None, roaming=False):
167
+ r"""Return full path to the user-specific config dir for this application.
168
+
169
+ "appname" is the name of application.
170
+ If None, just the system directory is returned.
171
+ "appauthor" (only used on Windows) is the name of the
172
+ appauthor or distributing body for this application. Typically
173
+ it is the owning company name. This falls back to appname. You may
174
+ pass False to disable it.
175
+ "version" is an optional version path element to append to the
176
+ path. You might want to use this if you want multiple versions
177
+ of your app to be able to run independently. If used, this
178
+ would typically be "<major>.<minor>".
179
+ Only applied when appname is present.
180
+ "roaming" (boolean, default False) can be set True to use the Windows
181
+ roaming appdata directory. That means that for users on a Windows
182
+ network setup for roaming profiles, this user data will be
183
+ sync'd on login. See
184
+ <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
185
+ for a discussion of issues.
186
+
187
+ Typical user config directories are:
188
+ Mac OS X: same as user_data_dir
189
+ Unix: ~/.config/<AppName> # or in $XDG_CONFIG_HOME, if defined
190
+ Win *: same as user_data_dir
191
+
192
+ For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME.
193
+ That means, by default "~/.config/<AppName>".
194
+ """
195
+ if system in ["win32", "darwin"]:
196
+ path = user_data_dir(appname, appauthor, None, roaming)
197
+ else:
198
+ path = os.getenv('XDG_CONFIG_HOME', os.path.expanduser("~/.config"))
199
+ if appname:
200
+ path = os.path.join(path, appname)
201
+ if appname and version:
202
+ path = os.path.join(path, version)
203
+ return path
204
+
205
+
206
+ def site_config_dir(appname=None, appauthor=None, version=None, multipath=False):
207
+ r"""Return full path to the user-shared data dir for this application.
208
+
209
+ "appname" is the name of application.
210
+ If None, just the system directory is returned.
211
+ "appauthor" (only used on Windows) is the name of the
212
+ appauthor or distributing body for this application. Typically
213
+ it is the owning company name. This falls back to appname. You may
214
+ pass False to disable it.
215
+ "version" is an optional version path element to append to the
216
+ path. You might want to use this if you want multiple versions
217
+ of your app to be able to run independently. If used, this
218
+ would typically be "<major>.<minor>".
219
+ Only applied when appname is present.
220
+ "multipath" is an optional parameter only applicable to *nix
221
+ which indicates that the entire list of config dirs should be
222
+ returned. By default, the first item from XDG_CONFIG_DIRS is
223
+ returned, or '/etc/xdg/<AppName>', if XDG_CONFIG_DIRS is not set
224
+
225
+ Typical site config directories are:
226
+ Mac OS X: same as site_data_dir
227
+ Unix: /etc/xdg/<AppName> or $XDG_CONFIG_DIRS[i]/<AppName> for each value in
228
+ $XDG_CONFIG_DIRS
229
+ Win *: same as site_data_dir
230
+ Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.)
231
+
232
+ For Unix, this is using the $XDG_CONFIG_DIRS[0] default, if multipath=False
233
+
234
+ WARNING: Do not use this on Windows. See the Vista-Fail note above for why.
235
+ """
236
+ if system in ["win32", "darwin"]:
237
+ path = site_data_dir(appname, appauthor)
238
+ if appname and version:
239
+ path = os.path.join(path, version)
240
+ else:
241
+ # XDG default for $XDG_CONFIG_DIRS
242
+ # only first, if multipath is False
243
+ path = os.getenv('XDG_CONFIG_DIRS', '/etc/xdg')
244
+ pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)]
245
+ if appname:
246
+ if version:
247
+ appname = os.path.join(appname, version)
248
+ pathlist = [os.sep.join([x, appname]) for x in pathlist]
249
+
250
+ if multipath:
251
+ path = os.pathsep.join(pathlist)
252
+ else:
253
+ path = pathlist[0]
254
+ return path
255
+
256
+
257
+ def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True):
258
+ r"""Return full path to the user-specific cache dir for this application.
259
+
260
+ "appname" is the name of application.
261
+ If None, just the system directory is returned.
262
+ "appauthor" (only used on Windows) is the name of the
263
+ appauthor or distributing body for this application. Typically
264
+ it is the owning company name. This falls back to appname. You may
265
+ pass False to disable it.
266
+ "version" is an optional version path element to append to the
267
+ path. You might want to use this if you want multiple versions
268
+ of your app to be able to run independently. If used, this
269
+ would typically be "<major>.<minor>".
270
+ Only applied when appname is present.
271
+ "opinion" (boolean) can be False to disable the appending of
272
+ "Cache" to the base app data dir for Windows. See
273
+ discussion below.
274
+
275
+ Typical user cache directories are:
276
+ Mac OS X: ~/Library/Caches/<AppName>
277
+ Unix: ~/.cache/<AppName> (XDG default)
278
+ Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Cache
279
+ Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Cache
280
+
281
+ On Windows the only suggestion in the MSDN docs is that local settings go in
282
+ the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming
283
+ app data dir (the default returned by `user_data_dir` above). Apps typically
284
+ put cache data somewhere *under* the given dir here. Some examples:
285
+ ...\Mozilla\Firefox\Profiles\<ProfileName>\Cache
286
+ ...\Acme\SuperApp\Cache\1.0
287
+ OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value.
288
+ This can be disabled with the `opinion=False` option.
289
+ """
290
+ if system == "win32":
291
+ if appauthor is None:
292
+ appauthor = appname
293
+ path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA"))
294
+ if appname:
295
+ if appauthor is not False:
296
+ path = os.path.join(path, appauthor, appname)
297
+ else:
298
+ path = os.path.join(path, appname)
299
+ if opinion:
300
+ path = os.path.join(path, "Cache")
301
+ elif system == 'darwin':
302
+ path = os.path.expanduser('~/Library/Caches')
303
+ if appname:
304
+ path = os.path.join(path, appname)
305
+ else:
306
+ path = os.getenv('XDG_CACHE_HOME', os.path.expanduser('~/.cache'))
307
+ if appname:
308
+ path = os.path.join(path, appname)
309
+ if appname and version:
310
+ path = os.path.join(path, version)
311
+ return path
312
+
313
+
314
+ def user_state_dir(appname=None, appauthor=None, version=None, roaming=False):
315
+ r"""Return full path to the user-specific state dir for this application.
316
+
317
+ "appname" is the name of application.
318
+ If None, just the system directory is returned.
319
+ "appauthor" (only used on Windows) is the name of the
320
+ appauthor or distributing body for this application. Typically
321
+ it is the owning company name. This falls back to appname. You may
322
+ pass False to disable it.
323
+ "version" is an optional version path element to append to the
324
+ path. You might want to use this if you want multiple versions
325
+ of your app to be able to run independently. If used, this
326
+ would typically be "<major>.<minor>".
327
+ Only applied when appname is present.
328
+ "roaming" (boolean, default False) can be set True to use the Windows
329
+ roaming appdata directory. That means that for users on a Windows
330
+ network setup for roaming profiles, this user data will be
331
+ sync'd on login. See
332
+ <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
333
+ for a discussion of issues.
334
+
335
+ Typical user state directories are:
336
+ Mac OS X: same as user_data_dir
337
+ Unix: ~/.local/state/<AppName> # or in $XDG_STATE_HOME, if defined
338
+ Win *: same as user_data_dir
339
+
340
+ For Unix, we follow this Debian proposal <https://wiki.debian.org/XDGBaseDirectorySpecification#state>
341
+ to extend the XDG spec and support $XDG_STATE_HOME.
342
+
343
+ That means, by default "~/.local/state/<AppName>".
344
+ """
345
+ if system in ["win32", "darwin"]:
346
+ path = user_data_dir(appname, appauthor, None, roaming)
347
+ else:
348
+ path = os.getenv('XDG_STATE_HOME', os.path.expanduser("~/.local/state"))
349
+ if appname:
350
+ path = os.path.join(path, appname)
351
+ if appname and version:
352
+ path = os.path.join(path, version)
353
+ return path
354
+
355
+
356
+ def user_log_dir(appname=None, appauthor=None, version=None, opinion=True):
357
+ r"""Return full path to the user-specific log dir for this application.
358
+
359
+ "appname" is the name of application.
360
+ If None, just the system directory is returned.
361
+ "appauthor" (only used on Windows) is the name of the
362
+ appauthor or distributing body for this application. Typically
363
+ it is the owning company name. This falls back to appname. You may
364
+ pass False to disable it.
365
+ "version" is an optional version path element to append to the
366
+ path. You might want to use this if you want multiple versions
367
+ of your app to be able to run independently. If used, this
368
+ would typically be "<major>.<minor>".
369
+ Only applied when appname is present.
370
+ "opinion" (boolean) can be False to disable the appending of
371
+ "Logs" to the base app data dir for Windows, and "log" to the
372
+ base cache dir for Unix. See discussion below.
373
+
374
+ Typical user log directories are:
375
+ Mac OS X: ~/Library/Logs/<AppName>
376
+ Unix: ~/.cache/<AppName>/log # or under $XDG_CACHE_HOME if defined
377
+ Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Logs
378
+ Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Logs
379
+
380
+ On Windows the only suggestion in the MSDN docs is that local settings
381
+ go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in
382
+ examples of what some windows apps use for a logs dir.)
383
+
384
+ OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA`
385
+ value for Windows and appends "log" to the user cache dir for Unix.
386
+ This can be disabled with the `opinion=False` option.
387
+ """
388
+ if system == "darwin":
389
+ path = os.path.join(
390
+ os.path.expanduser('~/Library/Logs'),
391
+ appname)
392
+ elif system == "win32":
393
+ path = user_data_dir(appname, appauthor, version)
394
+ version = False
395
+ if opinion:
396
+ path = os.path.join(path, "Logs")
397
+ else:
398
+ path = user_cache_dir(appname, appauthor, version)
399
+ version = False
400
+ if opinion:
401
+ path = os.path.join(path, "log")
402
+ if appname and version:
403
+ path = os.path.join(path, version)
404
+ return path
405
+
406
+
407
+ class AppDirs(object):
408
+ """Convenience wrapper for getting application dirs."""
409
+ def __init__(self, appname=None, appauthor=None, version=None,
410
+ roaming=False, multipath=False):
411
+ self.appname = appname
412
+ self.appauthor = appauthor
413
+ self.version = version
414
+ self.roaming = roaming
415
+ self.multipath = multipath
416
+
417
+ @property
418
+ def user_data_dir(self):
419
+ return user_data_dir(self.appname, self.appauthor,
420
+ version=self.version, roaming=self.roaming)
421
+
422
+ @property
423
+ def site_data_dir(self):
424
+ return site_data_dir(self.appname, self.appauthor,
425
+ version=self.version, multipath=self.multipath)
426
+
427
+ @property
428
+ def user_config_dir(self):
429
+ return user_config_dir(self.appname, self.appauthor,
430
+ version=self.version, roaming=self.roaming)
431
+
432
+ @property
433
+ def site_config_dir(self):
434
+ return site_config_dir(self.appname, self.appauthor,
435
+ version=self.version, multipath=self.multipath)
436
+
437
+ @property
438
+ def user_cache_dir(self):
439
+ return user_cache_dir(self.appname, self.appauthor,
440
+ version=self.version)
441
+
442
+ @property
443
+ def user_state_dir(self):
444
+ return user_state_dir(self.appname, self.appauthor,
445
+ version=self.version)
446
+
447
+ @property
448
+ def user_log_dir(self):
449
+ return user_log_dir(self.appname, self.appauthor,
450
+ version=self.version)
451
+
452
+
453
+ #---- internal support stuff
454
+
455
+ def _get_win_folder_from_registry(csidl_name):
456
+ """This is a fallback technique at best. I'm not sure if using the
457
+ registry for this guarantees us the correct answer for all CSIDL_*
458
+ names.
459
+ """
460
+ if PY3:
461
+ import winreg as _winreg
462
+ else:
463
+ import _winreg
464
+
465
+ shell_folder_name = {
466
+ "CSIDL_APPDATA": "AppData",
467
+ "CSIDL_COMMON_APPDATA": "Common AppData",
468
+ "CSIDL_LOCAL_APPDATA": "Local AppData",
469
+ }[csidl_name]
470
+
471
+ key = _winreg.OpenKey(
472
+ _winreg.HKEY_CURRENT_USER,
473
+ r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
474
+ )
475
+ dir, type = _winreg.QueryValueEx(key, shell_folder_name)
476
+ return dir
477
+
478
+
479
+ def _get_win_folder_with_pywin32(csidl_name):
480
+ from win32com.shell import shellcon, shell
481
+ dir = shell.SHGetFolderPath(0, getattr(shellcon, csidl_name), 0, 0)
482
+ # Try to make this a unicode path because SHGetFolderPath does
483
+ # not return unicode strings when there is unicode data in the
484
+ # path.
485
+ try:
486
+ dir = unicode(dir)
487
+
488
+ # Downgrade to short path name if have highbit chars. See
489
+ # <http://bugs.activestate.com/show_bug.cgi?id=85099>.
490
+ has_high_char = False
491
+ for c in dir:
492
+ if ord(c) > 255:
493
+ has_high_char = True
494
+ break
495
+ if has_high_char:
496
+ try:
497
+ import win32api
498
+ dir = win32api.GetShortPathName(dir)
499
+ except ImportError:
500
+ pass
501
+ except UnicodeError:
502
+ pass
503
+ return dir
504
+
505
+
506
+ def _get_win_folder_with_ctypes(csidl_name):
507
+ import ctypes
508
+
509
+ csidl_const = {
510
+ "CSIDL_APPDATA": 26,
511
+ "CSIDL_COMMON_APPDATA": 35,
512
+ "CSIDL_LOCAL_APPDATA": 28,
513
+ }[csidl_name]
514
+
515
+ buf = ctypes.create_unicode_buffer(1024)
516
+ ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf)
517
+
518
+ # Downgrade to short path name if have highbit chars. See
519
+ # <http://bugs.activestate.com/show_bug.cgi?id=85099>.
520
+ has_high_char = False
521
+ for c in buf:
522
+ if ord(c) > 255:
523
+ has_high_char = True
524
+ break
525
+ if has_high_char:
526
+ buf2 = ctypes.create_unicode_buffer(1024)
527
+ if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024):
528
+ buf = buf2
529
+
530
+ return buf.value
531
+
532
+ def _get_win_folder_with_jna(csidl_name):
533
+ import array
534
+ from com.sun import jna
535
+ from com.sun.jna.platform import win32
536
+
537
+ buf_size = win32.WinDef.MAX_PATH * 2
538
+ buf = array.zeros('c', buf_size)
539
+ shell = win32.Shell32.INSTANCE
540
+ shell.SHGetFolderPath(None, getattr(win32.ShlObj, csidl_name), None, win32.ShlObj.SHGFP_TYPE_CURRENT, buf)
541
+ dir = jna.Native.toString(buf.tostring()).rstrip("\0")
542
+
543
+ # Downgrade to short path name if have highbit chars. See
544
+ # <http://bugs.activestate.com/show_bug.cgi?id=85099>.
545
+ has_high_char = False
546
+ for c in dir:
547
+ if ord(c) > 255:
548
+ has_high_char = True
549
+ break
550
+ if has_high_char:
551
+ buf = array.zeros('c', buf_size)
552
+ kernel = win32.Kernel32.INSTANCE
553
+ if kernel.GetShortPathName(dir, buf, buf_size):
554
+ dir = jna.Native.toString(buf.tostring()).rstrip("\0")
555
+
556
+ return dir
557
+
558
+ if system == "win32":
559
+ try:
560
+ import win32com.shell
561
+ _get_win_folder = _get_win_folder_with_pywin32
562
+ except ImportError:
563
+ try:
564
+ from ctypes import windll
565
+ _get_win_folder = _get_win_folder_with_ctypes
566
+ except ImportError:
567
+ try:
568
+ import com.sun.jna
569
+ _get_win_folder = _get_win_folder_with_jna
570
+ except ImportError:
571
+ _get_win_folder = _get_win_folder_from_registry
572
+
573
+
574
+ #---- self test code
575
+
576
+ if __name__ == "__main__":
577
+ appname = "MyApp"
578
+ appauthor = "MyCompany"
579
+
580
+ props = ("user_data_dir",
581
+ "user_config_dir",
582
+ "user_cache_dir",
583
+ "user_state_dir",
584
+ "user_log_dir",
585
+ "site_data_dir",
586
+ "site_config_dir")
587
+
588
+ print("-- app dirs %s --" % __version__)
589
+
590
+ print("-- app dirs (with optional 'version')")
591
+ dirs = AppDirs(appname, appauthor, version="1.0")
592
+ for prop in props:
593
+ print("%s: %s" % (prop, getattr(dirs, prop)))
594
+
595
+ print("\n-- app dirs (without optional 'version')")
596
+ dirs = AppDirs(appname, appauthor)
597
+ for prop in props:
598
+ print("%s: %s" % (prop, getattr(dirs, prop)))
599
+
600
+ print("\n-- app dirs (without optional 'appauthor')")
601
+ dirs = AppDirs(appname)
602
+ for prop in props:
603
+ print("%s: %s" % (prop, getattr(dirs, prop)))
604
+
605
+ print("\n-- app dirs (with disabled 'appauthor')")
606
+ dirs = AppDirs(appname, appauthor=False)
607
+ for prop in props:
608
+ print("%s: %s" % (prop, getattr(dirs, prop)))
venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/__about__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ __all__ = [
6
+ "__title__",
7
+ "__summary__",
8
+ "__uri__",
9
+ "__version__",
10
+ "__author__",
11
+ "__email__",
12
+ "__license__",
13
+ "__copyright__",
14
+ ]
15
+
16
+ __title__ = "packaging"
17
+ __summary__ = "Core utilities for Python packages"
18
+ __uri__ = "https://github.com/pypa/packaging"
19
+
20
+ __version__ = "21.2"
21
+
22
+ __author__ = "Donald Stufft and individual contributors"
23
+ __email__ = "donald@stufft.io"
24
+
25
+ __license__ = "BSD-2-Clause or Apache-2.0"
26
+ __copyright__ = "2014-2019 %s" % __author__
venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/__init__.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ from .__about__ import (
6
+ __author__,
7
+ __copyright__,
8
+ __email__,
9
+ __license__,
10
+ __summary__,
11
+ __title__,
12
+ __uri__,
13
+ __version__,
14
+ )
15
+
16
+ __all__ = [
17
+ "__title__",
18
+ "__summary__",
19
+ "__uri__",
20
+ "__version__",
21
+ "__author__",
22
+ "__email__",
23
+ "__license__",
24
+ "__copyright__",
25
+ ]
venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/__pycache__/__about__.cpython-310.pyc ADDED
Binary file (664 Bytes). View file
 
venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/__pycache__/_musllinux.cpython-310.pyc ADDED
Binary file (4.69 kB). View file
 
venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/__pycache__/_structures.cpython-310.pyc ADDED
Binary file (3.04 kB). View file
 
venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/__pycache__/markers.cpython-310.pyc ADDED
Binary file (9.37 kB). View file
 
venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/__pycache__/requirements.cpython-310.pyc ADDED
Binary file (4.06 kB). View file
 
venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/__pycache__/specifiers.cpython-310.pyc ADDED
Binary file (22.3 kB). View file
 
venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/__pycache__/tags.cpython-310.pyc ADDED
Binary file (12.3 kB). View file
 
venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/__pycache__/utils.cpython-310.pyc ADDED
Binary file (3.65 kB). View file
 
venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/_manylinux.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import functools
3
+ import os
4
+ import re
5
+ import struct
6
+ import sys
7
+ import warnings
8
+ from typing import IO, Dict, Iterator, NamedTuple, Optional, Tuple
9
+
10
+
11
+ # Python does not provide platform information at sufficient granularity to
12
+ # identify the architecture of the running executable in some cases, so we
13
+ # determine it dynamically by reading the information from the running
14
+ # process. This only applies on Linux, which uses the ELF format.
15
+ class _ELFFileHeader:
16
+ # https://en.wikipedia.org/wiki/Executable_and_Linkable_Format#File_header
17
+ class _InvalidELFFileHeader(ValueError):
18
+ """
19
+ An invalid ELF file header was found.
20
+ """
21
+
22
+ ELF_MAGIC_NUMBER = 0x7F454C46
23
+ ELFCLASS32 = 1
24
+ ELFCLASS64 = 2
25
+ ELFDATA2LSB = 1
26
+ ELFDATA2MSB = 2
27
+ EM_386 = 3
28
+ EM_S390 = 22
29
+ EM_ARM = 40
30
+ EM_X86_64 = 62
31
+ EF_ARM_ABIMASK = 0xFF000000
32
+ EF_ARM_ABI_VER5 = 0x05000000
33
+ EF_ARM_ABI_FLOAT_HARD = 0x00000400
34
+
35
+ def __init__(self, file: IO[bytes]) -> None:
36
+ def unpack(fmt: str) -> int:
37
+ try:
38
+ data = file.read(struct.calcsize(fmt))
39
+ result: Tuple[int, ...] = struct.unpack(fmt, data)
40
+ except struct.error:
41
+ raise _ELFFileHeader._InvalidELFFileHeader()
42
+ return result[0]
43
+
44
+ self.e_ident_magic = unpack(">I")
45
+ if self.e_ident_magic != self.ELF_MAGIC_NUMBER:
46
+ raise _ELFFileHeader._InvalidELFFileHeader()
47
+ self.e_ident_class = unpack("B")
48
+ if self.e_ident_class not in {self.ELFCLASS32, self.ELFCLASS64}:
49
+ raise _ELFFileHeader._InvalidELFFileHeader()
50
+ self.e_ident_data = unpack("B")
51
+ if self.e_ident_data not in {self.ELFDATA2LSB, self.ELFDATA2MSB}:
52
+ raise _ELFFileHeader._InvalidELFFileHeader()
53
+ self.e_ident_version = unpack("B")
54
+ self.e_ident_osabi = unpack("B")
55
+ self.e_ident_abiversion = unpack("B")
56
+ self.e_ident_pad = file.read(7)
57
+ format_h = "<H" if self.e_ident_data == self.ELFDATA2LSB else ">H"
58
+ format_i = "<I" if self.e_ident_data == self.ELFDATA2LSB else ">I"
59
+ format_q = "<Q" if self.e_ident_data == self.ELFDATA2LSB else ">Q"
60
+ format_p = format_i if self.e_ident_class == self.ELFCLASS32 else format_q
61
+ self.e_type = unpack(format_h)
62
+ self.e_machine = unpack(format_h)
63
+ self.e_version = unpack(format_i)
64
+ self.e_entry = unpack(format_p)
65
+ self.e_phoff = unpack(format_p)
66
+ self.e_shoff = unpack(format_p)
67
+ self.e_flags = unpack(format_i)
68
+ self.e_ehsize = unpack(format_h)
69
+ self.e_phentsize = unpack(format_h)
70
+ self.e_phnum = unpack(format_h)
71
+ self.e_shentsize = unpack(format_h)
72
+ self.e_shnum = unpack(format_h)
73
+ self.e_shstrndx = unpack(format_h)
74
+
75
+
76
+ def _get_elf_header() -> Optional[_ELFFileHeader]:
77
+ try:
78
+ with open(sys.executable, "rb") as f:
79
+ elf_header = _ELFFileHeader(f)
80
+ except (OSError, TypeError, _ELFFileHeader._InvalidELFFileHeader):
81
+ return None
82
+ return elf_header
83
+
84
+
85
+ def _is_linux_armhf() -> bool:
86
+ # hard-float ABI can be detected from the ELF header of the running
87
+ # process
88
+ # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf
89
+ elf_header = _get_elf_header()
90
+ if elf_header is None:
91
+ return False
92
+ result = elf_header.e_ident_class == elf_header.ELFCLASS32
93
+ result &= elf_header.e_ident_data == elf_header.ELFDATA2LSB
94
+ result &= elf_header.e_machine == elf_header.EM_ARM
95
+ result &= (
96
+ elf_header.e_flags & elf_header.EF_ARM_ABIMASK
97
+ ) == elf_header.EF_ARM_ABI_VER5
98
+ result &= (
99
+ elf_header.e_flags & elf_header.EF_ARM_ABI_FLOAT_HARD
100
+ ) == elf_header.EF_ARM_ABI_FLOAT_HARD
101
+ return result
102
+
103
+
104
+ def _is_linux_i686() -> bool:
105
+ elf_header = _get_elf_header()
106
+ if elf_header is None:
107
+ return False
108
+ result = elf_header.e_ident_class == elf_header.ELFCLASS32
109
+ result &= elf_header.e_ident_data == elf_header.ELFDATA2LSB
110
+ result &= elf_header.e_machine == elf_header.EM_386
111
+ return result
112
+
113
+
114
+ def _have_compatible_abi(arch: str) -> bool:
115
+ if arch == "armv7l":
116
+ return _is_linux_armhf()
117
+ if arch == "i686":
118
+ return _is_linux_i686()
119
+ return arch in {"x86_64", "aarch64", "ppc64", "ppc64le", "s390x"}
120
+
121
+
122
+ # If glibc ever changes its major version, we need to know what the last
123
+ # minor version was, so we can build the complete list of all versions.
124
+ # For now, guess what the highest minor version might be, assume it will
125
+ # be 50 for testing. Once this actually happens, update the dictionary
126
+ # with the actual value.
127
+ _LAST_GLIBC_MINOR: Dict[int, int] = collections.defaultdict(lambda: 50)
128
+
129
+
130
+ class _GLibCVersion(NamedTuple):
131
+ major: int
132
+ minor: int
133
+
134
+
135
+ def _glibc_version_string_confstr() -> Optional[str]:
136
+ """
137
+ Primary implementation of glibc_version_string using os.confstr.
138
+ """
139
+ # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely
140
+ # to be broken or missing. This strategy is used in the standard library
141
+ # platform module.
142
+ # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183
143
+ try:
144
+ # os.confstr("CS_GNU_LIBC_VERSION") returns a string like "glibc 2.17".
145
+ version_string = os.confstr("CS_GNU_LIBC_VERSION")
146
+ assert version_string is not None
147
+ _, version = version_string.split()
148
+ except (AssertionError, AttributeError, OSError, ValueError):
149
+ # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...
150
+ return None
151
+ return version
152
+
153
+
154
+ def _glibc_version_string_ctypes() -> Optional[str]:
155
+ """
156
+ Fallback implementation of glibc_version_string using ctypes.
157
+ """
158
+ try:
159
+ import ctypes
160
+ except ImportError:
161
+ return None
162
+
163
+ # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen
164
+ # manpage says, "If filename is NULL, then the returned handle is for the
165
+ # main program". This way we can let the linker do the work to figure out
166
+ # which libc our process is actually using.
167
+ #
168
+ # We must also handle the special case where the executable is not a
169
+ # dynamically linked executable. This can occur when using musl libc,
170
+ # for example. In this situation, dlopen() will error, leading to an
171
+ # OSError. Interestingly, at least in the case of musl, there is no
172
+ # errno set on the OSError. The single string argument used to construct
173
+ # OSError comes from libc itself and is therefore not portable to
174
+ # hard code here. In any case, failure to call dlopen() means we
175
+ # can proceed, so we bail on our attempt.
176
+ try:
177
+ process_namespace = ctypes.CDLL(None)
178
+ except OSError:
179
+ return None
180
+
181
+ try:
182
+ gnu_get_libc_version = process_namespace.gnu_get_libc_version
183
+ except AttributeError:
184
+ # Symbol doesn't exist -> therefore, we are not linked to
185
+ # glibc.
186
+ return None
187
+
188
+ # Call gnu_get_libc_version, which returns a string like "2.5"
189
+ gnu_get_libc_version.restype = ctypes.c_char_p
190
+ version_str: str = gnu_get_libc_version()
191
+ # py2 / py3 compatibility:
192
+ if not isinstance(version_str, str):
193
+ version_str = version_str.decode("ascii")
194
+
195
+ return version_str
196
+
197
+
198
+ def _glibc_version_string() -> Optional[str]:
199
+ """Returns glibc version string, or None if not using glibc."""
200
+ return _glibc_version_string_confstr() or _glibc_version_string_ctypes()
201
+
202
+
203
+ def _parse_glibc_version(version_str: str) -> Tuple[int, int]:
204
+ """Parse glibc version.
205
+
206
+ We use a regexp instead of str.split because we want to discard any
207
+ random junk that might come after the minor version -- this might happen
208
+ in patched/forked versions of glibc (e.g. Linaro's version of glibc
209
+ uses version strings like "2.20-2014.11"). See gh-3588.
210
+ """
211
+ m = re.match(r"(?P<major>[0-9]+)\.(?P<minor>[0-9]+)", version_str)
212
+ if not m:
213
+ warnings.warn(
214
+ "Expected glibc version with 2 components major.minor,"
215
+ " got: %s" % version_str,
216
+ RuntimeWarning,
217
+ )
218
+ return -1, -1
219
+ return int(m.group("major")), int(m.group("minor"))
220
+
221
+
222
+ @functools.lru_cache()
223
+ def _get_glibc_version() -> Tuple[int, int]:
224
+ version_str = _glibc_version_string()
225
+ if version_str is None:
226
+ return (-1, -1)
227
+ return _parse_glibc_version(version_str)
228
+
229
+
230
+ # From PEP 513, PEP 600
231
+ def _is_compatible(name: str, arch: str, version: _GLibCVersion) -> bool:
232
+ sys_glibc = _get_glibc_version()
233
+ if sys_glibc < version:
234
+ return False
235
+ # Check for presence of _manylinux module.
236
+ try:
237
+ import _manylinux # noqa
238
+ except ImportError:
239
+ return True
240
+ if hasattr(_manylinux, "manylinux_compatible"):
241
+ result = _manylinux.manylinux_compatible(version[0], version[1], arch)
242
+ if result is not None:
243
+ return bool(result)
244
+ return True
245
+ if version == _GLibCVersion(2, 5):
246
+ if hasattr(_manylinux, "manylinux1_compatible"):
247
+ return bool(_manylinux.manylinux1_compatible)
248
+ if version == _GLibCVersion(2, 12):
249
+ if hasattr(_manylinux, "manylinux2010_compatible"):
250
+ return bool(_manylinux.manylinux2010_compatible)
251
+ if version == _GLibCVersion(2, 17):
252
+ if hasattr(_manylinux, "manylinux2014_compatible"):
253
+ return bool(_manylinux.manylinux2014_compatible)
254
+ return True
255
+
256
+
257
+ _LEGACY_MANYLINUX_MAP = {
258
+ # CentOS 7 w/ glibc 2.17 (PEP 599)
259
+ (2, 17): "manylinux2014",
260
+ # CentOS 6 w/ glibc 2.12 (PEP 571)
261
+ (2, 12): "manylinux2010",
262
+ # CentOS 5 w/ glibc 2.5 (PEP 513)
263
+ (2, 5): "manylinux1",
264
+ }
265
+
266
+
267
+ def platform_tags(linux: str, arch: str) -> Iterator[str]:
268
+ if not _have_compatible_abi(arch):
269
+ return
270
+ # Oldest glibc to be supported regardless of architecture is (2, 17).
271
+ too_old_glibc2 = _GLibCVersion(2, 16)
272
+ if arch in {"x86_64", "i686"}:
273
+ # On x86/i686 also oldest glibc to be supported is (2, 5).
274
+ too_old_glibc2 = _GLibCVersion(2, 4)
275
+ current_glibc = _GLibCVersion(*_get_glibc_version())
276
+ glibc_max_list = [current_glibc]
277
+ # We can assume compatibility across glibc major versions.
278
+ # https://sourceware.org/bugzilla/show_bug.cgi?id=24636
279
+ #
280
+ # Build a list of maximum glibc versions so that we can
281
+ # output the canonical list of all glibc from current_glibc
282
+ # down to too_old_glibc2, including all intermediary versions.
283
+ for glibc_major in range(current_glibc.major - 1, 1, -1):
284
+ glibc_minor = _LAST_GLIBC_MINOR[glibc_major]
285
+ glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor))
286
+ for glibc_max in glibc_max_list:
287
+ if glibc_max.major == too_old_glibc2.major:
288
+ min_minor = too_old_glibc2.minor
289
+ else:
290
+ # For other glibc major versions oldest supported is (x, 0).
291
+ min_minor = -1
292
+ for glibc_minor in range(glibc_max.minor, min_minor, -1):
293
+ glibc_version = _GLibCVersion(glibc_max.major, glibc_minor)
294
+ tag = "manylinux_{}_{}".format(*glibc_version)
295
+ if _is_compatible(tag, arch, glibc_version):
296
+ yield linux.replace("linux", tag)
297
+ # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags.
298
+ if glibc_version in _LEGACY_MANYLINUX_MAP:
299
+ legacy_tag = _LEGACY_MANYLINUX_MAP[glibc_version]
300
+ if _is_compatible(legacy_tag, arch, glibc_version):
301
+ yield linux.replace("linux", legacy_tag)
venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/_musllinux.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PEP 656 support.
2
+
3
+ This module implements logic to detect if the currently running Python is
4
+ linked against musl, and what musl version is used.
5
+ """
6
+
7
+ import contextlib
8
+ import functools
9
+ import operator
10
+ import os
11
+ import re
12
+ import struct
13
+ import subprocess
14
+ import sys
15
+ from typing import IO, Iterator, NamedTuple, Optional, Tuple
16
+
17
+
18
+ def _read_unpacked(f: IO[bytes], fmt: str) -> Tuple[int, ...]:
19
+ return struct.unpack(fmt, f.read(struct.calcsize(fmt)))
20
+
21
+
22
+ def _parse_ld_musl_from_elf(f: IO[bytes]) -> Optional[str]:
23
+ """Detect musl libc location by parsing the Python executable.
24
+
25
+ Based on: https://gist.github.com/lyssdod/f51579ae8d93c8657a5564aefc2ffbca
26
+ ELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html
27
+ """
28
+ f.seek(0)
29
+ try:
30
+ ident = _read_unpacked(f, "16B")
31
+ except struct.error:
32
+ return None
33
+ if ident[:4] != tuple(b"\x7fELF"): # Invalid magic, not ELF.
34
+ return None
35
+ f.seek(struct.calcsize("HHI"), 1) # Skip file type, machine, and version.
36
+
37
+ try:
38
+ # e_fmt: Format for program header.
39
+ # p_fmt: Format for section header.
40
+ # p_idx: Indexes to find p_type, p_offset, and p_filesz.
41
+ e_fmt, p_fmt, p_idx = {
42
+ 1: ("IIIIHHH", "IIIIIIII", (0, 1, 4)), # 32-bit.
43
+ 2: ("QQQIHHH", "IIQQQQQQ", (0, 2, 5)), # 64-bit.
44
+ }[ident[4]]
45
+ except KeyError:
46
+ return None
47
+ else:
48
+ p_get = operator.itemgetter(*p_idx)
49
+
50
+ # Find the interpreter section and return its content.
51
+ try:
52
+ _, e_phoff, _, _, _, e_phentsize, e_phnum = _read_unpacked(f, e_fmt)
53
+ except struct.error:
54
+ return None
55
+ for i in range(e_phnum + 1):
56
+ f.seek(e_phoff + e_phentsize * i)
57
+ try:
58
+ p_type, p_offset, p_filesz = p_get(_read_unpacked(f, p_fmt))
59
+ except struct.error:
60
+ return None
61
+ if p_type != 3: # Not PT_INTERP.
62
+ continue
63
+ f.seek(p_offset)
64
+ interpreter = os.fsdecode(f.read(p_filesz)).strip("\0")
65
+ if "musl" not in interpreter:
66
+ return None
67
+ return interpreter
68
+ return None
69
+
70
+
71
+ class _MuslVersion(NamedTuple):
72
+ major: int
73
+ minor: int
74
+
75
+
76
+ def _parse_musl_version(output: str) -> Optional[_MuslVersion]:
77
+ lines = [n for n in (n.strip() for n in output.splitlines()) if n]
78
+ if len(lines) < 2 or lines[0][:4] != "musl":
79
+ return None
80
+ m = re.match(r"Version (\d+)\.(\d+)", lines[1])
81
+ if not m:
82
+ return None
83
+ return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2)))
84
+
85
+
86
+ @functools.lru_cache()
87
+ def _get_musl_version(executable: str) -> Optional[_MuslVersion]:
88
+ """Detect currently-running musl runtime version.
89
+
90
+ This is done by checking the specified executable's dynamic linking
91
+ information, and invoking the loader to parse its output for a version
92
+ string. If the loader is musl, the output would be something like::
93
+
94
+ musl libc (x86_64)
95
+ Version 1.2.2
96
+ Dynamic Program Loader
97
+ """
98
+ with contextlib.ExitStack() as stack:
99
+ try:
100
+ f = stack.enter_context(open(executable, "rb"))
101
+ except IOError:
102
+ return None
103
+ ld = _parse_ld_musl_from_elf(f)
104
+ if not ld:
105
+ return None
106
+ proc = subprocess.run([ld], stderr=subprocess.PIPE, universal_newlines=True)
107
+ return _parse_musl_version(proc.stderr)
108
+
109
+
110
+ def platform_tags(arch: str) -> Iterator[str]:
111
+ """Generate musllinux tags compatible to the current platform.
112
+
113
+ :param arch: Should be the part of platform tag after the ``linux_``
114
+ prefix, e.g. ``x86_64``. The ``linux_`` prefix is assumed as a
115
+ prerequisite for the current platform to be musllinux-compatible.
116
+
117
+ :returns: An iterator of compatible musllinux tags.
118
+ """
119
+ sys_musl = _get_musl_version(sys.executable)
120
+ if sys_musl is None: # Python not dynamically linked against musl.
121
+ return
122
+ for minor in range(sys_musl.minor, -1, -1):
123
+ yield f"musllinux_{sys_musl.major}_{minor}_{arch}"
124
+
125
+
126
+ if __name__ == "__main__": # pragma: no cover
127
+ import sysconfig
128
+
129
+ plat = sysconfig.get_platform()
130
+ assert plat.startswith("linux-"), "not linux"
131
+
132
+ print("plat:", plat)
133
+ print("musl:", _get_musl_version(sys.executable))
134
+ print("tags:", end=" ")
135
+ for t in platform_tags(re.sub(r"[.-]", "_", plat.split("-", 1)[-1])):
136
+ print(t, end="\n ")
venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/_structures.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+
6
+ class InfinityType:
7
+ def __repr__(self) -> str:
8
+ return "Infinity"
9
+
10
+ def __hash__(self) -> int:
11
+ return hash(repr(self))
12
+
13
+ def __lt__(self, other: object) -> bool:
14
+ return False
15
+
16
+ def __le__(self, other: object) -> bool:
17
+ return False
18
+
19
+ def __eq__(self, other: object) -> bool:
20
+ return isinstance(other, self.__class__)
21
+
22
+ def __ne__(self, other: object) -> bool:
23
+ return not isinstance(other, self.__class__)
24
+
25
+ def __gt__(self, other: object) -> bool:
26
+ return True
27
+
28
+ def __ge__(self, other: object) -> bool:
29
+ return True
30
+
31
+ def __neg__(self: object) -> "NegativeInfinityType":
32
+ return NegativeInfinity
33
+
34
+
35
+ Infinity = InfinityType()
36
+
37
+
38
+ class NegativeInfinityType:
39
+ def __repr__(self) -> str:
40
+ return "-Infinity"
41
+
42
+ def __hash__(self) -> int:
43
+ return hash(repr(self))
44
+
45
+ def __lt__(self, other: object) -> bool:
46
+ return True
47
+
48
+ def __le__(self, other: object) -> bool:
49
+ return True
50
+
51
+ def __eq__(self, other: object) -> bool:
52
+ return isinstance(other, self.__class__)
53
+
54
+ def __ne__(self, other: object) -> bool:
55
+ return not isinstance(other, self.__class__)
56
+
57
+ def __gt__(self, other: object) -> bool:
58
+ return False
59
+
60
+ def __ge__(self, other: object) -> bool:
61
+ return False
62
+
63
+ def __neg__(self: object) -> InfinityType:
64
+ return Infinity
65
+
66
+
67
+ NegativeInfinity = NegativeInfinityType()
venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/requirements.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ import re
6
+ import string
7
+ import urllib.parse
8
+ from typing import List, Optional as TOptional, Set
9
+
10
+ from pkg_resources.extern.pyparsing import ( # noqa
11
+ Combine,
12
+ Literal as L,
13
+ Optional,
14
+ ParseException,
15
+ Regex,
16
+ Word,
17
+ ZeroOrMore,
18
+ originalTextFor,
19
+ stringEnd,
20
+ stringStart,
21
+ )
22
+
23
+ from .markers import MARKER_EXPR, Marker
24
+ from .specifiers import LegacySpecifier, Specifier, SpecifierSet
25
+
26
+
27
+ class InvalidRequirement(ValueError):
28
+ """
29
+ An invalid requirement was found, users should refer to PEP 508.
30
+ """
31
+
32
+
33
+ ALPHANUM = Word(string.ascii_letters + string.digits)
34
+
35
+ LBRACKET = L("[").suppress()
36
+ RBRACKET = L("]").suppress()
37
+ LPAREN = L("(").suppress()
38
+ RPAREN = L(")").suppress()
39
+ COMMA = L(",").suppress()
40
+ SEMICOLON = L(";").suppress()
41
+ AT = L("@").suppress()
42
+
43
+ PUNCTUATION = Word("-_.")
44
+ IDENTIFIER_END = ALPHANUM | (ZeroOrMore(PUNCTUATION) + ALPHANUM)
45
+ IDENTIFIER = Combine(ALPHANUM + ZeroOrMore(IDENTIFIER_END))
46
+
47
+ NAME = IDENTIFIER("name")
48
+ EXTRA = IDENTIFIER
49
+
50
+ URI = Regex(r"[^ ]+")("url")
51
+ URL = AT + URI
52
+
53
+ EXTRAS_LIST = EXTRA + ZeroOrMore(COMMA + EXTRA)
54
+ EXTRAS = (LBRACKET + Optional(EXTRAS_LIST) + RBRACKET)("extras")
55
+
56
+ VERSION_PEP440 = Regex(Specifier._regex_str, re.VERBOSE | re.IGNORECASE)
57
+ VERSION_LEGACY = Regex(LegacySpecifier._regex_str, re.VERBOSE | re.IGNORECASE)
58
+
59
+ VERSION_ONE = VERSION_PEP440 ^ VERSION_LEGACY
60
+ VERSION_MANY = Combine(
61
+ VERSION_ONE + ZeroOrMore(COMMA + VERSION_ONE), joinString=",", adjacent=False
62
+ )("_raw_spec")
63
+ _VERSION_SPEC = Optional((LPAREN + VERSION_MANY + RPAREN) | VERSION_MANY)
64
+ _VERSION_SPEC.setParseAction(lambda s, l, t: t._raw_spec or "")
65
+
66
+ VERSION_SPEC = originalTextFor(_VERSION_SPEC)("specifier")
67
+ VERSION_SPEC.setParseAction(lambda s, l, t: t[1])
68
+
69
+ MARKER_EXPR = originalTextFor(MARKER_EXPR())("marker")
70
+ MARKER_EXPR.setParseAction(
71
+ lambda s, l, t: Marker(s[t._original_start : t._original_end])
72
+ )
73
+ MARKER_SEPARATOR = SEMICOLON
74
+ MARKER = MARKER_SEPARATOR + MARKER_EXPR
75
+
76
+ VERSION_AND_MARKER = VERSION_SPEC + Optional(MARKER)
77
+ URL_AND_MARKER = URL + Optional(MARKER)
78
+
79
+ NAMED_REQUIREMENT = NAME + Optional(EXTRAS) + (URL_AND_MARKER | VERSION_AND_MARKER)
80
+
81
+ REQUIREMENT = stringStart + NAMED_REQUIREMENT + stringEnd
82
+ # pkg_resources.extern.pyparsing isn't thread safe during initialization, so we do it eagerly, see
83
+ # issue #104
84
+ REQUIREMENT.parseString("x[]")
85
+
86
+
87
+ class Requirement:
88
+ """Parse a requirement.
89
+
90
+ Parse a given requirement string into its parts, such as name, specifier,
91
+ URL, and extras. Raises InvalidRequirement on a badly-formed requirement
92
+ string.
93
+ """
94
+
95
+ # TODO: Can we test whether something is contained within a requirement?
96
+ # If so how do we do that? Do we need to test against the _name_ of
97
+ # the thing as well as the version? What about the markers?
98
+ # TODO: Can we normalize the name and extra name?
99
+
100
+ def __init__(self, requirement_string: str) -> None:
101
+ try:
102
+ req = REQUIREMENT.parseString(requirement_string)
103
+ except ParseException as e:
104
+ raise InvalidRequirement(
105
+ f'Parse error at "{ requirement_string[e.loc : e.loc + 8]!r}": {e.msg}'
106
+ )
107
+
108
+ self.name: str = req.name
109
+ if req.url:
110
+ parsed_url = urllib.parse.urlparse(req.url)
111
+ if parsed_url.scheme == "file":
112
+ if urllib.parse.urlunparse(parsed_url) != req.url:
113
+ raise InvalidRequirement("Invalid URL given")
114
+ elif not (parsed_url.scheme and parsed_url.netloc) or (
115
+ not parsed_url.scheme and not parsed_url.netloc
116
+ ):
117
+ raise InvalidRequirement(f"Invalid URL: {req.url}")
118
+ self.url: TOptional[str] = req.url
119
+ else:
120
+ self.url = None
121
+ self.extras: Set[str] = set(req.extras.asList() if req.extras else [])
122
+ self.specifier: SpecifierSet = SpecifierSet(req.specifier)
123
+ self.marker: TOptional[Marker] = req.marker if req.marker else None
124
+
125
+ def __str__(self) -> str:
126
+ parts: List[str] = [self.name]
127
+
128
+ if self.extras:
129
+ formatted_extras = ",".join(sorted(self.extras))
130
+ parts.append(f"[{formatted_extras}]")
131
+
132
+ if self.specifier:
133
+ parts.append(str(self.specifier))
134
+
135
+ if self.url:
136
+ parts.append(f"@ {self.url}")
137
+ if self.marker:
138
+ parts.append(" ")
139
+
140
+ if self.marker:
141
+ parts.append(f"; {self.marker}")
142
+
143
+ return "".join(parts)
144
+
145
+ def __repr__(self) -> str:
146
+ return f"<Requirement('{self}')>"
venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/specifiers.py ADDED
@@ -0,0 +1,828 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ import abc
6
+ import functools
7
+ import itertools
8
+ import re
9
+ import warnings
10
+ from typing import (
11
+ Callable,
12
+ Dict,
13
+ Iterable,
14
+ Iterator,
15
+ List,
16
+ Optional,
17
+ Pattern,
18
+ Set,
19
+ Tuple,
20
+ TypeVar,
21
+ Union,
22
+ )
23
+
24
+ from .utils import canonicalize_version
25
+ from .version import LegacyVersion, Version, parse
26
+
27
+ ParsedVersion = Union[Version, LegacyVersion]
28
+ UnparsedVersion = Union[Version, LegacyVersion, str]
29
+ VersionTypeVar = TypeVar("VersionTypeVar", bound=UnparsedVersion)
30
+ CallableOperator = Callable[[ParsedVersion, str], bool]
31
+
32
+
33
+ class InvalidSpecifier(ValueError):
34
+ """
35
+ An invalid specifier was found, users should refer to PEP 440.
36
+ """
37
+
38
+
39
+ class BaseSpecifier(metaclass=abc.ABCMeta):
40
+ @abc.abstractmethod
41
+ def __str__(self) -> str:
42
+ """
43
+ Returns the str representation of this Specifier like object. This
44
+ should be representative of the Specifier itself.
45
+ """
46
+
47
+ @abc.abstractmethod
48
+ def __hash__(self) -> int:
49
+ """
50
+ Returns a hash value for this Specifier like object.
51
+ """
52
+
53
+ @abc.abstractmethod
54
+ def __eq__(self, other: object) -> bool:
55
+ """
56
+ Returns a boolean representing whether or not the two Specifier like
57
+ objects are equal.
58
+ """
59
+
60
+ @abc.abstractmethod
61
+ def __ne__(self, other: object) -> bool:
62
+ """
63
+ Returns a boolean representing whether or not the two Specifier like
64
+ objects are not equal.
65
+ """
66
+
67
+ @abc.abstractproperty
68
+ def prereleases(self) -> Optional[bool]:
69
+ """
70
+ Returns whether or not pre-releases as a whole are allowed by this
71
+ specifier.
72
+ """
73
+
74
+ @prereleases.setter
75
+ def prereleases(self, value: bool) -> None:
76
+ """
77
+ Sets whether or not pre-releases as a whole are allowed by this
78
+ specifier.
79
+ """
80
+
81
+ @abc.abstractmethod
82
+ def contains(self, item: str, prereleases: Optional[bool] = None) -> bool:
83
+ """
84
+ Determines if the given item is contained within this specifier.
85
+ """
86
+
87
+ @abc.abstractmethod
88
+ def filter(
89
+ self, iterable: Iterable[VersionTypeVar], prereleases: Optional[bool] = None
90
+ ) -> Iterable[VersionTypeVar]:
91
+ """
92
+ Takes an iterable of items and filters them so that only items which
93
+ are contained within this specifier are allowed in it.
94
+ """
95
+
96
+
97
+ class _IndividualSpecifier(BaseSpecifier):
98
+
99
+ _operators: Dict[str, str] = {}
100
+ _regex: Pattern[str]
101
+
102
+ def __init__(self, spec: str = "", prereleases: Optional[bool] = None) -> None:
103
+ match = self._regex.search(spec)
104
+ if not match:
105
+ raise InvalidSpecifier(f"Invalid specifier: '{spec}'")
106
+
107
+ self._spec: Tuple[str, str] = (
108
+ match.group("operator").strip(),
109
+ match.group("version").strip(),
110
+ )
111
+
112
+ # Store whether or not this Specifier should accept prereleases
113
+ self._prereleases = prereleases
114
+
115
+ def __repr__(self) -> str:
116
+ pre = (
117
+ f", prereleases={self.prereleases!r}"
118
+ if self._prereleases is not None
119
+ else ""
120
+ )
121
+
122
+ return "<{}({!r}{})>".format(self.__class__.__name__, str(self), pre)
123
+
124
+ def __str__(self) -> str:
125
+ return "{}{}".format(*self._spec)
126
+
127
+ @property
128
+ def _canonical_spec(self) -> Tuple[str, str]:
129
+ return self._spec[0], canonicalize_version(self._spec[1])
130
+
131
+ def __hash__(self) -> int:
132
+ return hash(self._canonical_spec)
133
+
134
+ def __eq__(self, other: object) -> bool:
135
+ if isinstance(other, str):
136
+ try:
137
+ other = self.__class__(str(other))
138
+ except InvalidSpecifier:
139
+ return NotImplemented
140
+ elif not isinstance(other, self.__class__):
141
+ return NotImplemented
142
+
143
+ return self._canonical_spec == other._canonical_spec
144
+
145
+ def __ne__(self, other: object) -> bool:
146
+ if isinstance(other, str):
147
+ try:
148
+ other = self.__class__(str(other))
149
+ except InvalidSpecifier:
150
+ return NotImplemented
151
+ elif not isinstance(other, self.__class__):
152
+ return NotImplemented
153
+
154
+ return self._spec != other._spec
155
+
156
+ def _get_operator(self, op: str) -> CallableOperator:
157
+ operator_callable: CallableOperator = getattr(
158
+ self, f"_compare_{self._operators[op]}"
159
+ )
160
+ return operator_callable
161
+
162
+ def _coerce_version(self, version: UnparsedVersion) -> ParsedVersion:
163
+ if not isinstance(version, (LegacyVersion, Version)):
164
+ version = parse(version)
165
+ return version
166
+
167
+ @property
168
+ def operator(self) -> str:
169
+ return self._spec[0]
170
+
171
+ @property
172
+ def version(self) -> str:
173
+ return self._spec[1]
174
+
175
+ @property
176
+ def prereleases(self) -> Optional[bool]:
177
+ return self._prereleases
178
+
179
+ @prereleases.setter
180
+ def prereleases(self, value: bool) -> None:
181
+ self._prereleases = value
182
+
183
+ def __contains__(self, item: str) -> bool:
184
+ return self.contains(item)
185
+
186
+ def contains(
187
+ self, item: UnparsedVersion, prereleases: Optional[bool] = None
188
+ ) -> bool:
189
+
190
+ # Determine if prereleases are to be allowed or not.
191
+ if prereleases is None:
192
+ prereleases = self.prereleases
193
+
194
+ # Normalize item to a Version or LegacyVersion, this allows us to have
195
+ # a shortcut for ``"2.0" in Specifier(">=2")
196
+ normalized_item = self._coerce_version(item)
197
+
198
+ # Determine if we should be supporting prereleases in this specifier
199
+ # or not, if we do not support prereleases than we can short circuit
200
+ # logic if this version is a prereleases.
201
+ if normalized_item.is_prerelease and not prereleases:
202
+ return False
203
+
204
+ # Actually do the comparison to determine if this item is contained
205
+ # within this Specifier or not.
206
+ operator_callable: CallableOperator = self._get_operator(self.operator)
207
+ return operator_callable(normalized_item, self.version)
208
+
209
+ def filter(
210
+ self, iterable: Iterable[VersionTypeVar], prereleases: Optional[bool] = None
211
+ ) -> Iterable[VersionTypeVar]:
212
+
213
+ yielded = False
214
+ found_prereleases = []
215
+
216
+ kw = {"prereleases": prereleases if prereleases is not None else True}
217
+
218
+ # Attempt to iterate over all the values in the iterable and if any of
219
+ # them match, yield them.
220
+ for version in iterable:
221
+ parsed_version = self._coerce_version(version)
222
+
223
+ if self.contains(parsed_version, **kw):
224
+ # If our version is a prerelease, and we were not set to allow
225
+ # prereleases, then we'll store it for later in case nothing
226
+ # else matches this specifier.
227
+ if parsed_version.is_prerelease and not (
228
+ prereleases or self.prereleases
229
+ ):
230
+ found_prereleases.append(version)
231
+ # Either this is not a prerelease, or we should have been
232
+ # accepting prereleases from the beginning.
233
+ else:
234
+ yielded = True
235
+ yield version
236
+
237
+ # Now that we've iterated over everything, determine if we've yielded
238
+ # any values, and if we have not and we have any prereleases stored up
239
+ # then we will go ahead and yield the prereleases.
240
+ if not yielded and found_prereleases:
241
+ for version in found_prereleases:
242
+ yield version
243
+
244
+
245
+ class LegacySpecifier(_IndividualSpecifier):
246
+
247
+ _regex_str = r"""
248
+ (?P<operator>(==|!=|<=|>=|<|>))
249
+ \s*
250
+ (?P<version>
251
+ [^,;\s)]* # Since this is a "legacy" specifier, and the version
252
+ # string can be just about anything, we match everything
253
+ # except for whitespace, a semi-colon for marker support,
254
+ # a closing paren since versions can be enclosed in
255
+ # them, and a comma since it's a version separator.
256
+ )
257
+ """
258
+
259
+ _regex = re.compile(r"^\s*" + _regex_str + r"\s*$", re.VERBOSE | re.IGNORECASE)
260
+
261
+ _operators = {
262
+ "==": "equal",
263
+ "!=": "not_equal",
264
+ "<=": "less_than_equal",
265
+ ">=": "greater_than_equal",
266
+ "<": "less_than",
267
+ ">": "greater_than",
268
+ }
269
+
270
+ def __init__(self, spec: str = "", prereleases: Optional[bool] = None) -> None:
271
+ super().__init__(spec, prereleases)
272
+
273
+ warnings.warn(
274
+ "Creating a LegacyVersion has been deprecated and will be "
275
+ "removed in the next major release",
276
+ DeprecationWarning,
277
+ )
278
+
279
+ def _coerce_version(self, version: UnparsedVersion) -> LegacyVersion:
280
+ if not isinstance(version, LegacyVersion):
281
+ version = LegacyVersion(str(version))
282
+ return version
283
+
284
+ def _compare_equal(self, prospective: LegacyVersion, spec: str) -> bool:
285
+ return prospective == self._coerce_version(spec)
286
+
287
+ def _compare_not_equal(self, prospective: LegacyVersion, spec: str) -> bool:
288
+ return prospective != self._coerce_version(spec)
289
+
290
+ def _compare_less_than_equal(self, prospective: LegacyVersion, spec: str) -> bool:
291
+ return prospective <= self._coerce_version(spec)
292
+
293
+ def _compare_greater_than_equal(
294
+ self, prospective: LegacyVersion, spec: str
295
+ ) -> bool:
296
+ return prospective >= self._coerce_version(spec)
297
+
298
+ def _compare_less_than(self, prospective: LegacyVersion, spec: str) -> bool:
299
+ return prospective < self._coerce_version(spec)
300
+
301
+ def _compare_greater_than(self, prospective: LegacyVersion, spec: str) -> bool:
302
+ return prospective > self._coerce_version(spec)
303
+
304
+
305
+ def _require_version_compare(
306
+ fn: Callable[["Specifier", ParsedVersion, str], bool]
307
+ ) -> Callable[["Specifier", ParsedVersion, str], bool]:
308
+ @functools.wraps(fn)
309
+ def wrapped(self: "Specifier", prospective: ParsedVersion, spec: str) -> bool:
310
+ if not isinstance(prospective, Version):
311
+ return False
312
+ return fn(self, prospective, spec)
313
+
314
+ return wrapped
315
+
316
+
317
+ class Specifier(_IndividualSpecifier):
318
+
319
+ _regex_str = r"""
320
+ (?P<operator>(~=|==|!=|<=|>=|<|>|===))
321
+ (?P<version>
322
+ (?:
323
+ # The identity operators allow for an escape hatch that will
324
+ # do an exact string match of the version you wish to install.
325
+ # This will not be parsed by PEP 440 and we cannot determine
326
+ # any semantic meaning from it. This operator is discouraged
327
+ # but included entirely as an escape hatch.
328
+ (?<====) # Only match for the identity operator
329
+ \s*
330
+ [^\s]* # We just match everything, except for whitespace
331
+ # since we are only testing for strict identity.
332
+ )
333
+ |
334
+ (?:
335
+ # The (non)equality operators allow for wild card and local
336
+ # versions to be specified so we have to define these two
337
+ # operators separately to enable that.
338
+ (?<===|!=) # Only match for equals and not equals
339
+
340
+ \s*
341
+ v?
342
+ (?:[0-9]+!)? # epoch
343
+ [0-9]+(?:\.[0-9]+)* # release
344
+ (?: # pre release
345
+ [-_\.]?
346
+ (a|b|c|rc|alpha|beta|pre|preview)
347
+ [-_\.]?
348
+ [0-9]*
349
+ )?
350
+ (?: # post release
351
+ (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
352
+ )?
353
+
354
+ # You cannot use a wild card and a dev or local version
355
+ # together so group them with a | and make them optional.
356
+ (?:
357
+ (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release
358
+ (?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local
359
+ |
360
+ \.\* # Wild card syntax of .*
361
+ )?
362
+ )
363
+ |
364
+ (?:
365
+ # The compatible operator requires at least two digits in the
366
+ # release segment.
367
+ (?<=~=) # Only match for the compatible operator
368
+
369
+ \s*
370
+ v?
371
+ (?:[0-9]+!)? # epoch
372
+ [0-9]+(?:\.[0-9]+)+ # release (We have a + instead of a *)
373
+ (?: # pre release
374
+ [-_\.]?
375
+ (a|b|c|rc|alpha|beta|pre|preview)
376
+ [-_\.]?
377
+ [0-9]*
378
+ )?
379
+ (?: # post release
380
+ (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
381
+ )?
382
+ (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release
383
+ )
384
+ |
385
+ (?:
386
+ # All other operators only allow a sub set of what the
387
+ # (non)equality operators do. Specifically they do not allow
388
+ # local versions to be specified nor do they allow the prefix
389
+ # matching wild cards.
390
+ (?<!==|!=|~=) # We have special cases for these
391
+ # operators so we want to make sure they
392
+ # don't match here.
393
+
394
+ \s*
395
+ v?
396
+ (?:[0-9]+!)? # epoch
397
+ [0-9]+(?:\.[0-9]+)* # release
398
+ (?: # pre release
399
+ [-_\.]?
400
+ (a|b|c|rc|alpha|beta|pre|preview)
401
+ [-_\.]?
402
+ [0-9]*
403
+ )?
404
+ (?: # post release
405
+ (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
406
+ )?
407
+ (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release
408
+ )
409
+ )
410
+ """
411
+
412
+ _regex = re.compile(r"^\s*" + _regex_str + r"\s*$", re.VERBOSE | re.IGNORECASE)
413
+
414
+ _operators = {
415
+ "~=": "compatible",
416
+ "==": "equal",
417
+ "!=": "not_equal",
418
+ "<=": "less_than_equal",
419
+ ">=": "greater_than_equal",
420
+ "<": "less_than",
421
+ ">": "greater_than",
422
+ "===": "arbitrary",
423
+ }
424
+
425
+ @_require_version_compare
426
+ def _compare_compatible(self, prospective: ParsedVersion, spec: str) -> bool:
427
+
428
+ # Compatible releases have an equivalent combination of >= and ==. That
429
+ # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to
430
+ # implement this in terms of the other specifiers instead of
431
+ # implementing it ourselves. The only thing we need to do is construct
432
+ # the other specifiers.
433
+
434
+ # We want everything but the last item in the version, but we want to
435
+ # ignore suffix segments.
436
+ prefix = ".".join(
437
+ list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1]
438
+ )
439
+
440
+ # Add the prefix notation to the end of our string
441
+ prefix += ".*"
442
+
443
+ return self._get_operator(">=")(prospective, spec) and self._get_operator("==")(
444
+ prospective, prefix
445
+ )
446
+
447
+ @_require_version_compare
448
+ def _compare_equal(self, prospective: ParsedVersion, spec: str) -> bool:
449
+
450
+ # We need special logic to handle prefix matching
451
+ if spec.endswith(".*"):
452
+ # In the case of prefix matching we want to ignore local segment.
453
+ prospective = Version(prospective.public)
454
+ # Split the spec out by dots, and pretend that there is an implicit
455
+ # dot in between a release segment and a pre-release segment.
456
+ split_spec = _version_split(spec[:-2]) # Remove the trailing .*
457
+
458
+ # Split the prospective version out by dots, and pretend that there
459
+ # is an implicit dot in between a release segment and a pre-release
460
+ # segment.
461
+ split_prospective = _version_split(str(prospective))
462
+
463
+ # Shorten the prospective version to be the same length as the spec
464
+ # so that we can determine if the specifier is a prefix of the
465
+ # prospective version or not.
466
+ shortened_prospective = split_prospective[: len(split_spec)]
467
+
468
+ # Pad out our two sides with zeros so that they both equal the same
469
+ # length.
470
+ padded_spec, padded_prospective = _pad_version(
471
+ split_spec, shortened_prospective
472
+ )
473
+
474
+ return padded_prospective == padded_spec
475
+ else:
476
+ # Convert our spec string into a Version
477
+ spec_version = Version(spec)
478
+
479
+ # If the specifier does not have a local segment, then we want to
480
+ # act as if the prospective version also does not have a local
481
+ # segment.
482
+ if not spec_version.local:
483
+ prospective = Version(prospective.public)
484
+
485
+ return prospective == spec_version
486
+
487
+ @_require_version_compare
488
+ def _compare_not_equal(self, prospective: ParsedVersion, spec: str) -> bool:
489
+ return not self._compare_equal(prospective, spec)
490
+
491
+ @_require_version_compare
492
+ def _compare_less_than_equal(self, prospective: ParsedVersion, spec: str) -> bool:
493
+
494
+ # NB: Local version identifiers are NOT permitted in the version
495
+ # specifier, so local version labels can be universally removed from
496
+ # the prospective version.
497
+ return Version(prospective.public) <= Version(spec)
498
+
499
+ @_require_version_compare
500
+ def _compare_greater_than_equal(
501
+ self, prospective: ParsedVersion, spec: str
502
+ ) -> bool:
503
+
504
+ # NB: Local version identifiers are NOT permitted in the version
505
+ # specifier, so local version labels can be universally removed from
506
+ # the prospective version.
507
+ return Version(prospective.public) >= Version(spec)
508
+
509
+ @_require_version_compare
510
+ def _compare_less_than(self, prospective: ParsedVersion, spec_str: str) -> bool:
511
+
512
+ # Convert our spec to a Version instance, since we'll want to work with
513
+ # it as a version.
514
+ spec = Version(spec_str)
515
+
516
+ # Check to see if the prospective version is less than the spec
517
+ # version. If it's not we can short circuit and just return False now
518
+ # instead of doing extra unneeded work.
519
+ if not prospective < spec:
520
+ return False
521
+
522
+ # This special case is here so that, unless the specifier itself
523
+ # includes is a pre-release version, that we do not accept pre-release
524
+ # versions for the version mentioned in the specifier (e.g. <3.1 should
525
+ # not match 3.1.dev0, but should match 3.0.dev0).
526
+ if not spec.is_prerelease and prospective.is_prerelease:
527
+ if Version(prospective.base_version) == Version(spec.base_version):
528
+ return False
529
+
530
+ # If we've gotten to here, it means that prospective version is both
531
+ # less than the spec version *and* it's not a pre-release of the same
532
+ # version in the spec.
533
+ return True
534
+
535
+ @_require_version_compare
536
+ def _compare_greater_than(self, prospective: ParsedVersion, spec_str: str) -> bool:
537
+
538
+ # Convert our spec to a Version instance, since we'll want to work with
539
+ # it as a version.
540
+ spec = Version(spec_str)
541
+
542
+ # Check to see if the prospective version is greater than the spec
543
+ # version. If it's not we can short circuit and just return False now
544
+ # instead of doing extra unneeded work.
545
+ if not prospective > spec:
546
+ return False
547
+
548
+ # This special case is here so that, unless the specifier itself
549
+ # includes is a post-release version, that we do not accept
550
+ # post-release versions for the version mentioned in the specifier
551
+ # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0).
552
+ if not spec.is_postrelease and prospective.is_postrelease:
553
+ if Version(prospective.base_version) == Version(spec.base_version):
554
+ return False
555
+
556
+ # Ensure that we do not allow a local version of the version mentioned
557
+ # in the specifier, which is technically greater than, to match.
558
+ if prospective.local is not None:
559
+ if Version(prospective.base_version) == Version(spec.base_version):
560
+ return False
561
+
562
+ # If we've gotten to here, it means that prospective version is both
563
+ # greater than the spec version *and* it's not a pre-release of the
564
+ # same version in the spec.
565
+ return True
566
+
567
+ def _compare_arbitrary(self, prospective: Version, spec: str) -> bool:
568
+ return str(prospective).lower() == str(spec).lower()
569
+
570
+ @property
571
+ def prereleases(self) -> bool:
572
+
573
+ # If there is an explicit prereleases set for this, then we'll just
574
+ # blindly use that.
575
+ if self._prereleases is not None:
576
+ return self._prereleases
577
+
578
+ # Look at all of our specifiers and determine if they are inclusive
579
+ # operators, and if they are if they are including an explicit
580
+ # prerelease.
581
+ operator, version = self._spec
582
+ if operator in ["==", ">=", "<=", "~=", "==="]:
583
+ # The == specifier can include a trailing .*, if it does we
584
+ # want to remove before parsing.
585
+ if operator == "==" and version.endswith(".*"):
586
+ version = version[:-2]
587
+
588
+ # Parse the version, and if it is a pre-release than this
589
+ # specifier allows pre-releases.
590
+ if parse(version).is_prerelease:
591
+ return True
592
+
593
+ return False
594
+
595
+ @prereleases.setter
596
+ def prereleases(self, value: bool) -> None:
597
+ self._prereleases = value
598
+
599
+
600
+ _prefix_regex = re.compile(r"^([0-9]+)((?:a|b|c|rc)[0-9]+)$")
601
+
602
+
603
+ def _version_split(version: str) -> List[str]:
604
+ result: List[str] = []
605
+ for item in version.split("."):
606
+ match = _prefix_regex.search(item)
607
+ if match:
608
+ result.extend(match.groups())
609
+ else:
610
+ result.append(item)
611
+ return result
612
+
613
+
614
+ def _is_not_suffix(segment: str) -> bool:
615
+ return not any(
616
+ segment.startswith(prefix) for prefix in ("dev", "a", "b", "rc", "post")
617
+ )
618
+
619
+
620
+ def _pad_version(left: List[str], right: List[str]) -> Tuple[List[str], List[str]]:
621
+ left_split, right_split = [], []
622
+
623
+ # Get the release segment of our versions
624
+ left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left)))
625
+ right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right)))
626
+
627
+ # Get the rest of our versions
628
+ left_split.append(left[len(left_split[0]) :])
629
+ right_split.append(right[len(right_split[0]) :])
630
+
631
+ # Insert our padding
632
+ left_split.insert(1, ["0"] * max(0, len(right_split[0]) - len(left_split[0])))
633
+ right_split.insert(1, ["0"] * max(0, len(left_split[0]) - len(right_split[0])))
634
+
635
+ return (list(itertools.chain(*left_split)), list(itertools.chain(*right_split)))
636
+
637
+
638
+ class SpecifierSet(BaseSpecifier):
639
+ def __init__(
640
+ self, specifiers: str = "", prereleases: Optional[bool] = None
641
+ ) -> None:
642
+
643
+ # Split on , to break each individual specifier into it's own item, and
644
+ # strip each item to remove leading/trailing whitespace.
645
+ split_specifiers = [s.strip() for s in specifiers.split(",") if s.strip()]
646
+
647
+ # Parsed each individual specifier, attempting first to make it a
648
+ # Specifier and falling back to a LegacySpecifier.
649
+ parsed: Set[_IndividualSpecifier] = set()
650
+ for specifier in split_specifiers:
651
+ try:
652
+ parsed.add(Specifier(specifier))
653
+ except InvalidSpecifier:
654
+ parsed.add(LegacySpecifier(specifier))
655
+
656
+ # Turn our parsed specifiers into a frozen set and save them for later.
657
+ self._specs = frozenset(parsed)
658
+
659
+ # Store our prereleases value so we can use it later to determine if
660
+ # we accept prereleases or not.
661
+ self._prereleases = prereleases
662
+
663
+ def __repr__(self) -> str:
664
+ pre = (
665
+ f", prereleases={self.prereleases!r}"
666
+ if self._prereleases is not None
667
+ else ""
668
+ )
669
+
670
+ return "<SpecifierSet({!r}{})>".format(str(self), pre)
671
+
672
+ def __str__(self) -> str:
673
+ return ",".join(sorted(str(s) for s in self._specs))
674
+
675
+ def __hash__(self) -> int:
676
+ return hash(self._specs)
677
+
678
+ def __and__(self, other: Union["SpecifierSet", str]) -> "SpecifierSet":
679
+ if isinstance(other, str):
680
+ other = SpecifierSet(other)
681
+ elif not isinstance(other, SpecifierSet):
682
+ return NotImplemented
683
+
684
+ specifier = SpecifierSet()
685
+ specifier._specs = frozenset(self._specs | other._specs)
686
+
687
+ if self._prereleases is None and other._prereleases is not None:
688
+ specifier._prereleases = other._prereleases
689
+ elif self._prereleases is not None and other._prereleases is None:
690
+ specifier._prereleases = self._prereleases
691
+ elif self._prereleases == other._prereleases:
692
+ specifier._prereleases = self._prereleases
693
+ else:
694
+ raise ValueError(
695
+ "Cannot combine SpecifierSets with True and False prerelease "
696
+ "overrides."
697
+ )
698
+
699
+ return specifier
700
+
701
+ def __eq__(self, other: object) -> bool:
702
+ if isinstance(other, (str, _IndividualSpecifier)):
703
+ other = SpecifierSet(str(other))
704
+ elif not isinstance(other, SpecifierSet):
705
+ return NotImplemented
706
+
707
+ return self._specs == other._specs
708
+
709
+ def __ne__(self, other: object) -> bool:
710
+ if isinstance(other, (str, _IndividualSpecifier)):
711
+ other = SpecifierSet(str(other))
712
+ elif not isinstance(other, SpecifierSet):
713
+ return NotImplemented
714
+
715
+ return self._specs != other._specs
716
+
717
+ def __len__(self) -> int:
718
+ return len(self._specs)
719
+
720
+ def __iter__(self) -> Iterator[_IndividualSpecifier]:
721
+ return iter(self._specs)
722
+
723
+ @property
724
+ def prereleases(self) -> Optional[bool]:
725
+
726
+ # If we have been given an explicit prerelease modifier, then we'll
727
+ # pass that through here.
728
+ if self._prereleases is not None:
729
+ return self._prereleases
730
+
731
+ # If we don't have any specifiers, and we don't have a forced value,
732
+ # then we'll just return None since we don't know if this should have
733
+ # pre-releases or not.
734
+ if not self._specs:
735
+ return None
736
+
737
+ # Otherwise we'll see if any of the given specifiers accept
738
+ # prereleases, if any of them do we'll return True, otherwise False.
739
+ return any(s.prereleases for s in self._specs)
740
+
741
+ @prereleases.setter
742
+ def prereleases(self, value: bool) -> None:
743
+ self._prereleases = value
744
+
745
+ def __contains__(self, item: UnparsedVersion) -> bool:
746
+ return self.contains(item)
747
+
748
+ def contains(
749
+ self, item: UnparsedVersion, prereleases: Optional[bool] = None
750
+ ) -> bool:
751
+
752
+ # Ensure that our item is a Version or LegacyVersion instance.
753
+ if not isinstance(item, (LegacyVersion, Version)):
754
+ item = parse(item)
755
+
756
+ # Determine if we're forcing a prerelease or not, if we're not forcing
757
+ # one for this particular filter call, then we'll use whatever the
758
+ # SpecifierSet thinks for whether or not we should support prereleases.
759
+ if prereleases is None:
760
+ prereleases = self.prereleases
761
+
762
+ # We can determine if we're going to allow pre-releases by looking to
763
+ # see if any of the underlying items supports them. If none of them do
764
+ # and this item is a pre-release then we do not allow it and we can
765
+ # short circuit that here.
766
+ # Note: This means that 1.0.dev1 would not be contained in something
767
+ # like >=1.0.devabc however it would be in >=1.0.debabc,>0.0.dev0
768
+ if not prereleases and item.is_prerelease:
769
+ return False
770
+
771
+ # We simply dispatch to the underlying specs here to make sure that the
772
+ # given version is contained within all of them.
773
+ # Note: This use of all() here means that an empty set of specifiers
774
+ # will always return True, this is an explicit design decision.
775
+ return all(s.contains(item, prereleases=prereleases) for s in self._specs)
776
+
777
+ def filter(
778
+ self, iterable: Iterable[VersionTypeVar], prereleases: Optional[bool] = None
779
+ ) -> Iterable[VersionTypeVar]:
780
+
781
+ # Determine if we're forcing a prerelease or not, if we're not forcing
782
+ # one for this particular filter call, then we'll use whatever the
783
+ # SpecifierSet thinks for whether or not we should support prereleases.
784
+ if prereleases is None:
785
+ prereleases = self.prereleases
786
+
787
+ # If we have any specifiers, then we want to wrap our iterable in the
788
+ # filter method for each one, this will act as a logical AND amongst
789
+ # each specifier.
790
+ if self._specs:
791
+ for spec in self._specs:
792
+ iterable = spec.filter(iterable, prereleases=bool(prereleases))
793
+ return iterable
794
+ # If we do not have any specifiers, then we need to have a rough filter
795
+ # which will filter out any pre-releases, unless there are no final
796
+ # releases, and which will filter out LegacyVersion in general.
797
+ else:
798
+ filtered: List[VersionTypeVar] = []
799
+ found_prereleases: List[VersionTypeVar] = []
800
+
801
+ item: UnparsedVersion
802
+ parsed_version: Union[Version, LegacyVersion]
803
+
804
+ for item in iterable:
805
+ # Ensure that we some kind of Version class for this item.
806
+ if not isinstance(item, (LegacyVersion, Version)):
807
+ parsed_version = parse(item)
808
+ else:
809
+ parsed_version = item
810
+
811
+ # Filter out any item which is parsed as a LegacyVersion
812
+ if isinstance(parsed_version, LegacyVersion):
813
+ continue
814
+
815
+ # Store any item which is a pre-release for later unless we've
816
+ # already found a final version or we are accepting prereleases
817
+ if parsed_version.is_prerelease and not prereleases:
818
+ if not filtered:
819
+ found_prereleases.append(item)
820
+ else:
821
+ filtered.append(item)
822
+
823
+ # If we've found no items except for pre-releases, then we'll go
824
+ # ahead and use the pre-releases
825
+ if not filtered and found_prereleases and prereleases is None:
826
+ return found_prereleases
827
+
828
+ return filtered
venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/utils.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ import re
6
+ from typing import FrozenSet, NewType, Tuple, Union, cast
7
+
8
+ from .tags import Tag, parse_tag
9
+ from .version import InvalidVersion, Version
10
+
11
+ BuildTag = Union[Tuple[()], Tuple[int, str]]
12
+ NormalizedName = NewType("NormalizedName", str)
13
+
14
+
15
+ class InvalidWheelFilename(ValueError):
16
+ """
17
+ An invalid wheel filename was found, users should refer to PEP 427.
18
+ """
19
+
20
+
21
+ class InvalidSdistFilename(ValueError):
22
+ """
23
+ An invalid sdist filename was found, users should refer to the packaging user guide.
24
+ """
25
+
26
+
27
+ _canonicalize_regex = re.compile(r"[-_.]+")
28
+ # PEP 427: The build number must start with a digit.
29
+ _build_tag_regex = re.compile(r"(\d+)(.*)")
30
+
31
+
32
+ def canonicalize_name(name: str) -> NormalizedName:
33
+ # This is taken from PEP 503.
34
+ value = _canonicalize_regex.sub("-", name).lower()
35
+ return cast(NormalizedName, value)
36
+
37
+
38
+ def canonicalize_version(version: Union[Version, str]) -> str:
39
+ """
40
+ This is very similar to Version.__str__, but has one subtle difference
41
+ with the way it handles the release segment.
42
+ """
43
+ if isinstance(version, str):
44
+ try:
45
+ parsed = Version(version)
46
+ except InvalidVersion:
47
+ # Legacy versions cannot be normalized
48
+ return version
49
+ else:
50
+ parsed = version
51
+
52
+ parts = []
53
+
54
+ # Epoch
55
+ if parsed.epoch != 0:
56
+ parts.append(f"{parsed.epoch}!")
57
+
58
+ # Release segment
59
+ # NB: This strips trailing '.0's to normalize
60
+ parts.append(re.sub(r"(\.0)+$", "", ".".join(str(x) for x in parsed.release)))
61
+
62
+ # Pre-release
63
+ if parsed.pre is not None:
64
+ parts.append("".join(str(x) for x in parsed.pre))
65
+
66
+ # Post-release
67
+ if parsed.post is not None:
68
+ parts.append(f".post{parsed.post}")
69
+
70
+ # Development release
71
+ if parsed.dev is not None:
72
+ parts.append(f".dev{parsed.dev}")
73
+
74
+ # Local version segment
75
+ if parsed.local is not None:
76
+ parts.append(f"+{parsed.local}")
77
+
78
+ return "".join(parts)
79
+
80
+
81
+ def parse_wheel_filename(
82
+ filename: str,
83
+ ) -> Tuple[NormalizedName, Version, BuildTag, FrozenSet[Tag]]:
84
+ if not filename.endswith(".whl"):
85
+ raise InvalidWheelFilename(
86
+ f"Invalid wheel filename (extension must be '.whl'): {filename}"
87
+ )
88
+
89
+ filename = filename[:-4]
90
+ dashes = filename.count("-")
91
+ if dashes not in (4, 5):
92
+ raise InvalidWheelFilename(
93
+ f"Invalid wheel filename (wrong number of parts): {filename}"
94
+ )
95
+
96
+ parts = filename.split("-", dashes - 2)
97
+ name_part = parts[0]
98
+ # See PEP 427 for the rules on escaping the project name
99
+ if "__" in name_part or re.match(r"^[\w\d._]*$", name_part, re.UNICODE) is None:
100
+ raise InvalidWheelFilename(f"Invalid project name: {filename}")
101
+ name = canonicalize_name(name_part)
102
+ version = Version(parts[1])
103
+ if dashes == 5:
104
+ build_part = parts[2]
105
+ build_match = _build_tag_regex.match(build_part)
106
+ if build_match is None:
107
+ raise InvalidWheelFilename(
108
+ f"Invalid build number: {build_part} in '{filename}'"
109
+ )
110
+ build = cast(BuildTag, (int(build_match.group(1)), build_match.group(2)))
111
+ else:
112
+ build = ()
113
+ tags = parse_tag(parts[-1])
114
+ return (name, version, build, tags)
115
+
116
+
117
+ def parse_sdist_filename(filename: str) -> Tuple[NormalizedName, Version]:
118
+ if filename.endswith(".tar.gz"):
119
+ file_stem = filename[: -len(".tar.gz")]
120
+ elif filename.endswith(".zip"):
121
+ file_stem = filename[: -len(".zip")]
122
+ else:
123
+ raise InvalidSdistFilename(
124
+ f"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):"
125
+ f" {filename}"
126
+ )
127
+
128
+ # We are requiring a PEP 440 version, which cannot contain dashes,
129
+ # so we split on the last dash.
130
+ name_part, sep, version_part = file_stem.rpartition("-")
131
+ if not sep:
132
+ raise InvalidSdistFilename(f"Invalid sdist filename: {filename}")
133
+
134
+ name = canonicalize_name(name_part)
135
+ version = Version(version_part)
136
+ return (name, version)
venv/lib/python3.10/site-packages/pkg_resources/_vendor/packaging/version.py ADDED
@@ -0,0 +1,504 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ import collections
6
+ import itertools
7
+ import re
8
+ import warnings
9
+ from typing import Callable, Iterator, List, Optional, SupportsInt, Tuple, Union
10
+
11
+ from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType
12
+
13
+ __all__ = ["parse", "Version", "LegacyVersion", "InvalidVersion", "VERSION_PATTERN"]
14
+
15
+ InfiniteTypes = Union[InfinityType, NegativeInfinityType]
16
+ PrePostDevType = Union[InfiniteTypes, Tuple[str, int]]
17
+ SubLocalType = Union[InfiniteTypes, int, str]
18
+ LocalType = Union[
19
+ NegativeInfinityType,
20
+ Tuple[
21
+ Union[
22
+ SubLocalType,
23
+ Tuple[SubLocalType, str],
24
+ Tuple[NegativeInfinityType, SubLocalType],
25
+ ],
26
+ ...,
27
+ ],
28
+ ]
29
+ CmpKey = Tuple[
30
+ int, Tuple[int, ...], PrePostDevType, PrePostDevType, PrePostDevType, LocalType
31
+ ]
32
+ LegacyCmpKey = Tuple[int, Tuple[str, ...]]
33
+ VersionComparisonMethod = Callable[
34
+ [Union[CmpKey, LegacyCmpKey], Union[CmpKey, LegacyCmpKey]], bool
35
+ ]
36
+
37
+ _Version = collections.namedtuple(
38
+ "_Version", ["epoch", "release", "dev", "pre", "post", "local"]
39
+ )
40
+
41
+
42
+ def parse(version: str) -> Union["LegacyVersion", "Version"]:
43
+ """
44
+ Parse the given version string and return either a :class:`Version` object
45
+ or a :class:`LegacyVersion` object depending on if the given version is
46
+ a valid PEP 440 version or a legacy version.
47
+ """
48
+ try:
49
+ return Version(version)
50
+ except InvalidVersion:
51
+ return LegacyVersion(version)
52
+
53
+
54
+ class InvalidVersion(ValueError):
55
+ """
56
+ An invalid version was found, users should refer to PEP 440.
57
+ """
58
+
59
+
60
+ class _BaseVersion:
61
+ _key: Union[CmpKey, LegacyCmpKey]
62
+
63
+ def __hash__(self) -> int:
64
+ return hash(self._key)
65
+
66
+ # Please keep the duplicated `isinstance` check
67
+ # in the six comparisons hereunder
68
+ # unless you find a way to avoid adding overhead function calls.
69
+ def __lt__(self, other: "_BaseVersion") -> bool:
70
+ if not isinstance(other, _BaseVersion):
71
+ return NotImplemented
72
+
73
+ return self._key < other._key
74
+
75
+ def __le__(self, other: "_BaseVersion") -> bool:
76
+ if not isinstance(other, _BaseVersion):
77
+ return NotImplemented
78
+
79
+ return self._key <= other._key
80
+
81
+ def __eq__(self, other: object) -> bool:
82
+ if not isinstance(other, _BaseVersion):
83
+ return NotImplemented
84
+
85
+ return self._key == other._key
86
+
87
+ def __ge__(self, other: "_BaseVersion") -> bool:
88
+ if not isinstance(other, _BaseVersion):
89
+ return NotImplemented
90
+
91
+ return self._key >= other._key
92
+
93
+ def __gt__(self, other: "_BaseVersion") -> bool:
94
+ if not isinstance(other, _BaseVersion):
95
+ return NotImplemented
96
+
97
+ return self._key > other._key
98
+
99
+ def __ne__(self, other: object) -> bool:
100
+ if not isinstance(other, _BaseVersion):
101
+ return NotImplemented
102
+
103
+ return self._key != other._key
104
+
105
+
106
+ class LegacyVersion(_BaseVersion):
107
+ def __init__(self, version: str) -> None:
108
+ self._version = str(version)
109
+ self._key = _legacy_cmpkey(self._version)
110
+
111
+ warnings.warn(
112
+ "Creating a LegacyVersion has been deprecated and will be "
113
+ "removed in the next major release",
114
+ DeprecationWarning,
115
+ )
116
+
117
+ def __str__(self) -> str:
118
+ return self._version
119
+
120
+ def __repr__(self) -> str:
121
+ return f"<LegacyVersion('{self}')>"
122
+
123
+ @property
124
+ def public(self) -> str:
125
+ return self._version
126
+
127
+ @property
128
+ def base_version(self) -> str:
129
+ return self._version
130
+
131
+ @property
132
+ def epoch(self) -> int:
133
+ return -1
134
+
135
+ @property
136
+ def release(self) -> None:
137
+ return None
138
+
139
+ @property
140
+ def pre(self) -> None:
141
+ return None
142
+
143
+ @property
144
+ def post(self) -> None:
145
+ return None
146
+
147
+ @property
148
+ def dev(self) -> None:
149
+ return None
150
+
151
+ @property
152
+ def local(self) -> None:
153
+ return None
154
+
155
+ @property
156
+ def is_prerelease(self) -> bool:
157
+ return False
158
+
159
+ @property
160
+ def is_postrelease(self) -> bool:
161
+ return False
162
+
163
+ @property
164
+ def is_devrelease(self) -> bool:
165
+ return False
166
+
167
+
168
+ _legacy_version_component_re = re.compile(r"(\d+ | [a-z]+ | \.| -)", re.VERBOSE)
169
+
170
+ _legacy_version_replacement_map = {
171
+ "pre": "c",
172
+ "preview": "c",
173
+ "-": "final-",
174
+ "rc": "c",
175
+ "dev": "@",
176
+ }
177
+
178
+
179
+ def _parse_version_parts(s: str) -> Iterator[str]:
180
+ for part in _legacy_version_component_re.split(s):
181
+ part = _legacy_version_replacement_map.get(part, part)
182
+
183
+ if not part or part == ".":
184
+ continue
185
+
186
+ if part[:1] in "0123456789":
187
+ # pad for numeric comparison
188
+ yield part.zfill(8)
189
+ else:
190
+ yield "*" + part
191
+
192
+ # ensure that alpha/beta/candidate are before final
193
+ yield "*final"
194
+
195
+
196
+ def _legacy_cmpkey(version: str) -> LegacyCmpKey:
197
+
198
+ # We hardcode an epoch of -1 here. A PEP 440 version can only have a epoch
199
+ # greater than or equal to 0. This will effectively put the LegacyVersion,
200
+ # which uses the defacto standard originally implemented by setuptools,
201
+ # as before all PEP 440 versions.
202
+ epoch = -1
203
+
204
+ # This scheme is taken from pkg_resources.parse_version setuptools prior to
205
+ # it's adoption of the packaging library.
206
+ parts: List[str] = []
207
+ for part in _parse_version_parts(version.lower()):
208
+ if part.startswith("*"):
209
+ # remove "-" before a prerelease tag
210
+ if part < "*final":
211
+ while parts and parts[-1] == "*final-":
212
+ parts.pop()
213
+
214
+ # remove trailing zeros from each series of numeric parts
215
+ while parts and parts[-1] == "00000000":
216
+ parts.pop()
217
+
218
+ parts.append(part)
219
+
220
+ return epoch, tuple(parts)
221
+
222
+
223
+ # Deliberately not anchored to the start and end of the string, to make it
224
+ # easier for 3rd party code to reuse
225
+ VERSION_PATTERN = r"""
226
+ v?
227
+ (?:
228
+ (?:(?P<epoch>[0-9]+)!)? # epoch
229
+ (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
230
+ (?P<pre> # pre-release
231
+ [-_\.]?
232
+ (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
233
+ [-_\.]?
234
+ (?P<pre_n>[0-9]+)?
235
+ )?
236
+ (?P<post> # post release
237
+ (?:-(?P<post_n1>[0-9]+))
238
+ |
239
+ (?:
240
+ [-_\.]?
241
+ (?P<post_l>post|rev|r)
242
+ [-_\.]?
243
+ (?P<post_n2>[0-9]+)?
244
+ )
245
+ )?
246
+ (?P<dev> # dev release
247
+ [-_\.]?
248
+ (?P<dev_l>dev)
249
+ [-_\.]?
250
+ (?P<dev_n>[0-9]+)?
251
+ )?
252
+ )
253
+ (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version
254
+ """
255
+
256
+
257
+ class Version(_BaseVersion):
258
+
259
+ _regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE)
260
+
261
+ def __init__(self, version: str) -> None:
262
+
263
+ # Validate the version and parse it into pieces
264
+ match = self._regex.search(version)
265
+ if not match:
266
+ raise InvalidVersion(f"Invalid version: '{version}'")
267
+
268
+ # Store the parsed out pieces of the version
269
+ self._version = _Version(
270
+ epoch=int(match.group("epoch")) if match.group("epoch") else 0,
271
+ release=tuple(int(i) for i in match.group("release").split(".")),
272
+ pre=_parse_letter_version(match.group("pre_l"), match.group("pre_n")),
273
+ post=_parse_letter_version(
274
+ match.group("post_l"), match.group("post_n1") or match.group("post_n2")
275
+ ),
276
+ dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")),
277
+ local=_parse_local_version(match.group("local")),
278
+ )
279
+
280
+ # Generate a key which will be used for sorting
281
+ self._key = _cmpkey(
282
+ self._version.epoch,
283
+ self._version.release,
284
+ self._version.pre,
285
+ self._version.post,
286
+ self._version.dev,
287
+ self._version.local,
288
+ )
289
+
290
+ def __repr__(self) -> str:
291
+ return f"<Version('{self}')>"
292
+
293
+ def __str__(self) -> str:
294
+ parts = []
295
+
296
+ # Epoch
297
+ if self.epoch != 0:
298
+ parts.append(f"{self.epoch}!")
299
+
300
+ # Release segment
301
+ parts.append(".".join(str(x) for x in self.release))
302
+
303
+ # Pre-release
304
+ if self.pre is not None:
305
+ parts.append("".join(str(x) for x in self.pre))
306
+
307
+ # Post-release
308
+ if self.post is not None:
309
+ parts.append(f".post{self.post}")
310
+
311
+ # Development release
312
+ if self.dev is not None:
313
+ parts.append(f".dev{self.dev}")
314
+
315
+ # Local version segment
316
+ if self.local is not None:
317
+ parts.append(f"+{self.local}")
318
+
319
+ return "".join(parts)
320
+
321
+ @property
322
+ def epoch(self) -> int:
323
+ _epoch: int = self._version.epoch
324
+ return _epoch
325
+
326
+ @property
327
+ def release(self) -> Tuple[int, ...]:
328
+ _release: Tuple[int, ...] = self._version.release
329
+ return _release
330
+
331
+ @property
332
+ def pre(self) -> Optional[Tuple[str, int]]:
333
+ _pre: Optional[Tuple[str, int]] = self._version.pre
334
+ return _pre
335
+
336
+ @property
337
+ def post(self) -> Optional[int]:
338
+ return self._version.post[1] if self._version.post else None
339
+
340
+ @property
341
+ def dev(self) -> Optional[int]:
342
+ return self._version.dev[1] if self._version.dev else None
343
+
344
+ @property
345
+ def local(self) -> Optional[str]:
346
+ if self._version.local:
347
+ return ".".join(str(x) for x in self._version.local)
348
+ else:
349
+ return None
350
+
351
+ @property
352
+ def public(self) -> str:
353
+ return str(self).split("+", 1)[0]
354
+
355
+ @property
356
+ def base_version(self) -> str:
357
+ parts = []
358
+
359
+ # Epoch
360
+ if self.epoch != 0:
361
+ parts.append(f"{self.epoch}!")
362
+
363
+ # Release segment
364
+ parts.append(".".join(str(x) for x in self.release))
365
+
366
+ return "".join(parts)
367
+
368
+ @property
369
+ def is_prerelease(self) -> bool:
370
+ return self.dev is not None or self.pre is not None
371
+
372
+ @property
373
+ def is_postrelease(self) -> bool:
374
+ return self.post is not None
375
+
376
+ @property
377
+ def is_devrelease(self) -> bool:
378
+ return self.dev is not None
379
+
380
+ @property
381
+ def major(self) -> int:
382
+ return self.release[0] if len(self.release) >= 1 else 0
383
+
384
+ @property
385
+ def minor(self) -> int:
386
+ return self.release[1] if len(self.release) >= 2 else 0
387
+
388
+ @property
389
+ def micro(self) -> int:
390
+ return self.release[2] if len(self.release) >= 3 else 0
391
+
392
+
393
+ def _parse_letter_version(
394
+ letter: str, number: Union[str, bytes, SupportsInt]
395
+ ) -> Optional[Tuple[str, int]]:
396
+
397
+ if letter:
398
+ # We consider there to be an implicit 0 in a pre-release if there is
399
+ # not a numeral associated with it.
400
+ if number is None:
401
+ number = 0
402
+
403
+ # We normalize any letters to their lower case form
404
+ letter = letter.lower()
405
+
406
+ # We consider some words to be alternate spellings of other words and
407
+ # in those cases we want to normalize the spellings to our preferred
408
+ # spelling.
409
+ if letter == "alpha":
410
+ letter = "a"
411
+ elif letter == "beta":
412
+ letter = "b"
413
+ elif letter in ["c", "pre", "preview"]:
414
+ letter = "rc"
415
+ elif letter in ["rev", "r"]:
416
+ letter = "post"
417
+
418
+ return letter, int(number)
419
+ if not letter and number:
420
+ # We assume if we are given a number, but we are not given a letter
421
+ # then this is using the implicit post release syntax (e.g. 1.0-1)
422
+ letter = "post"
423
+
424
+ return letter, int(number)
425
+
426
+ return None
427
+
428
+
429
+ _local_version_separators = re.compile(r"[\._-]")
430
+
431
+
432
+ def _parse_local_version(local: str) -> Optional[LocalType]:
433
+ """
434
+ Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
435
+ """
436
+ if local is not None:
437
+ return tuple(
438
+ part.lower() if not part.isdigit() else int(part)
439
+ for part in _local_version_separators.split(local)
440
+ )
441
+ return None
442
+
443
+
444
+ def _cmpkey(
445
+ epoch: int,
446
+ release: Tuple[int, ...],
447
+ pre: Optional[Tuple[str, int]],
448
+ post: Optional[Tuple[str, int]],
449
+ dev: Optional[Tuple[str, int]],
450
+ local: Optional[Tuple[SubLocalType]],
451
+ ) -> CmpKey:
452
+
453
+ # When we compare a release version, we want to compare it with all of the
454
+ # trailing zeros removed. So we'll use a reverse the list, drop all the now
455
+ # leading zeros until we come to something non zero, then take the rest
456
+ # re-reverse it back into the correct order and make it a tuple and use
457
+ # that for our sorting key.
458
+ _release = tuple(
459
+ reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))
460
+ )
461
+
462
+ # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
463
+ # We'll do this by abusing the pre segment, but we _only_ want to do this
464
+ # if there is not a pre or a post segment. If we have one of those then
465
+ # the normal sorting rules will handle this case correctly.
466
+ if pre is None and post is None and dev is not None:
467
+ _pre: PrePostDevType = NegativeInfinity
468
+ # Versions without a pre-release (except as noted above) should sort after
469
+ # those with one.
470
+ elif pre is None:
471
+ _pre = Infinity
472
+ else:
473
+ _pre = pre
474
+
475
+ # Versions without a post segment should sort before those with one.
476
+ if post is None:
477
+ _post: PrePostDevType = NegativeInfinity
478
+
479
+ else:
480
+ _post = post
481
+
482
+ # Versions without a development segment should sort after those with one.
483
+ if dev is None:
484
+ _dev: PrePostDevType = Infinity
485
+
486
+ else:
487
+ _dev = dev
488
+
489
+ if local is None:
490
+ # Versions without a local segment should sort before those with one.
491
+ _local: LocalType = NegativeInfinity
492
+ else:
493
+ # Versions with a local segment need that segment parsed to implement
494
+ # the sorting rules in PEP440.
495
+ # - Alpha numeric segments sort before numeric segments
496
+ # - Alpha numeric segments sort lexicographically
497
+ # - Numeric segments sort numerically
498
+ # - Shorter versions sort before longer versions when the prefixes
499
+ # match exactly
500
+ _local = tuple(
501
+ (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local
502
+ )
503
+
504
+ return epoch, _release, _pre, _post, _dev, _local
venv/lib/python3.10/site-packages/pkg_resources/_vendor/pyparsing.py ADDED
The diff for this file is too large to render. See raw diff
 
venv/lib/python3.10/site-packages/pkg_resources/extern/__init__.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.util
2
+ import sys
3
+
4
+
5
+ class VendorImporter:
6
+ """
7
+ A PEP 302 meta path importer for finding optionally-vendored
8
+ or otherwise naturally-installed packages from root_name.
9
+ """
10
+
11
+ def __init__(self, root_name, vendored_names=(), vendor_pkg=None):
12
+ self.root_name = root_name
13
+ self.vendored_names = set(vendored_names)
14
+ self.vendor_pkg = vendor_pkg or root_name.replace('extern', '_vendor')
15
+
16
+ @property
17
+ def search_path(self):
18
+ """
19
+ Search first the vendor package then as a natural package.
20
+ """
21
+ yield self.vendor_pkg + '.'
22
+ yield ''
23
+
24
+ def _module_matches_namespace(self, fullname):
25
+ """Figure out if the target module is vendored."""
26
+ root, base, target = fullname.partition(self.root_name + '.')
27
+ return not root and any(map(target.startswith, self.vendored_names))
28
+
29
+ def load_module(self, fullname):
30
+ """
31
+ Iterate over the search path to locate and load fullname.
32
+ """
33
+ root, base, target = fullname.partition(self.root_name + '.')
34
+ for prefix in self.search_path:
35
+ try:
36
+ extant = prefix + target
37
+ __import__(extant)
38
+ mod = sys.modules[extant]
39
+ sys.modules[fullname] = mod
40
+ return mod
41
+ except ImportError:
42
+ pass
43
+ else:
44
+ raise ImportError(
45
+ "The '{target}' package is required; "
46
+ "normally this is bundled with this package so if you get "
47
+ "this warning, consult the packager of your "
48
+ "distribution.".format(**locals())
49
+ )
50
+
51
+ def create_module(self, spec):
52
+ return self.load_module(spec.name)
53
+
54
+ def exec_module(self, module):
55
+ pass
56
+
57
+ def find_spec(self, fullname, path=None, target=None):
58
+ """Return a module spec for vendored names."""
59
+ return (
60
+ importlib.util.spec_from_loader(fullname, self)
61
+ if self._module_matches_namespace(fullname) else None
62
+ )
63
+
64
+ def install(self):
65
+ """
66
+ Install this importer into sys.meta_path if not already present.
67
+ """
68
+ if self not in sys.meta_path:
69
+ sys.meta_path.append(self)
70
+
71
+
72
+ names = 'packaging', 'pyparsing', 'appdirs'
73
+ VendorImporter(__name__, names).install()
venv/lib/python3.10/site-packages/pkg_resources/extern/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.97 kB). View file
 
venv/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-source/__pycache__/setup.cpython-310.pyc ADDED
Binary file (385 Bytes). View file
 
venv/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-source/setup.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import setuptools
2
+ setuptools.setup(
3
+ name="my-test-package",
4
+ version="1.0",
5
+ zip_safe=True,
6
+ )
venv/lib/python3.10/site-packages/py.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # shim for pylib going away
2
+ # if pylib is installed this file will get skipped
3
+ # (`py/__init__.py` has higher precedence)
4
+ from __future__ import annotations
5
+
6
+ import sys
7
+
8
+ import _pytest._py.error as error
9
+ import _pytest._py.path as path
10
+
11
+
12
+ sys.modules["py.error"] = error
13
+ sys.modules["py.path"] = path
14
+
15
+ __all__ = ["error", "path"]
venv/lib/python3.10/site-packages/setuptools/__init__.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Extensions to the 'distutils' for large or complex distributions"""
2
+
3
+ from fnmatch import fnmatchcase
4
+ import functools
5
+ import os
6
+ import re
7
+
8
+ import _distutils_hack.override # noqa: F401
9
+
10
+ import distutils.core
11
+ from distutils.errors import DistutilsOptionError
12
+ from distutils.util import convert_path
13
+
14
+ from ._deprecation_warning import SetuptoolsDeprecationWarning
15
+
16
+ import setuptools.version
17
+ from setuptools.extension import Extension
18
+ from setuptools.dist import Distribution
19
+ from setuptools.depends import Require
20
+ from . import monkey
21
+
22
+
23
+ __all__ = [
24
+ 'setup',
25
+ 'Distribution',
26
+ 'Command',
27
+ 'Extension',
28
+ 'Require',
29
+ 'SetuptoolsDeprecationWarning',
30
+ 'find_packages',
31
+ 'find_namespace_packages',
32
+ ]
33
+
34
+ __version__ = setuptools.version.__version__
35
+
36
+ bootstrap_install_from = None
37
+
38
+
39
+ class PackageFinder:
40
+ """
41
+ Generate a list of all Python packages found within a directory
42
+ """
43
+
44
+ @classmethod
45
+ def find(cls, where='.', exclude=(), include=('*',)):
46
+ """Return a list all Python packages found within directory 'where'
47
+
48
+ 'where' is the root directory which will be searched for packages. It
49
+ should be supplied as a "cross-platform" (i.e. URL-style) path; it will
50
+ be converted to the appropriate local path syntax.
51
+
52
+ 'exclude' is a sequence of package names to exclude; '*' can be used
53
+ as a wildcard in the names, such that 'foo.*' will exclude all
54
+ subpackages of 'foo' (but not 'foo' itself).
55
+
56
+ 'include' is a sequence of package names to include. If it's
57
+ specified, only the named packages will be included. If it's not
58
+ specified, all found packages will be included. 'include' can contain
59
+ shell style wildcard patterns just like 'exclude'.
60
+ """
61
+
62
+ return list(
63
+ cls._find_packages_iter(
64
+ convert_path(where),
65
+ cls._build_filter('ez_setup', '*__pycache__', *exclude),
66
+ cls._build_filter(*include),
67
+ )
68
+ )
69
+
70
+ @classmethod
71
+ def _find_packages_iter(cls, where, exclude, include):
72
+ """
73
+ All the packages found in 'where' that pass the 'include' filter, but
74
+ not the 'exclude' filter.
75
+ """
76
+ for root, dirs, files in os.walk(where, followlinks=True):
77
+ # Copy dirs to iterate over it, then empty dirs.
78
+ all_dirs = dirs[:]
79
+ dirs[:] = []
80
+
81
+ for dir in all_dirs:
82
+ full_path = os.path.join(root, dir)
83
+ rel_path = os.path.relpath(full_path, where)
84
+ package = rel_path.replace(os.path.sep, '.')
85
+
86
+ # Skip directory trees that are not valid packages
87
+ if '.' in dir or not cls._looks_like_package(full_path):
88
+ continue
89
+
90
+ # Should this package be included?
91
+ if include(package) and not exclude(package):
92
+ yield package
93
+
94
+ # Keep searching subdirectories, as there may be more packages
95
+ # down there, even if the parent was excluded.
96
+ dirs.append(dir)
97
+
98
+ @staticmethod
99
+ def _looks_like_package(path):
100
+ """Does a directory look like a package?"""
101
+ return os.path.isfile(os.path.join(path, '__init__.py'))
102
+
103
+ @staticmethod
104
+ def _build_filter(*patterns):
105
+ """
106
+ Given a list of patterns, return a callable that will be true only if
107
+ the input matches at least one of the patterns.
108
+ """
109
+ return lambda name: any(fnmatchcase(name, pat=pat) for pat in patterns)
110
+
111
+
112
+ class PEP420PackageFinder(PackageFinder):
113
+ @staticmethod
114
+ def _looks_like_package(path):
115
+ return True
116
+
117
+
118
+ find_packages = PackageFinder.find
119
+ find_namespace_packages = PEP420PackageFinder.find
120
+
121
+
122
+ def _install_setup_requires(attrs):
123
+ # Note: do not use `setuptools.Distribution` directly, as
124
+ # our PEP 517 backend patch `distutils.core.Distribution`.
125
+ class MinimalDistribution(distutils.core.Distribution):
126
+ """
127
+ A minimal version of a distribution for supporting the
128
+ fetch_build_eggs interface.
129
+ """
130
+
131
+ def __init__(self, attrs):
132
+ _incl = 'dependency_links', 'setup_requires'
133
+ filtered = {k: attrs[k] for k in set(_incl) & set(attrs)}
134
+ distutils.core.Distribution.__init__(self, filtered)
135
+
136
+ def finalize_options(self):
137
+ """
138
+ Disable finalize_options to avoid building the working set.
139
+ Ref #2158.
140
+ """
141
+
142
+ dist = MinimalDistribution(attrs)
143
+
144
+ # Honor setup.cfg's options.
145
+ dist.parse_config_files(ignore_option_errors=True)
146
+ if dist.setup_requires:
147
+ dist.fetch_build_eggs(dist.setup_requires)
148
+
149
+
150
+ def setup(**attrs):
151
+ # Make sure we have any requirements needed to interpret 'attrs'.
152
+ _install_setup_requires(attrs)
153
+ return distutils.core.setup(**attrs)
154
+
155
+
156
+ setup.__doc__ = distutils.core.setup.__doc__
157
+
158
+
159
+ _Command = monkey.get_unpatched(distutils.core.Command)
160
+
161
+
162
+ class Command(_Command):
163
+ __doc__ = _Command.__doc__
164
+
165
+ command_consumes_arguments = False
166
+
167
+ def __init__(self, dist, **kw):
168
+ """
169
+ Construct the command for dist, updating
170
+ vars(self) with any keyword parameters.
171
+ """
172
+ _Command.__init__(self, dist)
173
+ vars(self).update(kw)
174
+
175
+ def _ensure_stringlike(self, option, what, default=None):
176
+ val = getattr(self, option)
177
+ if val is None:
178
+ setattr(self, option, default)
179
+ return default
180
+ elif not isinstance(val, str):
181
+ raise DistutilsOptionError(
182
+ "'%s' must be a %s (got `%s`)" % (option, what, val)
183
+ )
184
+ return val
185
+
186
+ def ensure_string_list(self, option):
187
+ r"""Ensure that 'option' is a list of strings. If 'option' is
188
+ currently a string, we split it either on /,\s*/ or /\s+/, so
189
+ "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
190
+ ["foo", "bar", "baz"].
191
+ """
192
+ val = getattr(self, option)
193
+ if val is None:
194
+ return
195
+ elif isinstance(val, str):
196
+ setattr(self, option, re.split(r',\s*|\s+', val))
197
+ else:
198
+ if isinstance(val, list):
199
+ ok = all(isinstance(v, str) for v in val)
200
+ else:
201
+ ok = False
202
+ if not ok:
203
+ raise DistutilsOptionError(
204
+ "'%s' must be a list of strings (got %r)" % (option, val)
205
+ )
206
+
207
+ def reinitialize_command(self, command, reinit_subcommands=0, **kw):
208
+ cmd = _Command.reinitialize_command(self, command, reinit_subcommands)
209
+ vars(cmd).update(kw)
210
+ return cmd
211
+
212
+
213
+ def _find_all_simple(path):
214
+ """
215
+ Find all files under 'path'
216
+ """
217
+ results = (
218
+ os.path.join(base, file)
219
+ for base, dirs, files in os.walk(path, followlinks=True)
220
+ for file in files
221
+ )
222
+ return filter(os.path.isfile, results)
223
+
224
+
225
+ def findall(dir=os.curdir):
226
+ """
227
+ Find all files under 'dir' and return the list of full filenames.
228
+ Unless dir is '.', return full filenames with dir prepended.
229
+ """
230
+ files = _find_all_simple(dir)
231
+ if dir == os.curdir:
232
+ make_rel = functools.partial(os.path.relpath, start=dir)
233
+ files = map(make_rel, files)
234
+ return list(files)
235
+
236
+
237
+ class sic(str):
238
+ """Treat this string as-is (https://en.wikipedia.org/wiki/Sic)"""
239
+
240
+
241
+ # Apply monkey patches
242
+ monkey.patch_all()
venv/lib/python3.10/site-packages/setuptools/_deprecation_warning.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ class SetuptoolsDeprecationWarning(Warning):
2
+ """
3
+ Base class for warning deprecations in ``setuptools``
4
+
5
+ This class is not derived from ``DeprecationWarning``, and as such is
6
+ visible by default.
7
+ """
venv/lib/python3.10/site-packages/setuptools/_imp.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Re-implementation of find_module and get_frozen_object
3
+ from the deprecated imp module.
4
+ """
5
+
6
+ import os
7
+ import importlib.util
8
+ import importlib.machinery
9
+
10
+ from .py34compat import module_from_spec
11
+
12
+
13
+ PY_SOURCE = 1
14
+ PY_COMPILED = 2
15
+ C_EXTENSION = 3
16
+ C_BUILTIN = 6
17
+ PY_FROZEN = 7
18
+
19
+
20
+ def find_spec(module, paths):
21
+ finder = (
22
+ importlib.machinery.PathFinder().find_spec
23
+ if isinstance(paths, list) else
24
+ importlib.util.find_spec
25
+ )
26
+ return finder(module, paths)
27
+
28
+
29
+ def find_module(module, paths=None):
30
+ """Just like 'imp.find_module()', but with package support"""
31
+ spec = find_spec(module, paths)
32
+ if spec is None:
33
+ raise ImportError("Can't find %s" % module)
34
+ if not spec.has_location and hasattr(spec, 'submodule_search_locations'):
35
+ spec = importlib.util.spec_from_loader('__init__.py', spec.loader)
36
+
37
+ kind = -1
38
+ file = None
39
+ static = isinstance(spec.loader, type)
40
+ if spec.origin == 'frozen' or static and issubclass(
41
+ spec.loader, importlib.machinery.FrozenImporter):
42
+ kind = PY_FROZEN
43
+ path = None # imp compabilty
44
+ suffix = mode = '' # imp compatibility
45
+ elif spec.origin == 'built-in' or static and issubclass(
46
+ spec.loader, importlib.machinery.BuiltinImporter):
47
+ kind = C_BUILTIN
48
+ path = None # imp compabilty
49
+ suffix = mode = '' # imp compatibility
50
+ elif spec.has_location:
51
+ path = spec.origin
52
+ suffix = os.path.splitext(path)[1]
53
+ mode = 'r' if suffix in importlib.machinery.SOURCE_SUFFIXES else 'rb'
54
+
55
+ if suffix in importlib.machinery.SOURCE_SUFFIXES:
56
+ kind = PY_SOURCE
57
+ elif suffix in importlib.machinery.BYTECODE_SUFFIXES:
58
+ kind = PY_COMPILED
59
+ elif suffix in importlib.machinery.EXTENSION_SUFFIXES:
60
+ kind = C_EXTENSION
61
+
62
+ if kind in {PY_SOURCE, PY_COMPILED}:
63
+ file = open(path, mode)
64
+ else:
65
+ path = None
66
+ suffix = mode = ''
67
+
68
+ return file, path, (suffix, mode, kind)
69
+
70
+
71
+ def get_frozen_object(module, paths=None):
72
+ spec = find_spec(module, paths)
73
+ if not spec:
74
+ raise ImportError("Can't find %s" % module)
75
+ return spec.loader.get_code(module)
76
+
77
+
78
+ def get_module(module, paths, info):
79
+ spec = find_spec(module, paths)
80
+ if not spec:
81
+ raise ImportError("Can't find %s" % module)
82
+ return module_from_spec(spec)
venv/lib/python3.10/site-packages/setuptools/archive_util.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utilities for extracting common archive formats"""
2
+
3
+ import zipfile
4
+ import tarfile
5
+ import os
6
+ import shutil
7
+ import posixpath
8
+ import contextlib
9
+ from distutils.errors import DistutilsError
10
+
11
+ from pkg_resources import ensure_directory
12
+
13
+ __all__ = [
14
+ "unpack_archive", "unpack_zipfile", "unpack_tarfile", "default_filter",
15
+ "UnrecognizedFormat", "extraction_drivers", "unpack_directory",
16
+ ]
17
+
18
+
19
+ class UnrecognizedFormat(DistutilsError):
20
+ """Couldn't recognize the archive type"""
21
+
22
+
23
+ def default_filter(src, dst):
24
+ """The default progress/filter callback; returns True for all files"""
25
+ return dst
26
+
27
+
28
+ def unpack_archive(
29
+ filename, extract_dir, progress_filter=default_filter,
30
+ drivers=None):
31
+ """Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat``
32
+
33
+ `progress_filter` is a function taking two arguments: a source path
34
+ internal to the archive ('/'-separated), and a filesystem path where it
35
+ will be extracted. The callback must return the desired extract path
36
+ (which may be the same as the one passed in), or else ``None`` to skip
37
+ that file or directory. The callback can thus be used to report on the
38
+ progress of the extraction, as well as to filter the items extracted or
39
+ alter their extraction paths.
40
+
41
+ `drivers`, if supplied, must be a non-empty sequence of functions with the
42
+ same signature as this function (minus the `drivers` argument), that raise
43
+ ``UnrecognizedFormat`` if they do not support extracting the designated
44
+ archive type. The `drivers` are tried in sequence until one is found that
45
+ does not raise an error, or until all are exhausted (in which case
46
+ ``UnrecognizedFormat`` is raised). If you do not supply a sequence of
47
+ drivers, the module's ``extraction_drivers`` constant will be used, which
48
+ means that ``unpack_zipfile`` and ``unpack_tarfile`` will be tried, in that
49
+ order.
50
+ """
51
+ for driver in drivers or extraction_drivers:
52
+ try:
53
+ driver(filename, extract_dir, progress_filter)
54
+ except UnrecognizedFormat:
55
+ continue
56
+ else:
57
+ return
58
+ else:
59
+ raise UnrecognizedFormat(
60
+ "Not a recognized archive type: %s" % filename
61
+ )
62
+
63
+
64
+ def unpack_directory(filename, extract_dir, progress_filter=default_filter):
65
+ """"Unpack" a directory, using the same interface as for archives
66
+
67
+ Raises ``UnrecognizedFormat`` if `filename` is not a directory
68
+ """
69
+ if not os.path.isdir(filename):
70
+ raise UnrecognizedFormat("%s is not a directory" % filename)
71
+
72
+ paths = {
73
+ filename: ('', extract_dir),
74
+ }
75
+ for base, dirs, files in os.walk(filename):
76
+ src, dst = paths[base]
77
+ for d in dirs:
78
+ paths[os.path.join(base, d)] = src + d + '/', os.path.join(dst, d)
79
+ for f in files:
80
+ target = os.path.join(dst, f)
81
+ target = progress_filter(src + f, target)
82
+ if not target:
83
+ # skip non-files
84
+ continue
85
+ ensure_directory(target)
86
+ f = os.path.join(base, f)
87
+ shutil.copyfile(f, target)
88
+ shutil.copystat(f, target)
89
+
90
+
91
+ def unpack_zipfile(filename, extract_dir, progress_filter=default_filter):
92
+ """Unpack zip `filename` to `extract_dir`
93
+
94
+ Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined
95
+ by ``zipfile.is_zipfile()``). See ``unpack_archive()`` for an explanation
96
+ of the `progress_filter` argument.
97
+ """
98
+
99
+ if not zipfile.is_zipfile(filename):
100
+ raise UnrecognizedFormat("%s is not a zip file" % (filename,))
101
+
102
+ with zipfile.ZipFile(filename) as z:
103
+ for info in z.infolist():
104
+ name = info.filename
105
+
106
+ # don't extract absolute paths or ones with .. in them
107
+ if name.startswith('/') or '..' in name.split('/'):
108
+ continue
109
+
110
+ target = os.path.join(extract_dir, *name.split('/'))
111
+ target = progress_filter(name, target)
112
+ if not target:
113
+ continue
114
+ if name.endswith('/'):
115
+ # directory
116
+ ensure_directory(target)
117
+ else:
118
+ # file
119
+ ensure_directory(target)
120
+ data = z.read(info.filename)
121
+ with open(target, 'wb') as f:
122
+ f.write(data)
123
+ unix_attributes = info.external_attr >> 16
124
+ if unix_attributes:
125
+ os.chmod(target, unix_attributes)
126
+
127
+
128
+ def _resolve_tar_file_or_dir(tar_obj, tar_member_obj):
129
+ """Resolve any links and extract link targets as normal files."""
130
+ while tar_member_obj is not None and (
131
+ tar_member_obj.islnk() or tar_member_obj.issym()):
132
+ linkpath = tar_member_obj.linkname
133
+ if tar_member_obj.issym():
134
+ base = posixpath.dirname(tar_member_obj.name)
135
+ linkpath = posixpath.join(base, linkpath)
136
+ linkpath = posixpath.normpath(linkpath)
137
+ tar_member_obj = tar_obj._getmember(linkpath)
138
+
139
+ is_file_or_dir = (
140
+ tar_member_obj is not None and
141
+ (tar_member_obj.isfile() or tar_member_obj.isdir())
142
+ )
143
+ if is_file_or_dir:
144
+ return tar_member_obj
145
+
146
+ raise LookupError('Got unknown file type')
147
+
148
+
149
+ def _iter_open_tar(tar_obj, extract_dir, progress_filter):
150
+ """Emit member-destination pairs from a tar archive."""
151
+ # don't do any chowning!
152
+ tar_obj.chown = lambda *args: None
153
+
154
+ with contextlib.closing(tar_obj):
155
+ for member in tar_obj:
156
+ name = member.name
157
+ # don't extract absolute paths or ones with .. in them
158
+ if name.startswith('/') or '..' in name.split('/'):
159
+ continue
160
+
161
+ prelim_dst = os.path.join(extract_dir, *name.split('/'))
162
+
163
+ try:
164
+ member = _resolve_tar_file_or_dir(tar_obj, member)
165
+ except LookupError:
166
+ continue
167
+
168
+ final_dst = progress_filter(name, prelim_dst)
169
+ if not final_dst:
170
+ continue
171
+
172
+ if final_dst.endswith(os.sep):
173
+ final_dst = final_dst[:-1]
174
+
175
+ yield member, final_dst
176
+
177
+
178
+ def unpack_tarfile(filename, extract_dir, progress_filter=default_filter):
179
+ """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`
180
+
181
+ Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined
182
+ by ``tarfile.open()``). See ``unpack_archive()`` for an explanation
183
+ of the `progress_filter` argument.
184
+ """
185
+ try:
186
+ tarobj = tarfile.open(filename)
187
+ except tarfile.TarError as e:
188
+ raise UnrecognizedFormat(
189
+ "%s is not a compressed or uncompressed tar file" % (filename,)
190
+ ) from e
191
+
192
+ for member, final_dst in _iter_open_tar(
193
+ tarobj, extract_dir, progress_filter,
194
+ ):
195
+ try:
196
+ # XXX Ugh
197
+ tarobj._extract_member(member, final_dst)
198
+ except tarfile.ExtractError:
199
+ # chown/chmod/mkfifo/mknode/makedev failed
200
+ pass
201
+
202
+ return True
203
+
204
+
205
+ extraction_drivers = unpack_directory, unpack_zipfile, unpack_tarfile
venv/lib/python3.10/site-packages/setuptools/build_meta.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A PEP 517 interface to setuptools
2
+
3
+ Previously, when a user or a command line tool (let's call it a "frontend")
4
+ needed to make a request of setuptools to take a certain action, for
5
+ example, generating a list of installation requirements, the frontend would
6
+ would call "setup.py egg_info" or "setup.py bdist_wheel" on the command line.
7
+
8
+ PEP 517 defines a different method of interfacing with setuptools. Rather
9
+ than calling "setup.py" directly, the frontend should:
10
+
11
+ 1. Set the current directory to the directory with a setup.py file
12
+ 2. Import this module into a safe python interpreter (one in which
13
+ setuptools can potentially set global variables or crash hard).
14
+ 3. Call one of the functions defined in PEP 517.
15
+
16
+ What each function does is defined in PEP 517. However, here is a "casual"
17
+ definition of the functions (this definition should not be relied on for
18
+ bug reports or API stability):
19
+
20
+ - `build_wheel`: build a wheel in the folder and return the basename
21
+ - `get_requires_for_build_wheel`: get the `setup_requires` to build
22
+ - `prepare_metadata_for_build_wheel`: get the `install_requires`
23
+ - `build_sdist`: build an sdist in the folder and return the basename
24
+ - `get_requires_for_build_sdist`: get the `setup_requires` to build
25
+
26
+ Again, this is not a formal definition! Just a "taste" of the module.
27
+ """
28
+
29
+ import io
30
+ import os
31
+ import sys
32
+ import tokenize
33
+ import shutil
34
+ import contextlib
35
+ import tempfile
36
+ import warnings
37
+
38
+ import setuptools
39
+ import distutils
40
+
41
+ from pkg_resources import parse_requirements
42
+
43
+ __all__ = ['get_requires_for_build_sdist',
44
+ 'get_requires_for_build_wheel',
45
+ 'prepare_metadata_for_build_wheel',
46
+ 'build_wheel',
47
+ 'build_sdist',
48
+ '__legacy__',
49
+ 'SetupRequirementsError']
50
+
51
+
52
+ class SetupRequirementsError(BaseException):
53
+ def __init__(self, specifiers):
54
+ self.specifiers = specifiers
55
+
56
+
57
+ class Distribution(setuptools.dist.Distribution):
58
+ def fetch_build_eggs(self, specifiers):
59
+ specifier_list = list(map(str, parse_requirements(specifiers)))
60
+
61
+ raise SetupRequirementsError(specifier_list)
62
+
63
+ @classmethod
64
+ @contextlib.contextmanager
65
+ def patch(cls):
66
+ """
67
+ Replace
68
+ distutils.dist.Distribution with this class
69
+ for the duration of this context.
70
+ """
71
+ orig = distutils.core.Distribution
72
+ distutils.core.Distribution = cls
73
+ try:
74
+ yield
75
+ finally:
76
+ distutils.core.Distribution = orig
77
+
78
+
79
+ @contextlib.contextmanager
80
+ def no_install_setup_requires():
81
+ """Temporarily disable installing setup_requires
82
+
83
+ Under PEP 517, the backend reports build dependencies to the frontend,
84
+ and the frontend is responsible for ensuring they're installed.
85
+ So setuptools (acting as a backend) should not try to install them.
86
+ """
87
+ orig = setuptools._install_setup_requires
88
+ setuptools._install_setup_requires = lambda attrs: None
89
+ try:
90
+ yield
91
+ finally:
92
+ setuptools._install_setup_requires = orig
93
+
94
+
95
+ def _get_immediate_subdirectories(a_dir):
96
+ return [name for name in os.listdir(a_dir)
97
+ if os.path.isdir(os.path.join(a_dir, name))]
98
+
99
+
100
+ def _file_with_extension(directory, extension):
101
+ matching = (
102
+ f for f in os.listdir(directory)
103
+ if f.endswith(extension)
104
+ )
105
+ try:
106
+ file, = matching
107
+ except ValueError:
108
+ raise ValueError(
109
+ 'No distribution was found. Ensure that `setup.py` '
110
+ 'is not empty and that it calls `setup()`.')
111
+ return file
112
+
113
+
114
+ def _open_setup_script(setup_script):
115
+ if not os.path.exists(setup_script):
116
+ # Supply a default setup.py
117
+ return io.StringIO(u"from setuptools import setup; setup()")
118
+
119
+ return getattr(tokenize, 'open', open)(setup_script)
120
+
121
+
122
+ @contextlib.contextmanager
123
+ def suppress_known_deprecation():
124
+ with warnings.catch_warnings():
125
+ warnings.filterwarnings('ignore', 'setup.py install is deprecated')
126
+ yield
127
+
128
+
129
+ class _BuildMetaBackend(object):
130
+
131
+ def _fix_config(self, config_settings):
132
+ config_settings = config_settings or {}
133
+ config_settings.setdefault('--global-option', [])
134
+ return config_settings
135
+
136
+ def _get_build_requires(self, config_settings, requirements):
137
+ config_settings = self._fix_config(config_settings)
138
+
139
+ sys.argv = sys.argv[:1] + ['egg_info'] + \
140
+ config_settings["--global-option"]
141
+ try:
142
+ with Distribution.patch():
143
+ self.run_setup()
144
+ except SetupRequirementsError as e:
145
+ requirements += e.specifiers
146
+
147
+ return requirements
148
+
149
+ def run_setup(self, setup_script='setup.py'):
150
+ # Note that we can reuse our build directory between calls
151
+ # Correctness comes first, then optimization later
152
+ __file__ = setup_script
153
+ __name__ = '__main__'
154
+
155
+ with _open_setup_script(__file__) as f:
156
+ code = f.read().replace(r'\r\n', r'\n')
157
+
158
+ exec(compile(code, __file__, 'exec'), locals())
159
+
160
+ def get_requires_for_build_wheel(self, config_settings=None):
161
+ config_settings = self._fix_config(config_settings)
162
+ return self._get_build_requires(
163
+ config_settings, requirements=['wheel'])
164
+
165
+ def get_requires_for_build_sdist(self, config_settings=None):
166
+ config_settings = self._fix_config(config_settings)
167
+ return self._get_build_requires(config_settings, requirements=[])
168
+
169
+ def prepare_metadata_for_build_wheel(self, metadata_directory,
170
+ config_settings=None):
171
+ sys.argv = sys.argv[:1] + [
172
+ 'dist_info', '--egg-base', metadata_directory]
173
+ with no_install_setup_requires():
174
+ self.run_setup()
175
+
176
+ dist_info_directory = metadata_directory
177
+ while True:
178
+ dist_infos = [f for f in os.listdir(dist_info_directory)
179
+ if f.endswith('.dist-info')]
180
+
181
+ if (
182
+ len(dist_infos) == 0 and
183
+ len(_get_immediate_subdirectories(dist_info_directory)) == 1
184
+ ):
185
+
186
+ dist_info_directory = os.path.join(
187
+ dist_info_directory, os.listdir(dist_info_directory)[0])
188
+ continue
189
+
190
+ assert len(dist_infos) == 1
191
+ break
192
+
193
+ # PEP 517 requires that the .dist-info directory be placed in the
194
+ # metadata_directory. To comply, we MUST copy the directory to the root
195
+ if dist_info_directory != metadata_directory:
196
+ shutil.move(
197
+ os.path.join(dist_info_directory, dist_infos[0]),
198
+ metadata_directory)
199
+ shutil.rmtree(dist_info_directory, ignore_errors=True)
200
+
201
+ return dist_infos[0]
202
+
203
+ def _build_with_temp_dir(self, setup_command, result_extension,
204
+ result_directory, config_settings):
205
+ config_settings = self._fix_config(config_settings)
206
+ result_directory = os.path.abspath(result_directory)
207
+
208
+ # Build in a temporary directory, then copy to the target.
209
+ os.makedirs(result_directory, exist_ok=True)
210
+ with tempfile.TemporaryDirectory(dir=result_directory) as tmp_dist_dir:
211
+ sys.argv = (sys.argv[:1] + setup_command +
212
+ ['--dist-dir', tmp_dist_dir] +
213
+ config_settings["--global-option"])
214
+ with no_install_setup_requires():
215
+ self.run_setup()
216
+
217
+ result_basename = _file_with_extension(
218
+ tmp_dist_dir, result_extension)
219
+ result_path = os.path.join(result_directory, result_basename)
220
+ if os.path.exists(result_path):
221
+ # os.rename will fail overwriting on non-Unix.
222
+ os.remove(result_path)
223
+ os.rename(os.path.join(tmp_dist_dir, result_basename), result_path)
224
+
225
+ return result_basename
226
+
227
+ def build_wheel(self, wheel_directory, config_settings=None,
228
+ metadata_directory=None):
229
+ with suppress_known_deprecation():
230
+ return self._build_with_temp_dir(['bdist_wheel'], '.whl',
231
+ wheel_directory, config_settings)
232
+
233
+ def build_sdist(self, sdist_directory, config_settings=None):
234
+ return self._build_with_temp_dir(['sdist', '--formats', 'gztar'],
235
+ '.tar.gz', sdist_directory,
236
+ config_settings)
237
+
238
+
239
+ class _BuildMetaLegacyBackend(_BuildMetaBackend):
240
+ """Compatibility backend for setuptools
241
+
242
+ This is a version of setuptools.build_meta that endeavors
243
+ to maintain backwards
244
+ compatibility with pre-PEP 517 modes of invocation. It
245
+ exists as a temporary
246
+ bridge between the old packaging mechanism and the new
247
+ packaging mechanism,
248
+ and will eventually be removed.
249
+ """
250
+ def run_setup(self, setup_script='setup.py'):
251
+ # In order to maintain compatibility with scripts assuming that
252
+ # the setup.py script is in a directory on the PYTHONPATH, inject
253
+ # '' into sys.path. (pypa/setuptools#1642)
254
+ sys_path = list(sys.path) # Save the original path
255
+
256
+ script_dir = os.path.dirname(os.path.abspath(setup_script))
257
+ if script_dir not in sys.path:
258
+ sys.path.insert(0, script_dir)
259
+
260
+ # Some setup.py scripts (e.g. in pygame and numpy) use sys.argv[0] to
261
+ # get the directory of the source code. They expect it to refer to the
262
+ # setup.py script.
263
+ sys_argv_0 = sys.argv[0]
264
+ sys.argv[0] = setup_script
265
+
266
+ try:
267
+ super(_BuildMetaLegacyBackend,
268
+ self).run_setup(setup_script=setup_script)
269
+ finally:
270
+ # While PEP 517 frontends should be calling each hook in a fresh
271
+ # subprocess according to the standard (and thus it should not be
272
+ # strictly necessary to restore the old sys.path), we'll restore
273
+ # the original path so that the path manipulation does not persist
274
+ # within the hook after run_setup is called.
275
+ sys.path[:] = sys_path
276
+ sys.argv[0] = sys_argv_0
277
+
278
+
279
+ # The primary backend
280
+ _BACKEND = _BuildMetaBackend()
281
+
282
+ get_requires_for_build_wheel = _BACKEND.get_requires_for_build_wheel
283
+ get_requires_for_build_sdist = _BACKEND.get_requires_for_build_sdist
284
+ prepare_metadata_for_build_wheel = _BACKEND.prepare_metadata_for_build_wheel
285
+ build_wheel = _BACKEND.build_wheel
286
+ build_sdist = _BACKEND.build_sdist
287
+
288
+
289
+ # The legacy backend
290
+ __legacy__ = _BuildMetaLegacyBackend()
venv/lib/python3.10/site-packages/setuptools/cli-32.exe ADDED
Binary file (65.5 kB). View file
 
venv/lib/python3.10/site-packages/setuptools/cli-64.exe ADDED
Binary file (74.8 kB). View file
 
venv/lib/python3.10/site-packages/setuptools/cli.exe ADDED
Binary file (65.5 kB). View file
 
venv/lib/python3.10/site-packages/setuptools/config.py ADDED
@@ -0,0 +1,751 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ast
2
+ import io
3
+ import os
4
+ import sys
5
+
6
+ import warnings
7
+ import functools
8
+ import importlib
9
+ from collections import defaultdict
10
+ from functools import partial
11
+ from functools import wraps
12
+ from glob import iglob
13
+ import contextlib
14
+
15
+ from distutils.errors import DistutilsOptionError, DistutilsFileError
16
+ from setuptools.extern.packaging.version import Version, InvalidVersion
17
+ from setuptools.extern.packaging.specifiers import SpecifierSet
18
+
19
+
20
+ class StaticModule:
21
+ """
22
+ Attempt to load the module by the name
23
+ """
24
+
25
+ def __init__(self, name):
26
+ spec = importlib.util.find_spec(name)
27
+ with open(spec.origin) as strm:
28
+ src = strm.read()
29
+ module = ast.parse(src)
30
+ vars(self).update(locals())
31
+ del self.self
32
+
33
+ def __getattr__(self, attr):
34
+ try:
35
+ return next(
36
+ ast.literal_eval(statement.value)
37
+ for statement in self.module.body
38
+ if isinstance(statement, ast.Assign)
39
+ for target in statement.targets
40
+ if isinstance(target, ast.Name) and target.id == attr
41
+ )
42
+ except Exception as e:
43
+ raise AttributeError(
44
+ "{self.name} has no attribute {attr}".format(**locals())
45
+ ) from e
46
+
47
+
48
+ @contextlib.contextmanager
49
+ def patch_path(path):
50
+ """
51
+ Add path to front of sys.path for the duration of the context.
52
+ """
53
+ try:
54
+ sys.path.insert(0, path)
55
+ yield
56
+ finally:
57
+ sys.path.remove(path)
58
+
59
+
60
+ def read_configuration(filepath, find_others=False, ignore_option_errors=False):
61
+ """Read given configuration file and returns options from it as a dict.
62
+
63
+ :param str|unicode filepath: Path to configuration file
64
+ to get options from.
65
+
66
+ :param bool find_others: Whether to search for other configuration files
67
+ which could be on in various places.
68
+
69
+ :param bool ignore_option_errors: Whether to silently ignore
70
+ options, values of which could not be resolved (e.g. due to exceptions
71
+ in directives such as file:, attr:, etc.).
72
+ If False exceptions are propagated as expected.
73
+
74
+ :rtype: dict
75
+ """
76
+ from setuptools.dist import Distribution, _Distribution
77
+
78
+ filepath = os.path.abspath(filepath)
79
+
80
+ if not os.path.isfile(filepath):
81
+ raise DistutilsFileError('Configuration file %s does not exist.' % filepath)
82
+
83
+ current_directory = os.getcwd()
84
+ os.chdir(os.path.dirname(filepath))
85
+
86
+ try:
87
+ dist = Distribution()
88
+
89
+ filenames = dist.find_config_files() if find_others else []
90
+ if filepath not in filenames:
91
+ filenames.append(filepath)
92
+
93
+ _Distribution.parse_config_files(dist, filenames=filenames)
94
+
95
+ handlers = parse_configuration(
96
+ dist, dist.command_options, ignore_option_errors=ignore_option_errors
97
+ )
98
+
99
+ finally:
100
+ os.chdir(current_directory)
101
+
102
+ return configuration_to_dict(handlers)
103
+
104
+
105
+ def _get_option(target_obj, key):
106
+ """
107
+ Given a target object and option key, get that option from
108
+ the target object, either through a get_{key} method or
109
+ from an attribute directly.
110
+ """
111
+ getter_name = 'get_{key}'.format(**locals())
112
+ by_attribute = functools.partial(getattr, target_obj, key)
113
+ getter = getattr(target_obj, getter_name, by_attribute)
114
+ return getter()
115
+
116
+
117
+ def configuration_to_dict(handlers):
118
+ """Returns configuration data gathered by given handlers as a dict.
119
+
120
+ :param list[ConfigHandler] handlers: Handlers list,
121
+ usually from parse_configuration()
122
+
123
+ :rtype: dict
124
+ """
125
+ config_dict = defaultdict(dict)
126
+
127
+ for handler in handlers:
128
+ for option in handler.set_options:
129
+ value = _get_option(handler.target_obj, option)
130
+ config_dict[handler.section_prefix][option] = value
131
+
132
+ return config_dict
133
+
134
+
135
+ def parse_configuration(distribution, command_options, ignore_option_errors=False):
136
+ """Performs additional parsing of configuration options
137
+ for a distribution.
138
+
139
+ Returns a list of used option handlers.
140
+
141
+ :param Distribution distribution:
142
+ :param dict command_options:
143
+ :param bool ignore_option_errors: Whether to silently ignore
144
+ options, values of which could not be resolved (e.g. due to exceptions
145
+ in directives such as file:, attr:, etc.).
146
+ If False exceptions are propagated as expected.
147
+ :rtype: list
148
+ """
149
+ options = ConfigOptionsHandler(distribution, command_options, ignore_option_errors)
150
+ options.parse()
151
+
152
+ meta = ConfigMetadataHandler(
153
+ distribution.metadata,
154
+ command_options,
155
+ ignore_option_errors,
156
+ distribution.package_dir,
157
+ )
158
+ meta.parse()
159
+
160
+ return meta, options
161
+
162
+
163
+ class ConfigHandler:
164
+ """Handles metadata supplied in configuration files."""
165
+
166
+ section_prefix = None
167
+ """Prefix for config sections handled by this handler.
168
+ Must be provided by class heirs.
169
+
170
+ """
171
+
172
+ aliases = {}
173
+ """Options aliases.
174
+ For compatibility with various packages. E.g.: d2to1 and pbr.
175
+ Note: `-` in keys is replaced with `_` by config parser.
176
+
177
+ """
178
+
179
+ def __init__(self, target_obj, options, ignore_option_errors=False):
180
+ sections = {}
181
+
182
+ section_prefix = self.section_prefix
183
+ for section_name, section_options in options.items():
184
+ if not section_name.startswith(section_prefix):
185
+ continue
186
+
187
+ section_name = section_name.replace(section_prefix, '').strip('.')
188
+ sections[section_name] = section_options
189
+
190
+ self.ignore_option_errors = ignore_option_errors
191
+ self.target_obj = target_obj
192
+ self.sections = sections
193
+ self.set_options = []
194
+
195
+ @property
196
+ def parsers(self):
197
+ """Metadata item name to parser function mapping."""
198
+ raise NotImplementedError(
199
+ '%s must provide .parsers property' % self.__class__.__name__
200
+ )
201
+
202
+ def __setitem__(self, option_name, value):
203
+ unknown = tuple()
204
+ target_obj = self.target_obj
205
+
206
+ # Translate alias into real name.
207
+ option_name = self.aliases.get(option_name, option_name)
208
+
209
+ current_value = getattr(target_obj, option_name, unknown)
210
+
211
+ if current_value is unknown:
212
+ raise KeyError(option_name)
213
+
214
+ if current_value:
215
+ # Already inhabited. Skipping.
216
+ return
217
+
218
+ skip_option = False
219
+ parser = self.parsers.get(option_name)
220
+ if parser:
221
+ try:
222
+ value = parser(value)
223
+
224
+ except Exception:
225
+ skip_option = True
226
+ if not self.ignore_option_errors:
227
+ raise
228
+
229
+ if skip_option:
230
+ return
231
+
232
+ setter = getattr(target_obj, 'set_%s' % option_name, None)
233
+ if setter is None:
234
+ setattr(target_obj, option_name, value)
235
+ else:
236
+ setter(value)
237
+
238
+ self.set_options.append(option_name)
239
+
240
+ @classmethod
241
+ def _parse_list(cls, value, separator=','):
242
+ """Represents value as a list.
243
+
244
+ Value is split either by separator (defaults to comma) or by lines.
245
+
246
+ :param value:
247
+ :param separator: List items separator character.
248
+ :rtype: list
249
+ """
250
+ if isinstance(value, list): # _get_parser_compound case
251
+ return value
252
+
253
+ if '\n' in value:
254
+ value = value.splitlines()
255
+ else:
256
+ value = value.split(separator)
257
+
258
+ return [chunk.strip() for chunk in value if chunk.strip()]
259
+
260
+ @classmethod
261
+ def _parse_list_glob(cls, value, separator=','):
262
+ """Equivalent to _parse_list() but expands any glob patterns using glob().
263
+
264
+ However, unlike with glob() calls, the results remain relative paths.
265
+
266
+ :param value:
267
+ :param separator: List items separator character.
268
+ :rtype: list
269
+ """
270
+ glob_characters = ('*', '?', '[', ']', '{', '}')
271
+ values = cls._parse_list(value, separator=separator)
272
+ expanded_values = []
273
+ for value in values:
274
+
275
+ # Has globby characters?
276
+ if any(char in value for char in glob_characters):
277
+ # then expand the glob pattern while keeping paths *relative*:
278
+ expanded_values.extend(sorted(
279
+ os.path.relpath(path, os.getcwd())
280
+ for path in iglob(os.path.abspath(value))))
281
+
282
+ else:
283
+ # take the value as-is:
284
+ expanded_values.append(value)
285
+
286
+ return expanded_values
287
+
288
+ @classmethod
289
+ def _parse_dict(cls, value):
290
+ """Represents value as a dict.
291
+
292
+ :param value:
293
+ :rtype: dict
294
+ """
295
+ separator = '='
296
+ result = {}
297
+ for line in cls._parse_list(value):
298
+ key, sep, val = line.partition(separator)
299
+ if sep != separator:
300
+ raise DistutilsOptionError(
301
+ 'Unable to parse option value to dict: %s' % value
302
+ )
303
+ result[key.strip()] = val.strip()
304
+
305
+ return result
306
+
307
+ @classmethod
308
+ def _parse_bool(cls, value):
309
+ """Represents value as boolean.
310
+
311
+ :param value:
312
+ :rtype: bool
313
+ """
314
+ value = value.lower()
315
+ return value in ('1', 'true', 'yes')
316
+
317
+ @classmethod
318
+ def _exclude_files_parser(cls, key):
319
+ """Returns a parser function to make sure field inputs
320
+ are not files.
321
+
322
+ Parses a value after getting the key so error messages are
323
+ more informative.
324
+
325
+ :param key:
326
+ :rtype: callable
327
+ """
328
+
329
+ def parser(value):
330
+ exclude_directive = 'file:'
331
+ if value.startswith(exclude_directive):
332
+ raise ValueError(
333
+ 'Only strings are accepted for the {0} field, '
334
+ 'files are not accepted'.format(key)
335
+ )
336
+ return value
337
+
338
+ return parser
339
+
340
+ @classmethod
341
+ def _parse_file(cls, value):
342
+ """Represents value as a string, allowing including text
343
+ from nearest files using `file:` directive.
344
+
345
+ Directive is sandboxed and won't reach anything outside
346
+ directory with setup.py.
347
+
348
+ Examples:
349
+ file: README.rst, CHANGELOG.md, src/file.txt
350
+
351
+ :param str value:
352
+ :rtype: str
353
+ """
354
+ include_directive = 'file:'
355
+
356
+ if not isinstance(value, str):
357
+ return value
358
+
359
+ if not value.startswith(include_directive):
360
+ return value
361
+
362
+ spec = value[len(include_directive) :]
363
+ filepaths = (os.path.abspath(path.strip()) for path in spec.split(','))
364
+ return '\n'.join(
365
+ cls._read_file(path)
366
+ for path in filepaths
367
+ if (cls._assert_local(path) or True) and os.path.isfile(path)
368
+ )
369
+
370
+ @staticmethod
371
+ def _assert_local(filepath):
372
+ if not filepath.startswith(os.getcwd()):
373
+ raise DistutilsOptionError('`file:` directive can not access %s' % filepath)
374
+
375
+ @staticmethod
376
+ def _read_file(filepath):
377
+ with io.open(filepath, encoding='utf-8') as f:
378
+ return f.read()
379
+
380
+ @classmethod
381
+ def _parse_attr(cls, value, package_dir=None):
382
+ """Represents value as a module attribute.
383
+
384
+ Examples:
385
+ attr: package.attr
386
+ attr: package.module.attr
387
+
388
+ :param str value:
389
+ :rtype: str
390
+ """
391
+ attr_directive = 'attr:'
392
+ if not value.startswith(attr_directive):
393
+ return value
394
+
395
+ attrs_path = value.replace(attr_directive, '').strip().split('.')
396
+ attr_name = attrs_path.pop()
397
+
398
+ module_name = '.'.join(attrs_path)
399
+ module_name = module_name or '__init__'
400
+
401
+ parent_path = os.getcwd()
402
+ if package_dir:
403
+ if attrs_path[0] in package_dir:
404
+ # A custom path was specified for the module we want to import
405
+ custom_path = package_dir[attrs_path[0]]
406
+ parts = custom_path.rsplit('/', 1)
407
+ if len(parts) > 1:
408
+ parent_path = os.path.join(os.getcwd(), parts[0])
409
+ module_name = parts[1]
410
+ else:
411
+ module_name = custom_path
412
+ elif '' in package_dir:
413
+ # A custom parent directory was specified for all root modules
414
+ parent_path = os.path.join(os.getcwd(), package_dir[''])
415
+
416
+ with patch_path(parent_path):
417
+ try:
418
+ # attempt to load value statically
419
+ return getattr(StaticModule(module_name), attr_name)
420
+ except Exception:
421
+ # fallback to simple import
422
+ module = importlib.import_module(module_name)
423
+
424
+ return getattr(module, attr_name)
425
+
426
+ @classmethod
427
+ def _get_parser_compound(cls, *parse_methods):
428
+ """Returns parser function to represents value as a list.
429
+
430
+ Parses a value applying given methods one after another.
431
+
432
+ :param parse_methods:
433
+ :rtype: callable
434
+ """
435
+
436
+ def parse(value):
437
+ parsed = value
438
+
439
+ for method in parse_methods:
440
+ parsed = method(parsed)
441
+
442
+ return parsed
443
+
444
+ return parse
445
+
446
+ @classmethod
447
+ def _parse_section_to_dict(cls, section_options, values_parser=None):
448
+ """Parses section options into a dictionary.
449
+
450
+ Optionally applies a given parser to values.
451
+
452
+ :param dict section_options:
453
+ :param callable values_parser:
454
+ :rtype: dict
455
+ """
456
+ value = {}
457
+ values_parser = values_parser or (lambda val: val)
458
+ for key, (_, val) in section_options.items():
459
+ value[key] = values_parser(val)
460
+ return value
461
+
462
+ def parse_section(self, section_options):
463
+ """Parses configuration file section.
464
+
465
+ :param dict section_options:
466
+ """
467
+ for (name, (_, value)) in section_options.items():
468
+ try:
469
+ self[name] = value
470
+
471
+ except KeyError:
472
+ pass # Keep silent for a new option may appear anytime.
473
+
474
+ def parse(self):
475
+ """Parses configuration file items from one
476
+ or more related sections.
477
+
478
+ """
479
+ for section_name, section_options in self.sections.items():
480
+
481
+ method_postfix = ''
482
+ if section_name: # [section.option] variant
483
+ method_postfix = '_%s' % section_name
484
+
485
+ section_parser_method = getattr(
486
+ self,
487
+ # Dots in section names are translated into dunderscores.
488
+ ('parse_section%s' % method_postfix).replace('.', '__'),
489
+ None,
490
+ )
491
+
492
+ if section_parser_method is None:
493
+ raise DistutilsOptionError(
494
+ 'Unsupported distribution option section: [%s.%s]'
495
+ % (self.section_prefix, section_name)
496
+ )
497
+
498
+ section_parser_method(section_options)
499
+
500
+ def _deprecated_config_handler(self, func, msg, warning_class):
501
+ """this function will wrap around parameters that are deprecated
502
+
503
+ :param msg: deprecation message
504
+ :param warning_class: class of warning exception to be raised
505
+ :param func: function to be wrapped around
506
+ """
507
+
508
+ @wraps(func)
509
+ def config_handler(*args, **kwargs):
510
+ warnings.warn(msg, warning_class)
511
+ return func(*args, **kwargs)
512
+
513
+ return config_handler
514
+
515
+
516
+ class ConfigMetadataHandler(ConfigHandler):
517
+
518
+ section_prefix = 'metadata'
519
+
520
+ aliases = {
521
+ 'home_page': 'url',
522
+ 'summary': 'description',
523
+ 'classifier': 'classifiers',
524
+ 'platform': 'platforms',
525
+ }
526
+
527
+ strict_mode = False
528
+ """We need to keep it loose, to be partially compatible with
529
+ `pbr` and `d2to1` packages which also uses `metadata` section.
530
+
531
+ """
532
+
533
+ def __init__(
534
+ self, target_obj, options, ignore_option_errors=False, package_dir=None
535
+ ):
536
+ super(ConfigMetadataHandler, self).__init__(
537
+ target_obj, options, ignore_option_errors
538
+ )
539
+ self.package_dir = package_dir
540
+
541
+ @property
542
+ def parsers(self):
543
+ """Metadata item name to parser function mapping."""
544
+ parse_list = self._parse_list
545
+ parse_file = self._parse_file
546
+ parse_dict = self._parse_dict
547
+ exclude_files_parser = self._exclude_files_parser
548
+
549
+ return {
550
+ 'platforms': parse_list,
551
+ 'keywords': parse_list,
552
+ 'provides': parse_list,
553
+ 'requires': self._deprecated_config_handler(
554
+ parse_list,
555
+ "The requires parameter is deprecated, please use "
556
+ "install_requires for runtime dependencies.",
557
+ DeprecationWarning,
558
+ ),
559
+ 'obsoletes': parse_list,
560
+ 'classifiers': self._get_parser_compound(parse_file, parse_list),
561
+ 'license': exclude_files_parser('license'),
562
+ 'license_file': self._deprecated_config_handler(
563
+ exclude_files_parser('license_file'),
564
+ "The license_file parameter is deprecated, "
565
+ "use license_files instead.",
566
+ DeprecationWarning,
567
+ ),
568
+ 'license_files': parse_list,
569
+ 'description': parse_file,
570
+ 'long_description': parse_file,
571
+ 'version': self._parse_version,
572
+ 'project_urls': parse_dict,
573
+ }
574
+
575
+ def _parse_version(self, value):
576
+ """Parses `version` option value.
577
+
578
+ :param value:
579
+ :rtype: str
580
+
581
+ """
582
+ version = self._parse_file(value)
583
+
584
+ if version != value:
585
+ version = version.strip()
586
+ # Be strict about versions loaded from file because it's easy to
587
+ # accidentally include newlines and other unintended content
588
+ try:
589
+ Version(version)
590
+ except InvalidVersion:
591
+ tmpl = (
592
+ 'Version loaded from {value} does not '
593
+ 'comply with PEP 440: {version}'
594
+ )
595
+ raise DistutilsOptionError(tmpl.format(**locals()))
596
+
597
+ return version
598
+
599
+ version = self._parse_attr(value, self.package_dir)
600
+
601
+ if callable(version):
602
+ version = version()
603
+
604
+ if not isinstance(version, str):
605
+ if hasattr(version, '__iter__'):
606
+ version = '.'.join(map(str, version))
607
+ else:
608
+ version = '%s' % version
609
+
610
+ return version
611
+
612
+
613
+ class ConfigOptionsHandler(ConfigHandler):
614
+
615
+ section_prefix = 'options'
616
+
617
+ @property
618
+ def parsers(self):
619
+ """Metadata item name to parser function mapping."""
620
+ parse_list = self._parse_list
621
+ parse_list_semicolon = partial(self._parse_list, separator=';')
622
+ parse_bool = self._parse_bool
623
+ parse_dict = self._parse_dict
624
+ parse_cmdclass = self._parse_cmdclass
625
+
626
+ return {
627
+ 'zip_safe': parse_bool,
628
+ 'include_package_data': parse_bool,
629
+ 'package_dir': parse_dict,
630
+ 'scripts': parse_list,
631
+ 'eager_resources': parse_list,
632
+ 'dependency_links': parse_list,
633
+ 'namespace_packages': parse_list,
634
+ 'install_requires': parse_list_semicolon,
635
+ 'setup_requires': parse_list_semicolon,
636
+ 'tests_require': parse_list_semicolon,
637
+ 'packages': self._parse_packages,
638
+ 'entry_points': self._parse_file,
639
+ 'py_modules': parse_list,
640
+ 'python_requires': SpecifierSet,
641
+ 'cmdclass': parse_cmdclass,
642
+ }
643
+
644
+ def _parse_cmdclass(self, value):
645
+ def resolve_class(qualified_class_name):
646
+ idx = qualified_class_name.rfind('.')
647
+ class_name = qualified_class_name[idx + 1 :]
648
+ pkg_name = qualified_class_name[:idx]
649
+
650
+ module = __import__(pkg_name)
651
+
652
+ return getattr(module, class_name)
653
+
654
+ return {k: resolve_class(v) for k, v in self._parse_dict(value).items()}
655
+
656
+ def _parse_packages(self, value):
657
+ """Parses `packages` option value.
658
+
659
+ :param value:
660
+ :rtype: list
661
+ """
662
+ find_directives = ['find:', 'find_namespace:']
663
+ trimmed_value = value.strip()
664
+
665
+ if trimmed_value not in find_directives:
666
+ return self._parse_list(value)
667
+
668
+ findns = trimmed_value == find_directives[1]
669
+
670
+ # Read function arguments from a dedicated section.
671
+ find_kwargs = self.parse_section_packages__find(
672
+ self.sections.get('packages.find', {})
673
+ )
674
+
675
+ if findns:
676
+ from setuptools import find_namespace_packages as find_packages
677
+ else:
678
+ from setuptools import find_packages
679
+
680
+ return find_packages(**find_kwargs)
681
+
682
+ def parse_section_packages__find(self, section_options):
683
+ """Parses `packages.find` configuration file section.
684
+
685
+ To be used in conjunction with _parse_packages().
686
+
687
+ :param dict section_options:
688
+ """
689
+ section_data = self._parse_section_to_dict(section_options, self._parse_list)
690
+
691
+ valid_keys = ['where', 'include', 'exclude']
692
+
693
+ find_kwargs = dict(
694
+ [(k, v) for k, v in section_data.items() if k in valid_keys and v]
695
+ )
696
+
697
+ where = find_kwargs.get('where')
698
+ if where is not None:
699
+ find_kwargs['where'] = where[0] # cast list to single val
700
+
701
+ return find_kwargs
702
+
703
+ def parse_section_entry_points(self, section_options):
704
+ """Parses `entry_points` configuration file section.
705
+
706
+ :param dict section_options:
707
+ """
708
+ parsed = self._parse_section_to_dict(section_options, self._parse_list)
709
+ self['entry_points'] = parsed
710
+
711
+ def _parse_package_data(self, section_options):
712
+ parsed = self._parse_section_to_dict(section_options, self._parse_list)
713
+
714
+ root = parsed.get('*')
715
+ if root:
716
+ parsed[''] = root
717
+ del parsed['*']
718
+
719
+ return parsed
720
+
721
+ def parse_section_package_data(self, section_options):
722
+ """Parses `package_data` configuration file section.
723
+
724
+ :param dict section_options:
725
+ """
726
+ self['package_data'] = self._parse_package_data(section_options)
727
+
728
+ def parse_section_exclude_package_data(self, section_options):
729
+ """Parses `exclude_package_data` configuration file section.
730
+
731
+ :param dict section_options:
732
+ """
733
+ self['exclude_package_data'] = self._parse_package_data(section_options)
734
+
735
+ def parse_section_extras_require(self, section_options):
736
+ """Parses `extras_require` configuration file section.
737
+
738
+ :param dict section_options:
739
+ """
740
+ parse_list = partial(self._parse_list, separator=';')
741
+ self['extras_require'] = self._parse_section_to_dict(
742
+ section_options, parse_list
743
+ )
744
+
745
+ def parse_section_data_files(self, section_options):
746
+ """Parses `data_files` configuration file section.
747
+
748
+ :param dict section_options:
749
+ """
750
+ parsed = self._parse_section_to_dict(section_options, self._parse_list_glob)
751
+ self['data_files'] = [(k, v) for k, v in parsed.items()]
venv/lib/python3.10/site-packages/six.py ADDED
@@ -0,0 +1,1003 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2010-2024 Benjamin Peterson
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ # of this software and associated documentation files (the "Software"), to deal
5
+ # in the Software without restriction, including without limitation the rights
6
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ # copies of the Software, and to permit persons to whom the Software is
8
+ # furnished to do so, subject to the following conditions:
9
+ #
10
+ # The above copyright notice and this permission notice shall be included in all
11
+ # copies or substantial portions of the Software.
12
+ #
13
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ # SOFTWARE.
20
+
21
+ """Utilities for writing code that runs on Python 2 and 3"""
22
+
23
+ from __future__ import absolute_import
24
+
25
+ import functools
26
+ import itertools
27
+ import operator
28
+ import sys
29
+ import types
30
+
31
+ __author__ = "Benjamin Peterson <benjamin@python.org>"
32
+ __version__ = "1.17.0"
33
+
34
+
35
+ # Useful for very coarse version differentiation.
36
+ PY2 = sys.version_info[0] == 2
37
+ PY3 = sys.version_info[0] == 3
38
+ PY34 = sys.version_info[0:2] >= (3, 4)
39
+
40
+ if PY3:
41
+ string_types = str,
42
+ integer_types = int,
43
+ class_types = type,
44
+ text_type = str
45
+ binary_type = bytes
46
+
47
+ MAXSIZE = sys.maxsize
48
+ else:
49
+ string_types = basestring,
50
+ integer_types = (int, long)
51
+ class_types = (type, types.ClassType)
52
+ text_type = unicode
53
+ binary_type = str
54
+
55
+ if sys.platform.startswith("java"):
56
+ # Jython always uses 32 bits.
57
+ MAXSIZE = int((1 << 31) - 1)
58
+ else:
59
+ # It's possible to have sizeof(long) != sizeof(Py_ssize_t).
60
+ class X(object):
61
+
62
+ def __len__(self):
63
+ return 1 << 31
64
+ try:
65
+ len(X())
66
+ except OverflowError:
67
+ # 32-bit
68
+ MAXSIZE = int((1 << 31) - 1)
69
+ else:
70
+ # 64-bit
71
+ MAXSIZE = int((1 << 63) - 1)
72
+ del X
73
+
74
+ if PY34:
75
+ from importlib.util import spec_from_loader
76
+ else:
77
+ spec_from_loader = None
78
+
79
+
80
+ def _add_doc(func, doc):
81
+ """Add documentation to a function."""
82
+ func.__doc__ = doc
83
+
84
+
85
+ def _import_module(name):
86
+ """Import module, returning the module after the last dot."""
87
+ __import__(name)
88
+ return sys.modules[name]
89
+
90
+
91
+ class _LazyDescr(object):
92
+
93
+ def __init__(self, name):
94
+ self.name = name
95
+
96
+ def __get__(self, obj, tp):
97
+ result = self._resolve()
98
+ setattr(obj, self.name, result) # Invokes __set__.
99
+ try:
100
+ # This is a bit ugly, but it avoids running this again by
101
+ # removing this descriptor.
102
+ delattr(obj.__class__, self.name)
103
+ except AttributeError:
104
+ pass
105
+ return result
106
+
107
+
108
+ class MovedModule(_LazyDescr):
109
+
110
+ def __init__(self, name, old, new=None):
111
+ super(MovedModule, self).__init__(name)
112
+ if PY3:
113
+ if new is None:
114
+ new = name
115
+ self.mod = new
116
+ else:
117
+ self.mod = old
118
+
119
+ def _resolve(self):
120
+ return _import_module(self.mod)
121
+
122
+ def __getattr__(self, attr):
123
+ _module = self._resolve()
124
+ value = getattr(_module, attr)
125
+ setattr(self, attr, value)
126
+ return value
127
+
128
+
129
+ class _LazyModule(types.ModuleType):
130
+
131
+ def __init__(self, name):
132
+ super(_LazyModule, self).__init__(name)
133
+ self.__doc__ = self.__class__.__doc__
134
+
135
+ def __dir__(self):
136
+ attrs = ["__doc__", "__name__"]
137
+ attrs += [attr.name for attr in self._moved_attributes]
138
+ return attrs
139
+
140
+ # Subclasses should override this
141
+ _moved_attributes = []
142
+
143
+
144
+ class MovedAttribute(_LazyDescr):
145
+
146
+ def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):
147
+ super(MovedAttribute, self).__init__(name)
148
+ if PY3:
149
+ if new_mod is None:
150
+ new_mod = name
151
+ self.mod = new_mod
152
+ if new_attr is None:
153
+ if old_attr is None:
154
+ new_attr = name
155
+ else:
156
+ new_attr = old_attr
157
+ self.attr = new_attr
158
+ else:
159
+ self.mod = old_mod
160
+ if old_attr is None:
161
+ old_attr = name
162
+ self.attr = old_attr
163
+
164
+ def _resolve(self):
165
+ module = _import_module(self.mod)
166
+ return getattr(module, self.attr)
167
+
168
+
169
+ class _SixMetaPathImporter(object):
170
+
171
+ """
172
+ A meta path importer to import six.moves and its submodules.
173
+
174
+ This class implements a PEP302 finder and loader. It should be compatible
175
+ with Python 2.5 and all existing versions of Python3
176
+ """
177
+
178
+ def __init__(self, six_module_name):
179
+ self.name = six_module_name
180
+ self.known_modules = {}
181
+
182
+ def _add_module(self, mod, *fullnames):
183
+ for fullname in fullnames:
184
+ self.known_modules[self.name + "." + fullname] = mod
185
+
186
+ def _get_module(self, fullname):
187
+ return self.known_modules[self.name + "." + fullname]
188
+
189
+ def find_module(self, fullname, path=None):
190
+ if fullname in self.known_modules:
191
+ return self
192
+ return None
193
+
194
+ def find_spec(self, fullname, path, target=None):
195
+ if fullname in self.known_modules:
196
+ return spec_from_loader(fullname, self)
197
+ return None
198
+
199
+ def __get_module(self, fullname):
200
+ try:
201
+ return self.known_modules[fullname]
202
+ except KeyError:
203
+ raise ImportError("This loader does not know module " + fullname)
204
+
205
+ def load_module(self, fullname):
206
+ try:
207
+ # in case of a reload
208
+ return sys.modules[fullname]
209
+ except KeyError:
210
+ pass
211
+ mod = self.__get_module(fullname)
212
+ if isinstance(mod, MovedModule):
213
+ mod = mod._resolve()
214
+ else:
215
+ mod.__loader__ = self
216
+ sys.modules[fullname] = mod
217
+ return mod
218
+
219
+ def is_package(self, fullname):
220
+ """
221
+ Return true, if the named module is a package.
222
+
223
+ We need this method to get correct spec objects with
224
+ Python 3.4 (see PEP451)
225
+ """
226
+ return hasattr(self.__get_module(fullname), "__path__")
227
+
228
+ def get_code(self, fullname):
229
+ """Return None
230
+
231
+ Required, if is_package is implemented"""
232
+ self.__get_module(fullname) # eventually raises ImportError
233
+ return None
234
+ get_source = get_code # same as get_code
235
+
236
+ def create_module(self, spec):
237
+ return self.load_module(spec.name)
238
+
239
+ def exec_module(self, module):
240
+ pass
241
+
242
+ _importer = _SixMetaPathImporter(__name__)
243
+
244
+
245
+ class _MovedItems(_LazyModule):
246
+
247
+ """Lazy loading of moved objects"""
248
+ __path__ = [] # mark as package
249
+
250
+
251
+ _moved_attributes = [
252
+ MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),
253
+ MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),
254
+ MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"),
255
+ MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),
256
+ MovedAttribute("intern", "__builtin__", "sys"),
257
+ MovedAttribute("map", "itertools", "builtins", "imap", "map"),
258
+ MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"),
259
+ MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"),
260
+ MovedAttribute("getoutput", "commands", "subprocess"),
261
+ MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"),
262
+ MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"),
263
+ MovedAttribute("reduce", "__builtin__", "functools"),
264
+ MovedAttribute("shlex_quote", "pipes", "shlex", "quote"),
265
+ MovedAttribute("StringIO", "StringIO", "io"),
266
+ MovedAttribute("UserDict", "UserDict", "collections", "IterableUserDict", "UserDict"),
267
+ MovedAttribute("UserList", "UserList", "collections"),
268
+ MovedAttribute("UserString", "UserString", "collections"),
269
+ MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),
270
+ MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),
271
+ MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"),
272
+ MovedModule("builtins", "__builtin__"),
273
+ MovedModule("configparser", "ConfigParser"),
274
+ MovedModule("collections_abc", "collections", "collections.abc" if sys.version_info >= (3, 3) else "collections"),
275
+ MovedModule("copyreg", "copy_reg"),
276
+ MovedModule("dbm_gnu", "gdbm", "dbm.gnu"),
277
+ MovedModule("dbm_ndbm", "dbm", "dbm.ndbm"),
278
+ MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread" if sys.version_info < (3, 9) else "_thread"),
279
+ MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),
280
+ MovedModule("http_cookies", "Cookie", "http.cookies"),
281
+ MovedModule("html_entities", "htmlentitydefs", "html.entities"),
282
+ MovedModule("html_parser", "HTMLParser", "html.parser"),
283
+ MovedModule("http_client", "httplib", "http.client"),
284
+ MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),
285
+ MovedModule("email_mime_image", "email.MIMEImage", "email.mime.image"),
286
+ MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"),
287
+ MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"),
288
+ MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),
289
+ MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),
290
+ MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),
291
+ MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),
292
+ MovedModule("cPickle", "cPickle", "pickle"),
293
+ MovedModule("queue", "Queue"),
294
+ MovedModule("reprlib", "repr"),
295
+ MovedModule("socketserver", "SocketServer"),
296
+ MovedModule("_thread", "thread", "_thread"),
297
+ MovedModule("tkinter", "Tkinter"),
298
+ MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),
299
+ MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),
300
+ MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),
301
+ MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),
302
+ MovedModule("tkinter_tix", "Tix", "tkinter.tix"),
303
+ MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"),
304
+ MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),
305
+ MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),
306
+ MovedModule("tkinter_colorchooser", "tkColorChooser",
307
+ "tkinter.colorchooser"),
308
+ MovedModule("tkinter_commondialog", "tkCommonDialog",
309
+ "tkinter.commondialog"),
310
+ MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),
311
+ MovedModule("tkinter_font", "tkFont", "tkinter.font"),
312
+ MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),
313
+ MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",
314
+ "tkinter.simpledialog"),
315
+ MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"),
316
+ MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"),
317
+ MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"),
318
+ MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),
319
+ MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"),
320
+ MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"),
321
+ ]
322
+ # Add windows specific modules.
323
+ if sys.platform == "win32":
324
+ _moved_attributes += [
325
+ MovedModule("winreg", "_winreg"),
326
+ ]
327
+
328
+ for attr in _moved_attributes:
329
+ setattr(_MovedItems, attr.name, attr)
330
+ if isinstance(attr, MovedModule):
331
+ _importer._add_module(attr, "moves." + attr.name)
332
+ del attr
333
+
334
+ _MovedItems._moved_attributes = _moved_attributes
335
+
336
+ moves = _MovedItems(__name__ + ".moves")
337
+ _importer._add_module(moves, "moves")
338
+
339
+
340
+ class Module_six_moves_urllib_parse(_LazyModule):
341
+
342
+ """Lazy loading of moved objects in six.moves.urllib_parse"""
343
+
344
+
345
+ _urllib_parse_moved_attributes = [
346
+ MovedAttribute("ParseResult", "urlparse", "urllib.parse"),
347
+ MovedAttribute("SplitResult", "urlparse", "urllib.parse"),
348
+ MovedAttribute("parse_qs", "urlparse", "urllib.parse"),
349
+ MovedAttribute("parse_qsl", "urlparse", "urllib.parse"),
350
+ MovedAttribute("urldefrag", "urlparse", "urllib.parse"),
351
+ MovedAttribute("urljoin", "urlparse", "urllib.parse"),
352
+ MovedAttribute("urlparse", "urlparse", "urllib.parse"),
353
+ MovedAttribute("urlsplit", "urlparse", "urllib.parse"),
354
+ MovedAttribute("urlunparse", "urlparse", "urllib.parse"),
355
+ MovedAttribute("urlunsplit", "urlparse", "urllib.parse"),
356
+ MovedAttribute("quote", "urllib", "urllib.parse"),
357
+ MovedAttribute("quote_plus", "urllib", "urllib.parse"),
358
+ MovedAttribute("unquote", "urllib", "urllib.parse"),
359
+ MovedAttribute("unquote_plus", "urllib", "urllib.parse"),
360
+ MovedAttribute("unquote_to_bytes", "urllib", "urllib.parse", "unquote", "unquote_to_bytes"),
361
+ MovedAttribute("urlencode", "urllib", "urllib.parse"),
362
+ MovedAttribute("splitquery", "urllib", "urllib.parse"),
363
+ MovedAttribute("splittag", "urllib", "urllib.parse"),
364
+ MovedAttribute("splituser", "urllib", "urllib.parse"),
365
+ MovedAttribute("splitvalue", "urllib", "urllib.parse"),
366
+ MovedAttribute("uses_fragment", "urlparse", "urllib.parse"),
367
+ MovedAttribute("uses_netloc", "urlparse", "urllib.parse"),
368
+ MovedAttribute("uses_params", "urlparse", "urllib.parse"),
369
+ MovedAttribute("uses_query", "urlparse", "urllib.parse"),
370
+ MovedAttribute("uses_relative", "urlparse", "urllib.parse"),
371
+ ]
372
+ for attr in _urllib_parse_moved_attributes:
373
+ setattr(Module_six_moves_urllib_parse, attr.name, attr)
374
+ del attr
375
+
376
+ Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes
377
+
378
+ _importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"),
379
+ "moves.urllib_parse", "moves.urllib.parse")
380
+
381
+
382
+ class Module_six_moves_urllib_error(_LazyModule):
383
+
384
+ """Lazy loading of moved objects in six.moves.urllib_error"""
385
+
386
+
387
+ _urllib_error_moved_attributes = [
388
+ MovedAttribute("URLError", "urllib2", "urllib.error"),
389
+ MovedAttribute("HTTPError", "urllib2", "urllib.error"),
390
+ MovedAttribute("ContentTooShortError", "urllib", "urllib.error"),
391
+ ]
392
+ for attr in _urllib_error_moved_attributes:
393
+ setattr(Module_six_moves_urllib_error, attr.name, attr)
394
+ del attr
395
+
396
+ Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes
397
+
398
+ _importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"),
399
+ "moves.urllib_error", "moves.urllib.error")
400
+
401
+
402
+ class Module_six_moves_urllib_request(_LazyModule):
403
+
404
+ """Lazy loading of moved objects in six.moves.urllib_request"""
405
+
406
+
407
+ _urllib_request_moved_attributes = [
408
+ MovedAttribute("urlopen", "urllib2", "urllib.request"),
409
+ MovedAttribute("install_opener", "urllib2", "urllib.request"),
410
+ MovedAttribute("build_opener", "urllib2", "urllib.request"),
411
+ MovedAttribute("pathname2url", "urllib", "urllib.request"),
412
+ MovedAttribute("url2pathname", "urllib", "urllib.request"),
413
+ MovedAttribute("getproxies", "urllib", "urllib.request"),
414
+ MovedAttribute("Request", "urllib2", "urllib.request"),
415
+ MovedAttribute("OpenerDirector", "urllib2", "urllib.request"),
416
+ MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"),
417
+ MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"),
418
+ MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"),
419
+ MovedAttribute("ProxyHandler", "urllib2", "urllib.request"),
420
+ MovedAttribute("BaseHandler", "urllib2", "urllib.request"),
421
+ MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"),
422
+ MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"),
423
+ MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"),
424
+ MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"),
425
+ MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"),
426
+ MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"),
427
+ MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"),
428
+ MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"),
429
+ MovedAttribute("HTTPHandler", "urllib2", "urllib.request"),
430
+ MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"),
431
+ MovedAttribute("FileHandler", "urllib2", "urllib.request"),
432
+ MovedAttribute("FTPHandler", "urllib2", "urllib.request"),
433
+ MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"),
434
+ MovedAttribute("UnknownHandler", "urllib2", "urllib.request"),
435
+ MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"),
436
+ MovedAttribute("urlretrieve", "urllib", "urllib.request"),
437
+ MovedAttribute("urlcleanup", "urllib", "urllib.request"),
438
+ MovedAttribute("proxy_bypass", "urllib", "urllib.request"),
439
+ MovedAttribute("parse_http_list", "urllib2", "urllib.request"),
440
+ MovedAttribute("parse_keqv_list", "urllib2", "urllib.request"),
441
+ ]
442
+ if sys.version_info[:2] < (3, 14):
443
+ _urllib_request_moved_attributes.extend(
444
+ [
445
+ MovedAttribute("URLopener", "urllib", "urllib.request"),
446
+ MovedAttribute("FancyURLopener", "urllib", "urllib.request"),
447
+ ]
448
+ )
449
+ for attr in _urllib_request_moved_attributes:
450
+ setattr(Module_six_moves_urllib_request, attr.name, attr)
451
+ del attr
452
+
453
+ Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes
454
+
455
+ _importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"),
456
+ "moves.urllib_request", "moves.urllib.request")
457
+
458
+
459
+ class Module_six_moves_urllib_response(_LazyModule):
460
+
461
+ """Lazy loading of moved objects in six.moves.urllib_response"""
462
+
463
+
464
+ _urllib_response_moved_attributes = [
465
+ MovedAttribute("addbase", "urllib", "urllib.response"),
466
+ MovedAttribute("addclosehook", "urllib", "urllib.response"),
467
+ MovedAttribute("addinfo", "urllib", "urllib.response"),
468
+ MovedAttribute("addinfourl", "urllib", "urllib.response"),
469
+ ]
470
+ for attr in _urllib_response_moved_attributes:
471
+ setattr(Module_six_moves_urllib_response, attr.name, attr)
472
+ del attr
473
+
474
+ Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes
475
+
476
+ _importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"),
477
+ "moves.urllib_response", "moves.urllib.response")
478
+
479
+
480
+ class Module_six_moves_urllib_robotparser(_LazyModule):
481
+
482
+ """Lazy loading of moved objects in six.moves.urllib_robotparser"""
483
+
484
+
485
+ _urllib_robotparser_moved_attributes = [
486
+ MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"),
487
+ ]
488
+ for attr in _urllib_robotparser_moved_attributes:
489
+ setattr(Module_six_moves_urllib_robotparser, attr.name, attr)
490
+ del attr
491
+
492
+ Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes
493
+
494
+ _importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"),
495
+ "moves.urllib_robotparser", "moves.urllib.robotparser")
496
+
497
+
498
+ class Module_six_moves_urllib(types.ModuleType):
499
+
500
+ """Create a six.moves.urllib namespace that resembles the Python 3 namespace"""
501
+ __path__ = [] # mark as package
502
+ parse = _importer._get_module("moves.urllib_parse")
503
+ error = _importer._get_module("moves.urllib_error")
504
+ request = _importer._get_module("moves.urllib_request")
505
+ response = _importer._get_module("moves.urllib_response")
506
+ robotparser = _importer._get_module("moves.urllib_robotparser")
507
+
508
+ def __dir__(self):
509
+ return ['parse', 'error', 'request', 'response', 'robotparser']
510
+
511
+ _importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"),
512
+ "moves.urllib")
513
+
514
+
515
+ def add_move(move):
516
+ """Add an item to six.moves."""
517
+ setattr(_MovedItems, move.name, move)
518
+
519
+
520
+ def remove_move(name):
521
+ """Remove item from six.moves."""
522
+ try:
523
+ delattr(_MovedItems, name)
524
+ except AttributeError:
525
+ try:
526
+ del moves.__dict__[name]
527
+ except KeyError:
528
+ raise AttributeError("no such move, %r" % (name,))
529
+
530
+
531
+ if PY3:
532
+ _meth_func = "__func__"
533
+ _meth_self = "__self__"
534
+
535
+ _func_closure = "__closure__"
536
+ _func_code = "__code__"
537
+ _func_defaults = "__defaults__"
538
+ _func_globals = "__globals__"
539
+ else:
540
+ _meth_func = "im_func"
541
+ _meth_self = "im_self"
542
+
543
+ _func_closure = "func_closure"
544
+ _func_code = "func_code"
545
+ _func_defaults = "func_defaults"
546
+ _func_globals = "func_globals"
547
+
548
+
549
+ try:
550
+ advance_iterator = next
551
+ except NameError:
552
+ def advance_iterator(it):
553
+ return it.next()
554
+ next = advance_iterator
555
+
556
+
557
+ try:
558
+ callable = callable
559
+ except NameError:
560
+ def callable(obj):
561
+ return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
562
+
563
+
564
+ if PY3:
565
+ def get_unbound_function(unbound):
566
+ return unbound
567
+
568
+ create_bound_method = types.MethodType
569
+
570
+ def create_unbound_method(func, cls):
571
+ return func
572
+
573
+ Iterator = object
574
+ else:
575
+ def get_unbound_function(unbound):
576
+ return unbound.im_func
577
+
578
+ def create_bound_method(func, obj):
579
+ return types.MethodType(func, obj, obj.__class__)
580
+
581
+ def create_unbound_method(func, cls):
582
+ return types.MethodType(func, None, cls)
583
+
584
+ class Iterator(object):
585
+
586
+ def next(self):
587
+ return type(self).__next__(self)
588
+
589
+ callable = callable
590
+ _add_doc(get_unbound_function,
591
+ """Get the function out of a possibly unbound function""")
592
+
593
+
594
+ get_method_function = operator.attrgetter(_meth_func)
595
+ get_method_self = operator.attrgetter(_meth_self)
596
+ get_function_closure = operator.attrgetter(_func_closure)
597
+ get_function_code = operator.attrgetter(_func_code)
598
+ get_function_defaults = operator.attrgetter(_func_defaults)
599
+ get_function_globals = operator.attrgetter(_func_globals)
600
+
601
+
602
+ if PY3:
603
+ def iterkeys(d, **kw):
604
+ return iter(d.keys(**kw))
605
+
606
+ def itervalues(d, **kw):
607
+ return iter(d.values(**kw))
608
+
609
+ def iteritems(d, **kw):
610
+ return iter(d.items(**kw))
611
+
612
+ def iterlists(d, **kw):
613
+ return iter(d.lists(**kw))
614
+
615
+ viewkeys = operator.methodcaller("keys")
616
+
617
+ viewvalues = operator.methodcaller("values")
618
+
619
+ viewitems = operator.methodcaller("items")
620
+ else:
621
+ def iterkeys(d, **kw):
622
+ return d.iterkeys(**kw)
623
+
624
+ def itervalues(d, **kw):
625
+ return d.itervalues(**kw)
626
+
627
+ def iteritems(d, **kw):
628
+ return d.iteritems(**kw)
629
+
630
+ def iterlists(d, **kw):
631
+ return d.iterlists(**kw)
632
+
633
+ viewkeys = operator.methodcaller("viewkeys")
634
+
635
+ viewvalues = operator.methodcaller("viewvalues")
636
+
637
+ viewitems = operator.methodcaller("viewitems")
638
+
639
+ _add_doc(iterkeys, "Return an iterator over the keys of a dictionary.")
640
+ _add_doc(itervalues, "Return an iterator over the values of a dictionary.")
641
+ _add_doc(iteritems,
642
+ "Return an iterator over the (key, value) pairs of a dictionary.")
643
+ _add_doc(iterlists,
644
+ "Return an iterator over the (key, [values]) pairs of a dictionary.")
645
+
646
+
647
+ if PY3:
648
+ def b(s):
649
+ return s.encode("latin-1")
650
+
651
+ def u(s):
652
+ return s
653
+ unichr = chr
654
+ import struct
655
+ int2byte = struct.Struct(">B").pack
656
+ del struct
657
+ byte2int = operator.itemgetter(0)
658
+ indexbytes = operator.getitem
659
+ iterbytes = iter
660
+ import io
661
+ StringIO = io.StringIO
662
+ BytesIO = io.BytesIO
663
+ del io
664
+ _assertCountEqual = "assertCountEqual"
665
+ if sys.version_info[1] <= 1:
666
+ _assertRaisesRegex = "assertRaisesRegexp"
667
+ _assertRegex = "assertRegexpMatches"
668
+ _assertNotRegex = "assertNotRegexpMatches"
669
+ else:
670
+ _assertRaisesRegex = "assertRaisesRegex"
671
+ _assertRegex = "assertRegex"
672
+ _assertNotRegex = "assertNotRegex"
673
+ else:
674
+ def b(s):
675
+ return s
676
+ # Workaround for standalone backslash
677
+
678
+ def u(s):
679
+ return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")
680
+ unichr = unichr
681
+ int2byte = chr
682
+
683
+ def byte2int(bs):
684
+ return ord(bs[0])
685
+
686
+ def indexbytes(buf, i):
687
+ return ord(buf[i])
688
+ iterbytes = functools.partial(itertools.imap, ord)
689
+ import StringIO
690
+ StringIO = BytesIO = StringIO.StringIO
691
+ _assertCountEqual = "assertItemsEqual"
692
+ _assertRaisesRegex = "assertRaisesRegexp"
693
+ _assertRegex = "assertRegexpMatches"
694
+ _assertNotRegex = "assertNotRegexpMatches"
695
+ _add_doc(b, """Byte literal""")
696
+ _add_doc(u, """Text literal""")
697
+
698
+
699
+ def assertCountEqual(self, *args, **kwargs):
700
+ return getattr(self, _assertCountEqual)(*args, **kwargs)
701
+
702
+
703
+ def assertRaisesRegex(self, *args, **kwargs):
704
+ return getattr(self, _assertRaisesRegex)(*args, **kwargs)
705
+
706
+
707
+ def assertRegex(self, *args, **kwargs):
708
+ return getattr(self, _assertRegex)(*args, **kwargs)
709
+
710
+
711
+ def assertNotRegex(self, *args, **kwargs):
712
+ return getattr(self, _assertNotRegex)(*args, **kwargs)
713
+
714
+
715
+ if PY3:
716
+ exec_ = getattr(moves.builtins, "exec")
717
+
718
+ def reraise(tp, value, tb=None):
719
+ try:
720
+ if value is None:
721
+ value = tp()
722
+ if value.__traceback__ is not tb:
723
+ raise value.with_traceback(tb)
724
+ raise value
725
+ finally:
726
+ value = None
727
+ tb = None
728
+
729
+ else:
730
+ def exec_(_code_, _globs_=None, _locs_=None):
731
+ """Execute code in a namespace."""
732
+ if _globs_ is None:
733
+ frame = sys._getframe(1)
734
+ _globs_ = frame.f_globals
735
+ if _locs_ is None:
736
+ _locs_ = frame.f_locals
737
+ del frame
738
+ elif _locs_ is None:
739
+ _locs_ = _globs_
740
+ exec("""exec _code_ in _globs_, _locs_""")
741
+
742
+ exec_("""def reraise(tp, value, tb=None):
743
+ try:
744
+ raise tp, value, tb
745
+ finally:
746
+ tb = None
747
+ """)
748
+
749
+
750
+ if sys.version_info[:2] > (3,):
751
+ exec_("""def raise_from(value, from_value):
752
+ try:
753
+ raise value from from_value
754
+ finally:
755
+ value = None
756
+ """)
757
+ else:
758
+ def raise_from(value, from_value):
759
+ raise value
760
+
761
+
762
+ print_ = getattr(moves.builtins, "print", None)
763
+ if print_ is None:
764
+ def print_(*args, **kwargs):
765
+ """The new-style print function for Python 2.4 and 2.5."""
766
+ fp = kwargs.pop("file", sys.stdout)
767
+ if fp is None:
768
+ return
769
+
770
+ def write(data):
771
+ if not isinstance(data, basestring):
772
+ data = str(data)
773
+ # If the file has an encoding, encode unicode with it.
774
+ if (isinstance(fp, file) and
775
+ isinstance(data, unicode) and
776
+ fp.encoding is not None):
777
+ errors = getattr(fp, "errors", None)
778
+ if errors is None:
779
+ errors = "strict"
780
+ data = data.encode(fp.encoding, errors)
781
+ fp.write(data)
782
+ want_unicode = False
783
+ sep = kwargs.pop("sep", None)
784
+ if sep is not None:
785
+ if isinstance(sep, unicode):
786
+ want_unicode = True
787
+ elif not isinstance(sep, str):
788
+ raise TypeError("sep must be None or a string")
789
+ end = kwargs.pop("end", None)
790
+ if end is not None:
791
+ if isinstance(end, unicode):
792
+ want_unicode = True
793
+ elif not isinstance(end, str):
794
+ raise TypeError("end must be None or a string")
795
+ if kwargs:
796
+ raise TypeError("invalid keyword arguments to print()")
797
+ if not want_unicode:
798
+ for arg in args:
799
+ if isinstance(arg, unicode):
800
+ want_unicode = True
801
+ break
802
+ if want_unicode:
803
+ newline = unicode("\n")
804
+ space = unicode(" ")
805
+ else:
806
+ newline = "\n"
807
+ space = " "
808
+ if sep is None:
809
+ sep = space
810
+ if end is None:
811
+ end = newline
812
+ for i, arg in enumerate(args):
813
+ if i:
814
+ write(sep)
815
+ write(arg)
816
+ write(end)
817
+ if sys.version_info[:2] < (3, 3):
818
+ _print = print_
819
+
820
+ def print_(*args, **kwargs):
821
+ fp = kwargs.get("file", sys.stdout)
822
+ flush = kwargs.pop("flush", False)
823
+ _print(*args, **kwargs)
824
+ if flush and fp is not None:
825
+ fp.flush()
826
+
827
+ _add_doc(reraise, """Reraise an exception.""")
828
+
829
+ if sys.version_info[0:2] < (3, 4):
830
+ # This does exactly the same what the :func:`py3:functools.update_wrapper`
831
+ # function does on Python versions after 3.2. It sets the ``__wrapped__``
832
+ # attribute on ``wrapper`` object and it doesn't raise an error if any of
833
+ # the attributes mentioned in ``assigned`` and ``updated`` are missing on
834
+ # ``wrapped`` object.
835
+ def _update_wrapper(wrapper, wrapped,
836
+ assigned=functools.WRAPPER_ASSIGNMENTS,
837
+ updated=functools.WRAPPER_UPDATES):
838
+ for attr in assigned:
839
+ try:
840
+ value = getattr(wrapped, attr)
841
+ except AttributeError:
842
+ continue
843
+ else:
844
+ setattr(wrapper, attr, value)
845
+ for attr in updated:
846
+ getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
847
+ wrapper.__wrapped__ = wrapped
848
+ return wrapper
849
+ _update_wrapper.__doc__ = functools.update_wrapper.__doc__
850
+
851
+ def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS,
852
+ updated=functools.WRAPPER_UPDATES):
853
+ return functools.partial(_update_wrapper, wrapped=wrapped,
854
+ assigned=assigned, updated=updated)
855
+ wraps.__doc__ = functools.wraps.__doc__
856
+
857
+ else:
858
+ wraps = functools.wraps
859
+
860
+
861
+ def with_metaclass(meta, *bases):
862
+ """Create a base class with a metaclass."""
863
+ # This requires a bit of explanation: the basic idea is to make a dummy
864
+ # metaclass for one level of class instantiation that replaces itself with
865
+ # the actual metaclass.
866
+ class metaclass(type):
867
+
868
+ def __new__(cls, name, this_bases, d):
869
+ if sys.version_info[:2] >= (3, 7):
870
+ # This version introduced PEP 560 that requires a bit
871
+ # of extra care (we mimic what is done by __build_class__).
872
+ resolved_bases = types.resolve_bases(bases)
873
+ if resolved_bases is not bases:
874
+ d['__orig_bases__'] = bases
875
+ else:
876
+ resolved_bases = bases
877
+ return meta(name, resolved_bases, d)
878
+
879
+ @classmethod
880
+ def __prepare__(cls, name, this_bases):
881
+ return meta.__prepare__(name, bases)
882
+ return type.__new__(metaclass, 'temporary_class', (), {})
883
+
884
+
885
+ def add_metaclass(metaclass):
886
+ """Class decorator for creating a class with a metaclass."""
887
+ def wrapper(cls):
888
+ orig_vars = cls.__dict__.copy()
889
+ slots = orig_vars.get('__slots__')
890
+ if slots is not None:
891
+ if isinstance(slots, str):
892
+ slots = [slots]
893
+ for slots_var in slots:
894
+ orig_vars.pop(slots_var)
895
+ orig_vars.pop('__dict__', None)
896
+ orig_vars.pop('__weakref__', None)
897
+ if hasattr(cls, '__qualname__'):
898
+ orig_vars['__qualname__'] = cls.__qualname__
899
+ return metaclass(cls.__name__, cls.__bases__, orig_vars)
900
+ return wrapper
901
+
902
+
903
+ def ensure_binary(s, encoding='utf-8', errors='strict'):
904
+ """Coerce **s** to six.binary_type.
905
+
906
+ For Python 2:
907
+ - `unicode` -> encoded to `str`
908
+ - `str` -> `str`
909
+
910
+ For Python 3:
911
+ - `str` -> encoded to `bytes`
912
+ - `bytes` -> `bytes`
913
+ """
914
+ if isinstance(s, binary_type):
915
+ return s
916
+ if isinstance(s, text_type):
917
+ return s.encode(encoding, errors)
918
+ raise TypeError("not expecting type '%s'" % type(s))
919
+
920
+
921
+ def ensure_str(s, encoding='utf-8', errors='strict'):
922
+ """Coerce *s* to `str`.
923
+
924
+ For Python 2:
925
+ - `unicode` -> encoded to `str`
926
+ - `str` -> `str`
927
+
928
+ For Python 3:
929
+ - `str` -> `str`
930
+ - `bytes` -> decoded to `str`
931
+ """
932
+ # Optimization: Fast return for the common case.
933
+ if type(s) is str:
934
+ return s
935
+ if PY2 and isinstance(s, text_type):
936
+ return s.encode(encoding, errors)
937
+ elif PY3 and isinstance(s, binary_type):
938
+ return s.decode(encoding, errors)
939
+ elif not isinstance(s, (text_type, binary_type)):
940
+ raise TypeError("not expecting type '%s'" % type(s))
941
+ return s
942
+
943
+
944
+ def ensure_text(s, encoding='utf-8', errors='strict'):
945
+ """Coerce *s* to six.text_type.
946
+
947
+ For Python 2:
948
+ - `unicode` -> `unicode`
949
+ - `str` -> `unicode`
950
+
951
+ For Python 3:
952
+ - `str` -> `str`
953
+ - `bytes` -> decoded to `str`
954
+ """
955
+ if isinstance(s, binary_type):
956
+ return s.decode(encoding, errors)
957
+ elif isinstance(s, text_type):
958
+ return s
959
+ else:
960
+ raise TypeError("not expecting type '%s'" % type(s))
961
+
962
+
963
+ def python_2_unicode_compatible(klass):
964
+ """
965
+ A class decorator that defines __unicode__ and __str__ methods under Python 2.
966
+ Under Python 3 it does nothing.
967
+
968
+ To support Python 2 and 3 with a single code base, define a __str__ method
969
+ returning text and apply this decorator to the class.
970
+ """
971
+ if PY2:
972
+ if '__str__' not in klass.__dict__:
973
+ raise ValueError("@python_2_unicode_compatible cannot be applied "
974
+ "to %s because it doesn't define __str__()." %
975
+ klass.__name__)
976
+ klass.__unicode__ = klass.__str__
977
+ klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
978
+ return klass
979
+
980
+
981
+ # Complete the moves implementation.
982
+ # This code is at the end of this module to speed up module loading.
983
+ # Turn this module into a package.
984
+ __path__ = [] # required for PEP 302 and PEP 451
985
+ __package__ = __name__ # see PEP 366 @ReservedAssignment
986
+ if globals().get("__spec__") is not None:
987
+ __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable
988
+ # Remove other six meta path importers, since they cause problems. This can
989
+ # happen if six is removed from sys.modules and then reloaded. (Setuptools does
990
+ # this for some reason.)
991
+ if sys.meta_path:
992
+ for i, importer in enumerate(sys.meta_path):
993
+ # Here's some real nastiness: Another "instance" of the six module might
994
+ # be floating around. Therefore, we can't use isinstance() to check for
995
+ # the six meta path importer, since the other six instance will have
996
+ # inserted an importer with different class.
997
+ if (type(importer).__name__ == "_SixMetaPathImporter" and
998
+ importer.name == __name__):
999
+ del sys.meta_path[i]
1000
+ break
1001
+ del i, importer
1002
+ # Finally, add the importer to the meta path import hook.
1003
+ sys.meta_path.append(_importer)
venv/lib/python3.10/site-packages/sqlitedict.py ADDED
@@ -0,0 +1,697 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ #
4
+ # This code is distributed under the terms and conditions
5
+ # from the Apache License, Version 2.0
6
+ #
7
+ # http://opensource.org/licenses/apache2.0.php
8
+ #
9
+ # This code was inspired by:
10
+ # * http://code.activestate.com/recipes/576638-draft-for-an-sqlite3-based-dbm/
11
+ # * http://code.activestate.com/recipes/526618/
12
+
13
+ """
14
+ A lightweight wrapper around Python's sqlite3 database, with a dict-like interface
15
+ and multi-thread access support::
16
+
17
+ >>> mydict = SqliteDict('some.db', autocommit=True) # the mapping will be persisted to file `some.db`
18
+ >>> mydict['some_key'] = any_picklable_object
19
+ >>> print mydict['some_key']
20
+ >>> print len(mydict) # etc... all dict functions work
21
+
22
+ Pickle is used internally to serialize the values. Keys are strings.
23
+
24
+ If you don't use autocommit (default is no autocommit for performance), then
25
+ don't forget to call `mydict.commit()` when done with a transaction.
26
+
27
+ """
28
+
29
+ import sqlite3
30
+ import os
31
+ import sys
32
+ import tempfile
33
+ import threading
34
+ import logging
35
+ import traceback
36
+ from base64 import b64decode, b64encode
37
+ import weakref
38
+
39
+ __version__ = '2.1.0'
40
+
41
+
42
+ def reraise(tp, value, tb=None):
43
+ if value is None:
44
+ value = tp()
45
+ if value.__traceback__ is not tb:
46
+ raise value.with_traceback(tb)
47
+ raise value
48
+
49
+
50
+ try:
51
+ from cPickle import dumps, loads, HIGHEST_PROTOCOL as PICKLE_PROTOCOL
52
+ except ImportError:
53
+ from pickle import dumps, loads, HIGHEST_PROTOCOL as PICKLE_PROTOCOL
54
+
55
+ # some Python 3 vs 2 imports
56
+ try:
57
+ from collections import UserDict as DictClass
58
+ except ImportError:
59
+ from UserDict import DictMixin as DictClass
60
+
61
+ try:
62
+ from queue import Queue
63
+ except ImportError:
64
+ from Queue import Queue
65
+
66
+
67
+ logger = logging.getLogger(__name__)
68
+
69
+ #
70
+ # There's a thread that holds the actual SQL connection (SqliteMultithread).
71
+ # We communicate with this thread via queues (request and responses).
72
+ # The requests can either be SQL commands or one of the "special" commands
73
+ # below:
74
+ #
75
+ # _REQUEST_CLOSE: request that the SQL connection be closed
76
+ # _REQUEST_COMMIT: request that any changes be committed to the DB
77
+ #
78
+ # Responses are either SQL records (e.g. results of a SELECT) or the magic
79
+ # _RESPONSE_NO_MORE command, which indicates nothing else will ever be written
80
+ # to the response queue.
81
+ #
82
+ _REQUEST_CLOSE = '--close--'
83
+ _REQUEST_COMMIT = '--commit--'
84
+ _RESPONSE_NO_MORE = '--no more--'
85
+
86
+ #
87
+ # We work with weak references for better memory efficiency.
88
+ # Dereferencing, checking the referent queue still exists, and putting to it
89
+ # is boring and repetitive, so we have a _put function to handle it for us.
90
+ #
91
+ _PUT_OK, _PUT_REFERENT_DESTROYED, _PUT_NOOP = 0, 1, 2
92
+
93
+
94
+ def _put(queue_reference, item):
95
+ if queue_reference is not None:
96
+ queue = queue_reference()
97
+ if queue is None:
98
+ #
99
+ # We got a reference to a queue, but that queue no longer exists
100
+ #
101
+ retval = _PUT_REFERENT_DESTROYED
102
+ else:
103
+ queue.put(item)
104
+ retval = _PUT_OK
105
+
106
+ del queue
107
+ return retval
108
+
109
+ #
110
+ # We didn't get a reference to a queue, so do nothing (no-op).
111
+ #
112
+ return _PUT_NOOP
113
+
114
+
115
+ def open(*args, **kwargs):
116
+ """See documentation of the SqliteDict class."""
117
+ return SqliteDict(*args, **kwargs)
118
+
119
+
120
+ def encode(obj):
121
+ """Serialize an object using pickle to a binary format accepted by SQLite."""
122
+ return sqlite3.Binary(dumps(obj, protocol=PICKLE_PROTOCOL))
123
+
124
+
125
+ def decode(obj):
126
+ """Deserialize objects retrieved from SQLite."""
127
+ return loads(bytes(obj))
128
+
129
+
130
+ def encode_key(key):
131
+ """Serialize a key using pickle + base64 encoding to text accepted by SQLite."""
132
+ return b64encode(dumps(key, protocol=PICKLE_PROTOCOL)).decode("ascii")
133
+
134
+
135
+ def decode_key(key):
136
+ """Deserialize a key retrieved from SQLite."""
137
+ return loads(b64decode(key.encode("ascii")))
138
+
139
+
140
+ def identity(obj):
141
+ """Identity f(x) = x function for encoding/decoding."""
142
+ return obj
143
+
144
+
145
+ class SqliteDict(DictClass):
146
+ VALID_FLAGS = ['c', 'r', 'w', 'n']
147
+
148
+ def __init__(self, filename=None, tablename='unnamed', flag='c',
149
+ autocommit=False, journal_mode="DELETE", encode=encode,
150
+ decode=decode, encode_key=identity, decode_key=identity,
151
+ timeout=5, outer_stack=True):
152
+ """
153
+ Initialize a thread-safe sqlite-backed dictionary. The dictionary will
154
+ be a table `tablename` in database file `filename`. A single file (=database)
155
+ may contain multiple tables.
156
+
157
+ If no `filename` is given, a random file in temp will be used (and deleted
158
+ from temp once the dict is closed/deleted).
159
+
160
+ If you enable `autocommit`, changes will be committed after each operation
161
+ (more inefficient but safer). Otherwise, changes are committed on `self.commit()`,
162
+ `self.clear()` and `self.close()`.
163
+
164
+ Set `journal_mode` to 'OFF' if you're experiencing sqlite I/O problems
165
+ or if you need performance and don't care about crash-consistency.
166
+
167
+ Set `outer_stack` to False to disable the output of the outer exception
168
+ to the error logs. This may improve the efficiency of sqlitedict
169
+ operation at the expense of a detailed exception trace.
170
+
171
+ The `flag` parameter. Exactly one of:
172
+ 'c': default mode, open for read/write, creating the db/table if necessary.
173
+ 'w': open for r/w, but drop `tablename` contents first (start with empty table)
174
+ 'r': open as read-only
175
+ 'n': create a new database (erasing any existing tables, not just `tablename`!).
176
+
177
+ The `encode` and `decode` parameters are used to customize how the values
178
+ are serialized and deserialized.
179
+ The `encode` parameter must be a function that takes a single Python
180
+ object and returns a serialized representation.
181
+ The `decode` function must be a function that takes the serialized
182
+ representation produced by `encode` and returns a deserialized Python
183
+ object.
184
+ The default is to use pickle.
185
+
186
+ The `timeout` defines the maximum time (in seconds) to wait for initial Thread startup.
187
+
188
+ """
189
+ self.in_temp = filename is None
190
+ if self.in_temp:
191
+ fd, filename = tempfile.mkstemp(prefix='sqldict')
192
+ os.close(fd)
193
+
194
+ if flag not in SqliteDict.VALID_FLAGS:
195
+ raise RuntimeError("Unrecognized flag: %s" % flag)
196
+ self.flag = flag
197
+
198
+ if flag == 'n':
199
+ if os.path.exists(filename):
200
+ os.remove(filename)
201
+
202
+ dirname = os.path.dirname(filename)
203
+ if dirname:
204
+ if not os.path.exists(dirname):
205
+ raise RuntimeError('Error! The directory does not exist, %s' % dirname)
206
+
207
+ self.filename = filename
208
+
209
+ # Use standard SQL escaping of double quote characters in identifiers, by doubling them.
210
+ # See https://github.com/RaRe-Technologies/sqlitedict/pull/113
211
+ self.tablename = tablename.replace('"', '""')
212
+
213
+ self.autocommit = autocommit
214
+ self.journal_mode = journal_mode
215
+ self.encode = encode
216
+ self.decode = decode
217
+ self.encode_key = encode_key
218
+ self.decode_key = decode_key
219
+ self._outer_stack = outer_stack
220
+
221
+ logger.debug("opening Sqlite table %r in %r" % (tablename, filename))
222
+ self.conn = self._new_conn()
223
+ if self.flag == 'r':
224
+ if self.tablename not in SqliteDict.get_tablenames(self.filename):
225
+ msg = 'Refusing to create a new table "%s" in read-only DB mode' % tablename
226
+ raise RuntimeError(msg)
227
+ else:
228
+ MAKE_TABLE = 'CREATE TABLE IF NOT EXISTS "%s" (key TEXT PRIMARY KEY, value BLOB)' % self.tablename
229
+ self.conn.execute(MAKE_TABLE)
230
+ self.conn.commit()
231
+ if flag == 'w':
232
+ self.clear()
233
+
234
+ def _new_conn(self):
235
+ return SqliteMultithread(
236
+ self.filename,
237
+ autocommit=self.autocommit,
238
+ journal_mode=self.journal_mode,
239
+ outer_stack=self._outer_stack,
240
+ )
241
+
242
+ def __enter__(self):
243
+ if not hasattr(self, 'conn') or self.conn is None:
244
+ self.conn = self._new_conn()
245
+ return self
246
+
247
+ def __exit__(self, *exc_info):
248
+ self.close()
249
+
250
+ def __str__(self):
251
+ return "SqliteDict(%s)" % (self.filename)
252
+
253
+ def __repr__(self):
254
+ return str(self) # no need of something complex
255
+
256
+ def __len__(self):
257
+ # `select count (*)` is super slow in sqlite (does a linear scan!!)
258
+ # As a result, len() is very slow too once the table size grows beyond trivial.
259
+ # We could keep the total count of rows ourselves, by means of triggers,
260
+ # but that seems too complicated and would slow down normal operation
261
+ # (insert/delete etc).
262
+ GET_LEN = 'SELECT COUNT(*) FROM "%s"' % self.tablename
263
+ rows = self.conn.select_one(GET_LEN)[0]
264
+ return rows if rows is not None else 0
265
+
266
+ def __bool__(self):
267
+ # No elements is False, otherwise True
268
+ GET_MAX = 'SELECT MAX(ROWID) FROM "%s"' % self.tablename
269
+ m = self.conn.select_one(GET_MAX)[0]
270
+ # Explicit better than implicit and bla bla
271
+ return True if m is not None else False
272
+
273
+ def iterkeys(self):
274
+ GET_KEYS = 'SELECT key FROM "%s" ORDER BY rowid' % self.tablename
275
+ for key in self.conn.select(GET_KEYS):
276
+ yield self.decode_key(key[0])
277
+
278
+ def itervalues(self):
279
+ GET_VALUES = 'SELECT value FROM "%s" ORDER BY rowid' % self.tablename
280
+ for value in self.conn.select(GET_VALUES):
281
+ yield self.decode(value[0])
282
+
283
+ def iteritems(self):
284
+ GET_ITEMS = 'SELECT key, value FROM "%s" ORDER BY rowid' % self.tablename
285
+ for key, value in self.conn.select(GET_ITEMS):
286
+ yield self.decode_key(key), self.decode(value)
287
+
288
+ def keys(self):
289
+ return self.iterkeys()
290
+
291
+ def values(self):
292
+ return self.itervalues()
293
+
294
+ def items(self):
295
+ return self.iteritems()
296
+
297
+ def __contains__(self, key):
298
+ HAS_ITEM = 'SELECT 1 FROM "%s" WHERE key = ?' % self.tablename
299
+ return self.conn.select_one(HAS_ITEM, (self.encode_key(key),)) is not None
300
+
301
+ def __getitem__(self, key):
302
+ GET_ITEM = 'SELECT value FROM "%s" WHERE key = ?' % self.tablename
303
+ item = self.conn.select_one(GET_ITEM, (self.encode_key(key),))
304
+ if item is None:
305
+ raise KeyError(key)
306
+ return self.decode(item[0])
307
+
308
+ def __setitem__(self, key, value):
309
+ if self.flag == 'r':
310
+ raise RuntimeError('Refusing to write to read-only SqliteDict')
311
+
312
+ ADD_ITEM = 'REPLACE INTO "%s" (key, value) VALUES (?,?)' % self.tablename
313
+ self.conn.execute(ADD_ITEM, (self.encode_key(key), self.encode(value)))
314
+ if self.autocommit:
315
+ self.commit()
316
+
317
+ def __delitem__(self, key):
318
+ if self.flag == 'r':
319
+ raise RuntimeError('Refusing to delete from read-only SqliteDict')
320
+
321
+ if key not in self:
322
+ raise KeyError(key)
323
+ DEL_ITEM = 'DELETE FROM "%s" WHERE key = ?' % self.tablename
324
+ self.conn.execute(DEL_ITEM, (self.encode_key(key),))
325
+ if self.autocommit:
326
+ self.commit()
327
+
328
+ def update(self, items=(), **kwds):
329
+ if self.flag == 'r':
330
+ raise RuntimeError('Refusing to update read-only SqliteDict')
331
+
332
+ try:
333
+ items = items.items()
334
+ except AttributeError:
335
+ pass
336
+ items = [(self.encode_key(k), self.encode(v)) for k, v in items]
337
+
338
+ UPDATE_ITEMS = 'REPLACE INTO "%s" (key, value) VALUES (?, ?)' % self.tablename
339
+ self.conn.executemany(UPDATE_ITEMS, items)
340
+ if kwds:
341
+ self.update(kwds)
342
+ if self.autocommit:
343
+ self.commit()
344
+
345
+ def __iter__(self):
346
+ return self.iterkeys()
347
+
348
+ def clear(self):
349
+ if self.flag == 'r':
350
+ raise RuntimeError('Refusing to clear read-only SqliteDict')
351
+
352
+ # avoid VACUUM, as it gives "OperationalError: database schema has changed"
353
+ CLEAR_ALL = 'DELETE FROM "%s";' % self.tablename
354
+ self.conn.commit()
355
+ self.conn.execute(CLEAR_ALL)
356
+ self.conn.commit()
357
+
358
+ @staticmethod
359
+ def get_tablenames(filename):
360
+ """get the names of the tables in an sqlite db as a list"""
361
+ if not os.path.isfile(filename):
362
+ raise IOError('file %s does not exist' % (filename))
363
+ GET_TABLENAMES = 'SELECT name FROM sqlite_master WHERE type="table"'
364
+ with sqlite3.connect(filename) as conn:
365
+ cursor = conn.execute(GET_TABLENAMES)
366
+ res = cursor.fetchall()
367
+
368
+ return [name[0] for name in res]
369
+
370
+ def commit(self, blocking=True):
371
+ """
372
+ Persist all data to disk.
373
+
374
+ When `blocking` is False, the commit command is queued, but the data is
375
+ not guaranteed persisted (default implication when autocommit=True).
376
+ """
377
+ if self.conn is not None:
378
+ self.conn.commit(blocking)
379
+ sync = commit
380
+
381
+ def close(self, do_log=True, force=False):
382
+ if do_log:
383
+ logger.debug("closing %s" % self)
384
+ if hasattr(self, 'conn') and self.conn is not None:
385
+ if self.conn.autocommit and not force:
386
+ # typically calls to commit are non-blocking when autocommit is
387
+ # used. However, we need to block on close() to ensure any
388
+ # awaiting exceptions are handled and that all data is
389
+ # persisted to disk before returning.
390
+ self.conn.commit(blocking=True)
391
+ self.conn.close(force=force)
392
+ self.conn = None
393
+ if self.in_temp:
394
+ try:
395
+ os.remove(self.filename)
396
+ except Exception:
397
+ pass
398
+
399
+ def terminate(self):
400
+ """Delete the underlying database file. Use with care."""
401
+ if self.flag == 'r':
402
+ raise RuntimeError('Refusing to terminate read-only SqliteDict')
403
+
404
+ self.close()
405
+
406
+ if self.filename == ':memory:':
407
+ return
408
+
409
+ logger.info("deleting %s" % self.filename)
410
+ try:
411
+ if os.path.isfile(self.filename):
412
+ os.remove(self.filename)
413
+ except (OSError, IOError):
414
+ logger.exception("failed to delete %s" % (self.filename))
415
+
416
+ def __del__(self):
417
+ # like close(), but assume globals are gone by now (do not log!)
418
+ try:
419
+ self.close(do_log=False, force=True)
420
+ except Exception:
421
+ # prevent error log flood in case of multiple SqliteDicts
422
+ # closed after connection lost (exceptions are always ignored
423
+ # in __del__ method.
424
+ pass
425
+
426
+
427
+ class SqliteMultithread(threading.Thread):
428
+ """
429
+ Wrap sqlite connection in a way that allows concurrent requests from multiple threads.
430
+
431
+ This is done by internally queueing the requests and processing them sequentially
432
+ in a separate thread (in the same order they arrived).
433
+
434
+ """
435
+ def __init__(self, filename, autocommit, journal_mode, outer_stack=True):
436
+ super(SqliteMultithread, self).__init__()
437
+ self.filename = filename
438
+ self.autocommit = autocommit
439
+ self.journal_mode = journal_mode
440
+ # use request queue of unlimited size
441
+ self.reqs = Queue()
442
+ self.daemon = True
443
+ self._outer_stack = outer_stack
444
+ self.log = logging.getLogger('sqlitedict.SqliteMultithread')
445
+
446
+ #
447
+ # Parts of this object's state get accessed from different threads, so
448
+ # we use synchronization to avoid race conditions. For example,
449
+ # .exception gets set inside the new daemon thread that we spawned, but
450
+ # gets read from the main thread. This is particularly important
451
+ # during initialization: the Thread needs some time to actually start
452
+ # working, and until this happens, any calls to e.g.
453
+ # check_raise_error() will prematurely return None, meaning all is
454
+ # well. If the that connection happens to fail, we'll never know about
455
+ # it, and instead wait for a result that never arrives (effectively,
456
+ # deadlocking). Locking solves this problem by eliminating the race
457
+ # condition.
458
+ #
459
+ self._lock = threading.Lock()
460
+ self._lock.acquire()
461
+ self.exception = None
462
+
463
+ self.start()
464
+
465
+ def _connect(self):
466
+ """Connect to the underlying database.
467
+
468
+ Raises an exception on failure. Returns the connection and cursor on success.
469
+ """
470
+ try:
471
+ if self.autocommit:
472
+ conn = sqlite3.connect(self.filename, isolation_level=None, check_same_thread=False)
473
+ else:
474
+ conn = sqlite3.connect(self.filename, check_same_thread=False)
475
+ except Exception:
476
+ self.log.exception("Failed to initialize connection for filename: %s" % self.filename)
477
+ self.exception = sys.exc_info()
478
+ raise
479
+
480
+ try:
481
+ conn.execute('PRAGMA journal_mode = %s' % self.journal_mode)
482
+ conn.text_factory = str
483
+ cursor = conn.cursor()
484
+ conn.commit()
485
+ cursor.execute('PRAGMA synchronous=OFF')
486
+ except Exception:
487
+ self.log.exception("Failed to execute PRAGMA statements.")
488
+ self.exception = sys.exc_info()
489
+ raise
490
+
491
+ return conn, cursor
492
+
493
+ def run(self):
494
+ #
495
+ # Nb. this is what actually runs inside the new daemon thread.
496
+ # self._lock is locked at this stage - see the initializer function.
497
+ #
498
+ try:
499
+ conn, cursor = self._connect()
500
+ finally:
501
+ self._lock.release()
502
+
503
+ res_ref = None
504
+ while True:
505
+ #
506
+ # req: an SQL command or one of the --magic-- commands we use internally
507
+ # arg: arguments for the command
508
+ # res_ref: a weak reference to the queue into which responses must be placed
509
+ # outer_stack: the outer stack, for producing more informative traces in case of error
510
+ #
511
+ req, arg, res_ref, outer_stack = self.reqs.get()
512
+
513
+ if req == _REQUEST_CLOSE:
514
+ assert res_ref, ('--close-- without return queue', res_ref)
515
+ break
516
+ elif req == _REQUEST_COMMIT:
517
+ conn.commit()
518
+ _put(res_ref, _RESPONSE_NO_MORE)
519
+ else:
520
+ try:
521
+ cursor.execute(req, arg)
522
+ except Exception:
523
+ with self._lock:
524
+ self.exception = (e_type, e_value, e_tb) = sys.exc_info()
525
+
526
+ inner_stack = traceback.extract_stack()
527
+
528
+ # An exception occurred in our thread, but we may not
529
+ # immediately able to throw it in our calling thread, if it has
530
+ # no return `res` queue: log as level ERROR both the inner and
531
+ # outer exception immediately.
532
+ #
533
+ # Any iteration of res.get() or any next call will detect the
534
+ # inner exception and re-raise it in the calling Thread; though
535
+ # it may be confusing to see an exception for an unrelated
536
+ # statement, an ERROR log statement from the 'sqlitedict.*'
537
+ # namespace contains the original outer stack location.
538
+ self.log.error('Inner exception:')
539
+ for item in traceback.format_list(inner_stack):
540
+ self.log.error(item)
541
+ self.log.error('') # deliniate traceback & exception w/blank line
542
+ for item in traceback.format_exception_only(e_type, e_value):
543
+ self.log.error(item)
544
+
545
+ self.log.error('') # exception & outer stack w/blank line
546
+
547
+ if self._outer_stack:
548
+ self.log.error('Outer stack:')
549
+ for item in traceback.format_list(outer_stack):
550
+ self.log.error(item)
551
+ self.log.error('Exception will be re-raised at next call.')
552
+ else:
553
+ self.log.error(
554
+ 'Unable to show the outer stack. Pass '
555
+ 'outer_stack=True when initializing the '
556
+ 'SqliteDict instance to show the outer stack.'
557
+ )
558
+
559
+ if res_ref:
560
+ for rec in cursor:
561
+ if _put(res_ref, rec) == _PUT_REFERENT_DESTROYED:
562
+ #
563
+ # The queue we are sending responses to got garbage
564
+ # collected. Nobody is listening anymore, so we
565
+ # stop sending responses.
566
+ #
567
+ break
568
+
569
+ _put(res_ref, _RESPONSE_NO_MORE)
570
+
571
+ if self.autocommit:
572
+ conn.commit()
573
+
574
+ self.log.debug('received: %s, send: --no more--', req)
575
+ conn.close()
576
+
577
+ _put(res_ref, _RESPONSE_NO_MORE)
578
+
579
+ def check_raise_error(self):
580
+ """
581
+ Check for and raise exception for any previous sqlite query.
582
+
583
+ For the `execute*` family of method calls, such calls are non-blocking and any
584
+ exception raised in the thread cannot be handled by the calling Thread (usually
585
+ MainThread). This method is called on `close`, and prior to any subsequent
586
+ calls to the `execute*` methods to check for and raise an exception in a
587
+ previous call to the MainThread.
588
+ """
589
+ with self._lock:
590
+ if self.exception:
591
+ e_type, e_value, e_tb = self.exception
592
+
593
+ # clear self.exception, if the caller decides to handle such
594
+ # exception, we should not repeatedly re-raise it.
595
+ self.exception = None
596
+
597
+ self.log.error('An exception occurred from a previous statement, view '
598
+ 'the logging namespace "sqlitedict" for outer stack.')
599
+
600
+ # The third argument to raise is the traceback object, and it is
601
+ # substituted instead of the current location as the place where
602
+ # the exception occurred, this is so that when using debuggers such
603
+ # as `pdb', or simply evaluating the naturally raised traceback, we
604
+ # retain the original (inner) location of where the exception
605
+ # occurred.
606
+ reraise(e_type, e_value, e_tb)
607
+
608
+ def execute(self, req, arg=None, res=None):
609
+ """
610
+ `execute` calls are non-blocking: just queue up the request and return immediately.
611
+
612
+ :param req: The request (an SQL command)
613
+ :param arg: Arguments to the SQL command
614
+ :param res: A queue in which to place responses as they become available
615
+ """
616
+ self.check_raise_error()
617
+ stack = None
618
+
619
+ if self._outer_stack:
620
+ # NOTE: This might be a lot of information to pump into an input
621
+ # queue, affecting performance. I've also seen earlier versions of
622
+ # jython take a severe performance impact for throwing exceptions
623
+ # so often.
624
+ stack = traceback.extract_stack()[:-1]
625
+
626
+ #
627
+ # We pass a weak reference to the response queue instead of a regular
628
+ # reference, because we want the queues to be garbage-collected
629
+ # more aggressively.
630
+ #
631
+ res_ref = None
632
+ if res:
633
+ res_ref = weakref.ref(res)
634
+
635
+ self.reqs.put((req, arg or tuple(), res_ref, stack))
636
+
637
+ def executemany(self, req, items):
638
+ for item in items:
639
+ self.execute(req, item)
640
+ self.check_raise_error()
641
+
642
+ def select(self, req, arg=None):
643
+ """
644
+ Unlike sqlite's native select, this select doesn't handle iteration efficiently.
645
+
646
+ The result of `select` starts filling up with values as soon as the
647
+ request is dequeued, and although you can iterate over the result normally
648
+ (`for res in self.select(): ...`), the entire result will be in memory.
649
+ """
650
+ res = Queue() # results of the select will appear as items in this queue
651
+ self.execute(req, arg, res)
652
+ while True:
653
+ rec = res.get()
654
+ self.check_raise_error()
655
+ if rec == _RESPONSE_NO_MORE:
656
+ break
657
+ yield rec
658
+
659
+ def select_one(self, req, arg=None):
660
+ """Return only the first row of the SELECT, or None if there are no matching rows."""
661
+ try:
662
+ return next(iter(self.select(req, arg)))
663
+ except StopIteration:
664
+ return None
665
+
666
+ def commit(self, blocking=True):
667
+ if blocking:
668
+ # by default, we await completion of commit() unless
669
+ # blocking=False. This ensures any available exceptions for any
670
+ # previous statement are thrown before returning, and that the
671
+ # data has actually persisted to disk!
672
+ self.select_one(_REQUEST_COMMIT)
673
+ else:
674
+ # otherwise, we fire and forget as usual.
675
+ self.execute(_REQUEST_COMMIT)
676
+
677
+ def close(self, force=False):
678
+ if force:
679
+ # If a SqliteDict is being killed or garbage-collected, then select_one()
680
+ # could hang forever because run() might already have exited and therefore
681
+ # can't process the request. Instead, push the close command to the requests
682
+ # queue directly. If run() is still alive, it will exit gracefully. If not,
683
+ # then there's nothing we can do anyway.
684
+ self.reqs.put((_REQUEST_CLOSE, None, weakref.ref(Queue()), None))
685
+ else:
686
+ # we abuse 'select' to "iter" over a "--close--" statement so that we
687
+ # can confirm the completion of close before joining the thread and
688
+ # returning (by semaphore '--no more--'
689
+ self.select_one(_REQUEST_CLOSE)
690
+ self.join()
691
+
692
+
693
+ #
694
+ # This is here for .github/workflows/release.yml
695
+ #
696
+ if __name__ == '__main__':
697
+ print(__version__)
venv/lib/python3.10/site-packages/threadpoolctl.py ADDED
@@ -0,0 +1,1292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """threadpoolctl
2
+
3
+ This module provides utilities to introspect native libraries that relies on
4
+ thread pools (notably BLAS and OpenMP implementations) and dynamically set the
5
+ maximal number of threads they can use.
6
+ """
7
+
8
+ # License: BSD 3-Clause
9
+
10
+ # The code to introspect dynamically loaded libraries on POSIX systems is
11
+ # adapted from code by Intel developer @anton-malakhov available at
12
+ # https://github.com/IntelPython/smp (Copyright (c) 2017, Intel Corporation)
13
+ # and also published under the BSD 3-Clause license
14
+ import os
15
+ import re
16
+ import sys
17
+ import ctypes
18
+ import itertools
19
+ import textwrap
20
+ from typing import final
21
+ import warnings
22
+ from ctypes.util import find_library
23
+ from abc import ABC, abstractmethod
24
+ from functools import lru_cache
25
+ from contextlib import ContextDecorator
26
+
27
+ __version__ = "3.6.0"
28
+ __all__ = [
29
+ "threadpool_limits",
30
+ "threadpool_info",
31
+ "ThreadpoolController",
32
+ "LibController",
33
+ "register",
34
+ ]
35
+
36
+
37
+ # One can get runtime errors or even segfaults due to multiple OpenMP libraries
38
+ # loaded simultaneously which can happen easily in Python when importing and
39
+ # using compiled extensions built with different compilers and therefore
40
+ # different OpenMP runtimes in the same program. In particular libiomp (used by
41
+ # Intel ICC) and libomp used by clang/llvm tend to crash. This can happen for
42
+ # instance when calling BLAS inside a prange. Setting the following environment
43
+ # variable allows multiple OpenMP libraries to be loaded. It should not degrade
44
+ # performances since we manually take care of potential over-subscription
45
+ # performance issues, in sections of the code where nested OpenMP loops can
46
+ # happen, by dynamically reconfiguring the inner OpenMP runtime to temporarily
47
+ # disable it while under the scope of the outer OpenMP parallel section.
48
+ os.environ.setdefault("KMP_DUPLICATE_LIB_OK", "True")
49
+
50
+ # Structure to cast the info on dynamically loaded library. See
51
+ # https://linux.die.net/man/3/dl_iterate_phdr for more details.
52
+ _SYSTEM_UINT = ctypes.c_uint64 if sys.maxsize > 2**32 else ctypes.c_uint32
53
+ _SYSTEM_UINT_HALF = ctypes.c_uint32 if sys.maxsize > 2**32 else ctypes.c_uint16
54
+
55
+
56
+ class _dl_phdr_info(ctypes.Structure):
57
+ _fields_ = [
58
+ ("dlpi_addr", _SYSTEM_UINT), # Base address of object
59
+ ("dlpi_name", ctypes.c_char_p), # path to the library
60
+ ("dlpi_phdr", ctypes.c_void_p), # pointer on dlpi_headers
61
+ ("dlpi_phnum", _SYSTEM_UINT_HALF), # number of elements in dlpi_phdr
62
+ ]
63
+
64
+
65
+ # The RTLD_NOLOAD flag for loading shared libraries is not defined on Windows.
66
+ try:
67
+ _RTLD_NOLOAD = os.RTLD_NOLOAD
68
+ except AttributeError:
69
+ _RTLD_NOLOAD = ctypes.DEFAULT_MODE
70
+
71
+
72
+ class LibController(ABC):
73
+ """Abstract base class for the individual library controllers
74
+
75
+ A library controller must expose the following class attributes:
76
+ - user_api : str
77
+ Usually the name of the library or generic specification the library
78
+ implements, e.g. "blas" is a specification with different implementations.
79
+ - internal_api : str
80
+ Usually the name of the library or concrete implementation of some
81
+ specification, e.g. "openblas" is an implementation of the "blas"
82
+ specification.
83
+ - filename_prefixes : tuple
84
+ Possible prefixes of the shared library's filename that allow to
85
+ identify the library. e.g. "libopenblas" for libopenblas.so.
86
+
87
+ and implement the following methods: `get_num_threads`, `set_num_threads` and
88
+ `get_version`.
89
+
90
+ Threadpoolctl loops through all the loaded shared libraries and tries to match
91
+ the filename of each library with the `filename_prefixes`. If a match is found, a
92
+ controller is instantiated and a handler to the library is stored in the `dynlib`
93
+ attribute as a `ctypes.CDLL` object. It can be used to access the necessary symbols
94
+ of the shared library to implement the above methods.
95
+
96
+ The following information will be exposed in the info dictionary:
97
+ - user_api : standardized API, if any, or a copy of internal_api.
98
+ - internal_api : implementation-specific API.
99
+ - num_threads : the current thread limit.
100
+ - prefix : prefix of the shared library's filename.
101
+ - filepath : path to the loaded shared library.
102
+ - version : version of the library (if available).
103
+
104
+ In addition, each library controller may expose internal API specific entries. They
105
+ must be set as attributes in the `set_additional_attributes` method.
106
+ """
107
+
108
+ @final
109
+ def __init__(self, *, filepath=None, prefix=None, parent=None):
110
+ """This is not meant to be overriden by subclasses."""
111
+ self.parent = parent
112
+ self.prefix = prefix
113
+ self.filepath = filepath
114
+ self.dynlib = ctypes.CDLL(filepath, mode=_RTLD_NOLOAD)
115
+ self._symbol_prefix, self._symbol_suffix = self._find_affixes()
116
+ self.version = self.get_version()
117
+ self.set_additional_attributes()
118
+
119
+ def info(self):
120
+ """Return relevant info wrapped in a dict"""
121
+ hidden_attrs = ("dynlib", "parent", "_symbol_prefix", "_symbol_suffix")
122
+ return {
123
+ "user_api": self.user_api,
124
+ "internal_api": self.internal_api,
125
+ "num_threads": self.num_threads,
126
+ **{k: v for k, v in vars(self).items() if k not in hidden_attrs},
127
+ }
128
+
129
+ def set_additional_attributes(self):
130
+ """Set additional attributes meant to be exposed in the info dict"""
131
+
132
+ @property
133
+ def num_threads(self):
134
+ """Exposes the current thread limit as a dynamic property
135
+
136
+ This is not meant to be used or overriden by subclasses.
137
+ """
138
+ return self.get_num_threads()
139
+
140
+ @abstractmethod
141
+ def get_num_threads(self):
142
+ """Return the maximum number of threads available to use"""
143
+
144
+ @abstractmethod
145
+ def set_num_threads(self, num_threads):
146
+ """Set the maximum number of threads to use"""
147
+
148
+ @abstractmethod
149
+ def get_version(self):
150
+ """Return the version of the shared library"""
151
+
152
+ def _find_affixes(self):
153
+ """Return the affixes for the symbols of the shared library"""
154
+ return "", ""
155
+
156
+ def _get_symbol(self, name):
157
+ """Return the symbol of the shared library accounding for the affixes"""
158
+ return getattr(
159
+ self.dynlib, f"{self._symbol_prefix}{name}{self._symbol_suffix}", None
160
+ )
161
+
162
+
163
+ class OpenBLASController(LibController):
164
+ """Controller class for OpenBLAS"""
165
+
166
+ user_api = "blas"
167
+ internal_api = "openblas"
168
+ filename_prefixes = ("libopenblas", "libblas", "libscipy_openblas")
169
+
170
+ _symbol_prefixes = ("", "scipy_")
171
+ _symbol_suffixes = ("", "64_", "_64")
172
+
173
+ # All variations of "openblas_get_num_threads", accounting for the affixes
174
+ check_symbols = tuple(
175
+ f"{prefix}openblas_get_num_threads{suffix}"
176
+ for prefix, suffix in itertools.product(_symbol_prefixes, _symbol_suffixes)
177
+ )
178
+
179
+ def _find_affixes(self):
180
+ for prefix, suffix in itertools.product(
181
+ self._symbol_prefixes, self._symbol_suffixes
182
+ ):
183
+ if hasattr(self.dynlib, f"{prefix}openblas_get_num_threads{suffix}"):
184
+ return prefix, suffix
185
+
186
+ def set_additional_attributes(self):
187
+ self.threading_layer = self._get_threading_layer()
188
+ self.architecture = self._get_architecture()
189
+
190
+ def get_num_threads(self):
191
+ get_num_threads_func = self._get_symbol("openblas_get_num_threads")
192
+ if get_num_threads_func is not None:
193
+ return get_num_threads_func()
194
+ return None
195
+
196
+ def set_num_threads(self, num_threads):
197
+ set_num_threads_func = self._get_symbol("openblas_set_num_threads")
198
+ if set_num_threads_func is not None:
199
+ return set_num_threads_func(num_threads)
200
+ return None
201
+
202
+ def get_version(self):
203
+ # None means OpenBLAS is not loaded or version < 0.3.4, since OpenBLAS
204
+ # did not expose its version before that.
205
+ get_version_func = self._get_symbol("openblas_get_config")
206
+ if get_version_func is not None:
207
+ get_version_func.restype = ctypes.c_char_p
208
+ config = get_version_func().split()
209
+ if config[0] == b"OpenBLAS":
210
+ return config[1].decode("utf-8")
211
+ return None
212
+ return None
213
+
214
+ def _get_threading_layer(self):
215
+ """Return the threading layer of OpenBLAS"""
216
+ get_threading_layer_func = self._get_symbol("openblas_get_parallel")
217
+ if get_threading_layer_func is not None:
218
+ threading_layer = get_threading_layer_func()
219
+ if threading_layer == 2:
220
+ return "openmp"
221
+ elif threading_layer == 1:
222
+ return "pthreads"
223
+ return "disabled"
224
+ return "unknown"
225
+
226
+ def _get_architecture(self):
227
+ """Return the architecture detected by OpenBLAS"""
228
+ get_architecture_func = self._get_symbol("openblas_get_corename")
229
+ if get_architecture_func is not None:
230
+ get_architecture_func.restype = ctypes.c_char_p
231
+ return get_architecture_func().decode("utf-8")
232
+ return None
233
+
234
+
235
+ class BLISController(LibController):
236
+ """Controller class for BLIS"""
237
+
238
+ user_api = "blas"
239
+ internal_api = "blis"
240
+ filename_prefixes = ("libblis", "libblas")
241
+ check_symbols = (
242
+ "bli_thread_get_num_threads",
243
+ "bli_thread_set_num_threads",
244
+ "bli_info_get_version_str",
245
+ "bli_info_get_enable_openmp",
246
+ "bli_info_get_enable_pthreads",
247
+ "bli_arch_query_id",
248
+ "bli_arch_string",
249
+ )
250
+
251
+ def set_additional_attributes(self):
252
+ self.threading_layer = self._get_threading_layer()
253
+ self.architecture = self._get_architecture()
254
+
255
+ def get_num_threads(self):
256
+ get_func = getattr(self.dynlib, "bli_thread_get_num_threads", lambda: None)
257
+ num_threads = get_func()
258
+ # by default BLIS is single-threaded and get_num_threads
259
+ # returns -1. We map it to 1 for consistency with other libraries.
260
+ return 1 if num_threads == -1 else num_threads
261
+
262
+ def set_num_threads(self, num_threads):
263
+ set_func = getattr(
264
+ self.dynlib, "bli_thread_set_num_threads", lambda num_threads: None
265
+ )
266
+ return set_func(num_threads)
267
+
268
+ def get_version(self):
269
+ get_version_ = getattr(self.dynlib, "bli_info_get_version_str", None)
270
+ if get_version_ is None:
271
+ return None
272
+
273
+ get_version_.restype = ctypes.c_char_p
274
+ return get_version_().decode("utf-8")
275
+
276
+ def _get_threading_layer(self):
277
+ """Return the threading layer of BLIS"""
278
+ if getattr(self.dynlib, "bli_info_get_enable_openmp", lambda: False)():
279
+ return "openmp"
280
+ elif getattr(self.dynlib, "bli_info_get_enable_pthreads", lambda: False)():
281
+ return "pthreads"
282
+ return "disabled"
283
+
284
+ def _get_architecture(self):
285
+ """Return the architecture detected by BLIS"""
286
+ bli_arch_query_id = getattr(self.dynlib, "bli_arch_query_id", None)
287
+ bli_arch_string = getattr(self.dynlib, "bli_arch_string", None)
288
+ if bli_arch_query_id is None or bli_arch_string is None:
289
+ return None
290
+
291
+ # the true restype should be BLIS' arch_t (enum) but int should work
292
+ # for us:
293
+ bli_arch_query_id.restype = ctypes.c_int
294
+ bli_arch_string.restype = ctypes.c_char_p
295
+ return bli_arch_string(bli_arch_query_id()).decode("utf-8")
296
+
297
+
298
+ class FlexiBLASController(LibController):
299
+ """Controller class for FlexiBLAS"""
300
+
301
+ user_api = "blas"
302
+ internal_api = "flexiblas"
303
+ filename_prefixes = ("libflexiblas",)
304
+ check_symbols = (
305
+ "flexiblas_get_num_threads",
306
+ "flexiblas_set_num_threads",
307
+ "flexiblas_get_version",
308
+ "flexiblas_list",
309
+ "flexiblas_list_loaded",
310
+ "flexiblas_current_backend",
311
+ )
312
+
313
+ @property
314
+ def loaded_backends(self):
315
+ return self._get_backend_list(loaded=True)
316
+
317
+ @property
318
+ def current_backend(self):
319
+ return self._get_current_backend()
320
+
321
+ def info(self):
322
+ """Return relevant info wrapped in a dict"""
323
+ # We override the info method because the loaded and current backends
324
+ # are dynamic properties
325
+ exposed_attrs = super().info()
326
+ exposed_attrs["loaded_backends"] = self.loaded_backends
327
+ exposed_attrs["current_backend"] = self.current_backend
328
+
329
+ return exposed_attrs
330
+
331
+ def set_additional_attributes(self):
332
+ self.available_backends = self._get_backend_list(loaded=False)
333
+
334
+ def get_num_threads(self):
335
+ get_func = getattr(self.dynlib, "flexiblas_get_num_threads", lambda: None)
336
+ num_threads = get_func()
337
+ # by default BLIS is single-threaded and get_num_threads
338
+ # returns -1. We map it to 1 for consistency with other libraries.
339
+ return 1 if num_threads == -1 else num_threads
340
+
341
+ def set_num_threads(self, num_threads):
342
+ set_func = getattr(
343
+ self.dynlib, "flexiblas_set_num_threads", lambda num_threads: None
344
+ )
345
+ return set_func(num_threads)
346
+
347
+ def get_version(self):
348
+ get_version_ = getattr(self.dynlib, "flexiblas_get_version", None)
349
+ if get_version_ is None:
350
+ return None
351
+
352
+ major = ctypes.c_int()
353
+ minor = ctypes.c_int()
354
+ patch = ctypes.c_int()
355
+ get_version_(ctypes.byref(major), ctypes.byref(minor), ctypes.byref(patch))
356
+ return f"{major.value}.{minor.value}.{patch.value}"
357
+
358
+ def _get_backend_list(self, loaded=False):
359
+ """Return the list of available backends for FlexiBLAS.
360
+
361
+ If loaded is False, return the list of available backends from the FlexiBLAS
362
+ configuration. If loaded is True, return the list of actually loaded backends.
363
+ """
364
+ func_name = f"flexiblas_list{'_loaded' if loaded else ''}"
365
+ get_backend_list_ = getattr(self.dynlib, func_name, None)
366
+ if get_backend_list_ is None:
367
+ return None
368
+
369
+ n_backends = get_backend_list_(None, 0, 0)
370
+
371
+ backends = []
372
+ for i in range(n_backends):
373
+ backend_name = ctypes.create_string_buffer(1024)
374
+ get_backend_list_(backend_name, 1024, i)
375
+ if backend_name.value.decode("utf-8") != "__FALLBACK__":
376
+ # We don't know when to expect __FALLBACK__ but it is not a real
377
+ # backend and does not show up when running flexiblas list.
378
+ backends.append(backend_name.value.decode("utf-8"))
379
+ return backends
380
+
381
+ def _get_current_backend(self):
382
+ """Return the backend of FlexiBLAS"""
383
+ get_backend_ = getattr(self.dynlib, "flexiblas_current_backend", None)
384
+ if get_backend_ is None:
385
+ return None
386
+
387
+ backend = ctypes.create_string_buffer(1024)
388
+ get_backend_(backend, ctypes.sizeof(backend))
389
+ return backend.value.decode("utf-8")
390
+
391
+ def switch_backend(self, backend):
392
+ """Switch the backend of FlexiBLAS
393
+
394
+ Parameters
395
+ ----------
396
+ backend : str
397
+ The name or the path to the shared library of the backend to switch to. If
398
+ the backend is not already loaded, it will be loaded first.
399
+ """
400
+ if backend not in self.loaded_backends:
401
+ if backend in self.available_backends:
402
+ load_func = getattr(self.dynlib, "flexiblas_load_backend", lambda _: -1)
403
+ else: # assume backend is a path to a shared library
404
+ load_func = getattr(
405
+ self.dynlib, "flexiblas_load_backend_library", lambda _: -1
406
+ )
407
+ res = load_func(str(backend).encode("utf-8"))
408
+ if res == -1:
409
+ raise RuntimeError(
410
+ f"Failed to load backend {backend!r}. It must either be the name of"
411
+ " a backend available in the FlexiBLAS configuration "
412
+ f"{self.available_backends} or the path to a valid shared library."
413
+ )
414
+
415
+ # Trigger a new search of loaded shared libraries since loading a new
416
+ # backend caused a dlopen.
417
+ self.parent._load_libraries()
418
+
419
+ switch_func = getattr(self.dynlib, "flexiblas_switch", lambda _: -1)
420
+ idx = self.loaded_backends.index(backend)
421
+ res = switch_func(idx)
422
+ if res == -1:
423
+ raise RuntimeError(f"Failed to switch to backend {backend!r}.")
424
+
425
+
426
+ class MKLController(LibController):
427
+ """Controller class for MKL"""
428
+
429
+ user_api = "blas"
430
+ internal_api = "mkl"
431
+ filename_prefixes = ("libmkl_rt", "mkl_rt", "libblas")
432
+ check_symbols = (
433
+ "MKL_Get_Max_Threads",
434
+ "MKL_Set_Num_Threads",
435
+ "MKL_Get_Version_String",
436
+ "MKL_Set_Threading_Layer",
437
+ )
438
+
439
+ def set_additional_attributes(self):
440
+ self.threading_layer = self._get_threading_layer()
441
+
442
+ def get_num_threads(self):
443
+ get_func = getattr(self.dynlib, "MKL_Get_Max_Threads", lambda: None)
444
+ return get_func()
445
+
446
+ def set_num_threads(self, num_threads):
447
+ set_func = getattr(self.dynlib, "MKL_Set_Num_Threads", lambda num_threads: None)
448
+ return set_func(num_threads)
449
+
450
+ def get_version(self):
451
+ if not hasattr(self.dynlib, "MKL_Get_Version_String"):
452
+ return None
453
+
454
+ res = ctypes.create_string_buffer(200)
455
+ self.dynlib.MKL_Get_Version_String(res, 200)
456
+
457
+ version = res.value.decode("utf-8")
458
+ group = re.search(r"Version ([^ ]+) ", version)
459
+ if group is not None:
460
+ version = group.groups()[0]
461
+ return version.strip()
462
+
463
+ def _get_threading_layer(self):
464
+ """Return the threading layer of MKL"""
465
+ # The function mkl_set_threading_layer returns the current threading
466
+ # layer. Calling it with an invalid threading layer allows us to safely
467
+ # get the threading layer
468
+ set_threading_layer = getattr(
469
+ self.dynlib, "MKL_Set_Threading_Layer", lambda layer: -1
470
+ )
471
+ layer_map = {
472
+ 0: "intel",
473
+ 1: "sequential",
474
+ 2: "pgi",
475
+ 3: "gnu",
476
+ 4: "tbb",
477
+ -1: "not specified",
478
+ }
479
+ return layer_map[set_threading_layer(-1)]
480
+
481
+
482
+ class OpenMPController(LibController):
483
+ """Controller class for OpenMP"""
484
+
485
+ user_api = "openmp"
486
+ internal_api = "openmp"
487
+ filename_prefixes = ("libiomp", "libgomp", "libomp", "vcomp")
488
+ check_symbols = (
489
+ "omp_get_max_threads",
490
+ "omp_get_num_threads",
491
+ )
492
+
493
+ def get_num_threads(self):
494
+ get_func = getattr(self.dynlib, "omp_get_max_threads", lambda: None)
495
+ return get_func()
496
+
497
+ def set_num_threads(self, num_threads):
498
+ set_func = getattr(self.dynlib, "omp_set_num_threads", lambda num_threads: None)
499
+ return set_func(num_threads)
500
+
501
+ def get_version(self):
502
+ # There is no way to get the version number programmatically in OpenMP.
503
+ return None
504
+
505
+
506
+ # Controllers for the libraries that we'll look for in the loaded libraries.
507
+ # Third party libraries can register their own controllers.
508
+ _ALL_CONTROLLERS = [
509
+ OpenBLASController,
510
+ BLISController,
511
+ MKLController,
512
+ OpenMPController,
513
+ FlexiBLASController,
514
+ ]
515
+
516
+ # Helpers for the doc and test names
517
+ _ALL_USER_APIS = list(set(lib.user_api for lib in _ALL_CONTROLLERS))
518
+ _ALL_INTERNAL_APIS = [lib.internal_api for lib in _ALL_CONTROLLERS]
519
+ _ALL_PREFIXES = list(
520
+ set(prefix for lib in _ALL_CONTROLLERS for prefix in lib.filename_prefixes)
521
+ )
522
+ _ALL_BLAS_LIBRARIES = [
523
+ lib.internal_api for lib in _ALL_CONTROLLERS if lib.user_api == "blas"
524
+ ]
525
+ _ALL_OPENMP_LIBRARIES = OpenMPController.filename_prefixes
526
+
527
+
528
+ def register(controller):
529
+ """Register a new controller"""
530
+ _ALL_CONTROLLERS.append(controller)
531
+ _ALL_USER_APIS.append(controller.user_api)
532
+ _ALL_INTERNAL_APIS.append(controller.internal_api)
533
+ _ALL_PREFIXES.extend(controller.filename_prefixes)
534
+
535
+
536
+ def _format_docstring(*args, **kwargs):
537
+ def decorator(o):
538
+ if o.__doc__ is not None:
539
+ o.__doc__ = o.__doc__.format(*args, **kwargs)
540
+ return o
541
+
542
+ return decorator
543
+
544
+
545
+ @lru_cache(maxsize=10000)
546
+ def _realpath(filepath):
547
+ """Small caching wrapper around os.path.realpath to limit system calls"""
548
+ return os.path.realpath(filepath)
549
+
550
+
551
+ @_format_docstring(USER_APIS=list(_ALL_USER_APIS), INTERNAL_APIS=_ALL_INTERNAL_APIS)
552
+ def threadpool_info():
553
+ """Return the maximal number of threads for each detected library.
554
+
555
+ Return a list with all the supported libraries that have been found. Each
556
+ library is represented by a dict with the following information:
557
+
558
+ - "user_api" : user API. Possible values are {USER_APIS}.
559
+ - "internal_api": internal API. Possible values are {INTERNAL_APIS}.
560
+ - "prefix" : filename prefix of the specific implementation.
561
+ - "filepath": path to the loaded library.
562
+ - "version": version of the library (if available).
563
+ - "num_threads": the current thread limit.
564
+
565
+ In addition, each library may contain internal_api specific entries.
566
+ """
567
+ return ThreadpoolController().info()
568
+
569
+
570
+ class _ThreadpoolLimiter:
571
+ """The guts of ThreadpoolController.limit
572
+
573
+ Refer to the docstring of ThreadpoolController.limit for more details.
574
+
575
+ It will only act on the library controllers held by the provided `controller`.
576
+ Using the default constructor sets the limits right away such that it can be used as
577
+ a callable. Setting the limits can be delayed by using the `wrap` class method such
578
+ that it can be used as a decorator.
579
+ """
580
+
581
+ def __init__(self, controller, *, limits=None, user_api=None):
582
+ self._controller = controller
583
+ self._limits, self._user_api, self._prefixes = self._check_params(
584
+ limits, user_api
585
+ )
586
+ self._original_info = self._controller.info()
587
+ self._set_threadpool_limits()
588
+
589
+ def __enter__(self):
590
+ return self
591
+
592
+ def __exit__(self, type, value, traceback):
593
+ self.restore_original_limits()
594
+
595
+ @classmethod
596
+ def wrap(cls, controller, *, limits=None, user_api=None):
597
+ """Return an instance of this class that can be used as a decorator"""
598
+ return _ThreadpoolLimiterDecorator(
599
+ controller=controller, limits=limits, user_api=user_api
600
+ )
601
+
602
+ def restore_original_limits(self):
603
+ """Set the limits back to their original values"""
604
+ for lib_controller, original_info in zip(
605
+ self._controller.lib_controllers, self._original_info
606
+ ):
607
+ lib_controller.set_num_threads(original_info["num_threads"])
608
+
609
+ # Alias of `restore_original_limits` for backward compatibility
610
+ unregister = restore_original_limits
611
+
612
+ def get_original_num_threads(self):
613
+ """Original num_threads from before calling threadpool_limits
614
+
615
+ Return a dict `{user_api: num_threads}`.
616
+ """
617
+ num_threads = {}
618
+ warning_apis = []
619
+
620
+ for user_api in self._user_api:
621
+ limits = [
622
+ lib_info["num_threads"]
623
+ for lib_info in self._original_info
624
+ if lib_info["user_api"] == user_api
625
+ ]
626
+ limits = set(limits)
627
+ n_limits = len(limits)
628
+
629
+ if n_limits == 1:
630
+ limit = limits.pop()
631
+ elif n_limits == 0:
632
+ limit = None
633
+ else:
634
+ limit = min(limits)
635
+ warning_apis.append(user_api)
636
+
637
+ num_threads[user_api] = limit
638
+
639
+ if warning_apis:
640
+ warnings.warn(
641
+ "Multiple value possible for following user apis: "
642
+ + ", ".join(warning_apis)
643
+ + ". Returning the minimum."
644
+ )
645
+
646
+ return num_threads
647
+
648
+ def _check_params(self, limits, user_api):
649
+ """Suitable values for the _limits, _user_api and _prefixes attributes"""
650
+
651
+ if isinstance(limits, str) and limits == "sequential_blas_under_openmp":
652
+ (
653
+ limits,
654
+ user_api,
655
+ ) = self._controller._get_params_for_sequential_blas_under_openmp().values()
656
+
657
+ if limits is None or isinstance(limits, int):
658
+ if user_api is None:
659
+ user_api = _ALL_USER_APIS
660
+ elif user_api in _ALL_USER_APIS:
661
+ user_api = [user_api]
662
+ else:
663
+ raise ValueError(
664
+ f"user_api must be either in {_ALL_USER_APIS} or None. Got "
665
+ f"{user_api} instead."
666
+ )
667
+
668
+ if limits is not None:
669
+ limits = {api: limits for api in user_api}
670
+ prefixes = []
671
+ else:
672
+ if isinstance(limits, list):
673
+ # This should be a list of dicts of library info, for
674
+ # compatibility with the result from threadpool_info.
675
+ limits = {
676
+ lib_info["prefix"]: lib_info["num_threads"] for lib_info in limits
677
+ }
678
+ elif isinstance(limits, ThreadpoolController):
679
+ # To set the limits from the library controllers of a
680
+ # ThreadpoolController object.
681
+ limits = {
682
+ lib_controller.prefix: lib_controller.num_threads
683
+ for lib_controller in limits.lib_controllers
684
+ }
685
+
686
+ if not isinstance(limits, dict):
687
+ raise TypeError(
688
+ "limits must either be an int, a list, a dict, or "
689
+ f"'sequential_blas_under_openmp'. Got {type(limits)} instead"
690
+ )
691
+
692
+ # With a dictionary, can set both specific limit for given
693
+ # libraries and global limit for user_api. Fetch each separately.
694
+ prefixes = [prefix for prefix in limits if prefix in _ALL_PREFIXES]
695
+ user_api = [api for api in limits if api in _ALL_USER_APIS]
696
+
697
+ return limits, user_api, prefixes
698
+
699
+ def _set_threadpool_limits(self):
700
+ """Change the maximal number of threads in selected thread pools.
701
+
702
+ Return a list with all the supported libraries that have been found
703
+ matching `self._prefixes` and `self._user_api`.
704
+ """
705
+ if self._limits is None:
706
+ return
707
+
708
+ for lib_controller in self._controller.lib_controllers:
709
+ # self._limits is a dict {key: num_threads} where key is either
710
+ # a prefix or a user_api. If a library matches both, the limit
711
+ # corresponding to the prefix is chosen.
712
+ if lib_controller.prefix in self._limits:
713
+ num_threads = self._limits[lib_controller.prefix]
714
+ elif lib_controller.user_api in self._limits:
715
+ num_threads = self._limits[lib_controller.user_api]
716
+ else:
717
+ continue
718
+
719
+ if num_threads is not None:
720
+ lib_controller.set_num_threads(num_threads)
721
+
722
+
723
+ class _ThreadpoolLimiterDecorator(_ThreadpoolLimiter, ContextDecorator):
724
+ """Same as _ThreadpoolLimiter but to be used as a decorator"""
725
+
726
+ def __init__(self, controller, *, limits=None, user_api=None):
727
+ self._limits, self._user_api, self._prefixes = self._check_params(
728
+ limits, user_api
729
+ )
730
+ self._controller = controller
731
+
732
+ def __enter__(self):
733
+ # we need to set the limits here and not in the __init__ because we want the
734
+ # limits to be set when calling the decorated function, not when creating the
735
+ # decorator.
736
+ self._original_info = self._controller.info()
737
+ self._set_threadpool_limits()
738
+ return self
739
+
740
+
741
+ @_format_docstring(
742
+ USER_APIS=", ".join(f'"{api}"' for api in _ALL_USER_APIS),
743
+ BLAS_LIBS=", ".join(_ALL_BLAS_LIBRARIES),
744
+ OPENMP_LIBS=", ".join(_ALL_OPENMP_LIBRARIES),
745
+ )
746
+ class threadpool_limits(_ThreadpoolLimiter):
747
+ """Change the maximal number of threads that can be used in thread pools.
748
+
749
+ This object can be used either as a callable (the construction of this object
750
+ limits the number of threads), as a context manager in a `with` block to
751
+ automatically restore the original state of the controlled libraries when exiting
752
+ the block, or as a decorator through its `wrap` method.
753
+
754
+ Set the maximal number of threads that can be used in thread pools used in
755
+ the supported libraries to `limit`. This function works for libraries that
756
+ are already loaded in the interpreter and can be changed dynamically.
757
+
758
+ This effect is global and impacts the whole Python process. There is no thread level
759
+ isolation as these libraries do not offer thread-local APIs to configure the number
760
+ of threads to use in nested parallel calls.
761
+
762
+ Parameters
763
+ ----------
764
+ limits : int, dict, 'sequential_blas_under_openmp' or None (default=None)
765
+ The maximal number of threads that can be used in thread pools
766
+
767
+ - If int, sets the maximum number of threads to `limits` for each
768
+ library selected by `user_api`.
769
+
770
+ - If it is a dictionary `{{key: max_threads}}`, this function sets a
771
+ custom maximum number of threads for each `key` which can be either a
772
+ `user_api` or a `prefix` for a specific library.
773
+
774
+ - If 'sequential_blas_under_openmp', it will chose the appropriate `limits`
775
+ and `user_api` parameters for the specific use case of sequential BLAS
776
+ calls within an OpenMP parallel region. The `user_api` parameter is
777
+ ignored.
778
+
779
+ - If None, this function does not do anything.
780
+
781
+ user_api : {USER_APIS} or None (default=None)
782
+ APIs of libraries to limit. Used only if `limits` is an int.
783
+
784
+ - If "blas", it will only limit BLAS supported libraries ({BLAS_LIBS}).
785
+
786
+ - If "openmp", it will only limit OpenMP supported libraries
787
+ ({OPENMP_LIBS}). Note that it can affect the number of threads used
788
+ by the BLAS libraries if they rely on OpenMP.
789
+
790
+ - If None, this function will apply to all supported libraries.
791
+ """
792
+
793
+ def __init__(self, limits=None, user_api=None):
794
+ super().__init__(ThreadpoolController(), limits=limits, user_api=user_api)
795
+
796
+ @classmethod
797
+ def wrap(cls, limits=None, user_api=None):
798
+ return super().wrap(ThreadpoolController(), limits=limits, user_api=user_api)
799
+
800
+
801
+ class ThreadpoolController:
802
+ """Collection of LibController objects for all loaded supported libraries
803
+
804
+ Attributes
805
+ ----------
806
+ lib_controllers : list of `LibController` objects
807
+ The list of library controllers of all loaded supported libraries.
808
+ """
809
+
810
+ # Cache for libc under POSIX and a few system libraries under Windows.
811
+ # We use a class level cache instead of an instance level cache because
812
+ # it's very unlikely that a shared library will be unloaded and reloaded
813
+ # during the lifetime of a program.
814
+ _system_libraries = dict()
815
+
816
+ def __init__(self):
817
+ self.lib_controllers = []
818
+ self._load_libraries()
819
+ self._warn_if_incompatible_openmp()
820
+
821
+ @classmethod
822
+ def _from_controllers(cls, lib_controllers):
823
+ new_controller = cls.__new__(cls)
824
+ new_controller.lib_controllers = lib_controllers
825
+ return new_controller
826
+
827
+ def info(self):
828
+ """Return lib_controllers info as a list of dicts"""
829
+ return [lib_controller.info() for lib_controller in self.lib_controllers]
830
+
831
+ def select(self, **kwargs):
832
+ """Return a ThreadpoolController containing a subset of its current
833
+ library controllers
834
+
835
+ It will select all libraries matching at least one pair (key, value) from kwargs
836
+ where key is an entry of the library info dict (like "user_api", "internal_api",
837
+ "prefix", ...) and value is the value or a list of acceptable values for that
838
+ entry.
839
+
840
+ For instance, `ThreadpoolController().select(internal_api=["blis", "openblas"])`
841
+ will select all library controllers whose internal_api is either "blis" or
842
+ "openblas".
843
+ """
844
+ for key, vals in kwargs.items():
845
+ kwargs[key] = [vals] if not isinstance(vals, list) else vals
846
+
847
+ lib_controllers = [
848
+ lib_controller
849
+ for lib_controller in self.lib_controllers
850
+ if any(
851
+ getattr(lib_controller, key, None) in vals
852
+ for key, vals in kwargs.items()
853
+ )
854
+ ]
855
+
856
+ return ThreadpoolController._from_controllers(lib_controllers)
857
+
858
+ def _get_params_for_sequential_blas_under_openmp(self):
859
+ """Return appropriate params to use for a sequential BLAS call in an OpenMP loop
860
+
861
+ This function takes into account the unexpected behavior of OpenBLAS with the
862
+ OpenMP threading layer.
863
+ """
864
+ if self.select(
865
+ internal_api="openblas", threading_layer="openmp"
866
+ ).lib_controllers:
867
+ return {"limits": None, "user_api": None}
868
+ return {"limits": 1, "user_api": "blas"}
869
+
870
+ @_format_docstring(
871
+ USER_APIS=", ".join('"{}"'.format(api) for api in _ALL_USER_APIS),
872
+ BLAS_LIBS=", ".join(_ALL_BLAS_LIBRARIES),
873
+ OPENMP_LIBS=", ".join(_ALL_OPENMP_LIBRARIES),
874
+ )
875
+ def limit(self, *, limits=None, user_api=None):
876
+ """Change the maximal number of threads that can be used in thread pools.
877
+
878
+ This function returns an object that can be used either as a callable (the
879
+ construction of this object limits the number of threads) or as a context
880
+ manager, in a `with` block to automatically restore the original state of the
881
+ controlled libraries when exiting the block.
882
+
883
+ Set the maximal number of threads that can be used in thread pools used in
884
+ the supported libraries to `limits`. This function works for libraries that
885
+ are already loaded in the interpreter and can be changed dynamically.
886
+
887
+ This effect is global and impacts the whole Python process. There is no thread
888
+ level isolation as these libraries do not offer thread-local APIs to configure
889
+ the number of threads to use in nested parallel calls.
890
+
891
+ Parameters
892
+ ----------
893
+ limits : int, dict, 'sequential_blas_under_openmp' or None (default=None)
894
+ The maximal number of threads that can be used in thread pools
895
+
896
+ - If int, sets the maximum number of threads to `limits` for each
897
+ library selected by `user_api`.
898
+
899
+ - If it is a dictionary `{{key: max_threads}}`, this function sets a
900
+ custom maximum number of threads for each `key` which can be either a
901
+ `user_api` or a `prefix` for a specific library.
902
+
903
+ - If 'sequential_blas_under_openmp', it will chose the appropriate `limits`
904
+ and `user_api` parameters for the specific use case of sequential BLAS
905
+ calls within an OpenMP parallel region. The `user_api` parameter is
906
+ ignored.
907
+
908
+ - If None, this function does not do anything.
909
+
910
+ user_api : {USER_APIS} or None (default=None)
911
+ APIs of libraries to limit. Used only if `limits` is an int.
912
+
913
+ - If "blas", it will only limit BLAS supported libraries ({BLAS_LIBS}).
914
+
915
+ - If "openmp", it will only limit OpenMP supported libraries
916
+ ({OPENMP_LIBS}). Note that it can affect the number of threads used
917
+ by the BLAS libraries if they rely on OpenMP.
918
+
919
+ - If None, this function will apply to all supported libraries.
920
+ """
921
+ return _ThreadpoolLimiter(self, limits=limits, user_api=user_api)
922
+
923
+ @_format_docstring(
924
+ USER_APIS=", ".join('"{}"'.format(api) for api in _ALL_USER_APIS),
925
+ BLAS_LIBS=", ".join(_ALL_BLAS_LIBRARIES),
926
+ OPENMP_LIBS=", ".join(_ALL_OPENMP_LIBRARIES),
927
+ )
928
+ def wrap(self, *, limits=None, user_api=None):
929
+ """Change the maximal number of threads that can be used in thread pools.
930
+
931
+ This function returns an object that can be used as a decorator.
932
+
933
+ Set the maximal number of threads that can be used in thread pools used in
934
+ the supported libraries to `limits`. This function works for libraries that
935
+ are already loaded in the interpreter and can be changed dynamically.
936
+
937
+ Parameters
938
+ ----------
939
+ limits : int, dict or None (default=None)
940
+ The maximal number of threads that can be used in thread pools
941
+
942
+ - If int, sets the maximum number of threads to `limits` for each
943
+ library selected by `user_api`.
944
+
945
+ - If it is a dictionary `{{key: max_threads}}`, this function sets a
946
+ custom maximum number of threads for each `key` which can be either a
947
+ `user_api` or a `prefix` for a specific library.
948
+
949
+ - If None, this function does not do anything.
950
+
951
+ user_api : {USER_APIS} or None (default=None)
952
+ APIs of libraries to limit. Used only if `limits` is an int.
953
+
954
+ - If "blas", it will only limit BLAS supported libraries ({BLAS_LIBS}).
955
+
956
+ - If "openmp", it will only limit OpenMP supported libraries
957
+ ({OPENMP_LIBS}). Note that it can affect the number of threads used
958
+ by the BLAS libraries if they rely on OpenMP.
959
+
960
+ - If None, this function will apply to all supported libraries.
961
+ """
962
+ return _ThreadpoolLimiter.wrap(self, limits=limits, user_api=user_api)
963
+
964
+ def __len__(self):
965
+ return len(self.lib_controllers)
966
+
967
+ def _load_libraries(self):
968
+ """Loop through loaded shared libraries and store the supported ones"""
969
+ if sys.platform == "darwin":
970
+ self._find_libraries_with_dyld()
971
+ elif sys.platform == "win32":
972
+ self._find_libraries_with_enum_process_module_ex()
973
+ elif "pyodide" in sys.modules:
974
+ self._find_libraries_pyodide()
975
+ else:
976
+ self._find_libraries_with_dl_iterate_phdr()
977
+
978
+ def _find_libraries_with_dl_iterate_phdr(self):
979
+ """Loop through loaded libraries and return binders on supported ones
980
+
981
+ This function is expected to work on POSIX system only.
982
+ This code is adapted from code by Intel developer @anton-malakhov
983
+ available at https://github.com/IntelPython/smp
984
+
985
+ Copyright (c) 2017, Intel Corporation published under the BSD 3-Clause
986
+ license
987
+ """
988
+ libc = self._get_libc()
989
+ if not hasattr(libc, "dl_iterate_phdr"): # pragma: no cover
990
+ warnings.warn(
991
+ "Could not find dl_iterate_phdr in the C standard library.",
992
+ RuntimeWarning,
993
+ )
994
+ return []
995
+
996
+ # Callback function for `dl_iterate_phdr` which is called for every
997
+ # library loaded in the current process until it returns 1.
998
+ def match_library_callback(info, size, data):
999
+ # Get the path of the current library
1000
+ filepath = info.contents.dlpi_name
1001
+ if filepath:
1002
+ filepath = filepath.decode("utf-8")
1003
+
1004
+ # Store the library controller if it is supported and selected
1005
+ self._make_controller_from_path(filepath)
1006
+ return 0
1007
+
1008
+ c_func_signature = ctypes.CFUNCTYPE(
1009
+ ctypes.c_int, # Return type
1010
+ ctypes.POINTER(_dl_phdr_info),
1011
+ ctypes.c_size_t,
1012
+ ctypes.c_char_p,
1013
+ )
1014
+ c_match_library_callback = c_func_signature(match_library_callback)
1015
+
1016
+ data = ctypes.c_char_p(b"")
1017
+ libc.dl_iterate_phdr(c_match_library_callback, data)
1018
+
1019
+ def _find_libraries_with_dyld(self):
1020
+ """Loop through loaded libraries and return binders on supported ones
1021
+
1022
+ This function is expected to work on OSX system only
1023
+ """
1024
+ libc = self._get_libc()
1025
+ if not hasattr(libc, "_dyld_image_count"): # pragma: no cover
1026
+ warnings.warn(
1027
+ "Could not find _dyld_image_count in the C standard library.",
1028
+ RuntimeWarning,
1029
+ )
1030
+ return []
1031
+
1032
+ n_dyld = libc._dyld_image_count()
1033
+ libc._dyld_get_image_name.restype = ctypes.c_char_p
1034
+
1035
+ for i in range(n_dyld):
1036
+ filepath = ctypes.string_at(libc._dyld_get_image_name(i))
1037
+ filepath = filepath.decode("utf-8")
1038
+
1039
+ # Store the library controller if it is supported and selected
1040
+ self._make_controller_from_path(filepath)
1041
+
1042
+ def _find_libraries_with_enum_process_module_ex(self):
1043
+ """Loop through loaded libraries and return binders on supported ones
1044
+
1045
+ This function is expected to work on windows system only.
1046
+ This code is adapted from code by Philipp Hagemeister @phihag available
1047
+ at https://stackoverflow.com/questions/17474574
1048
+ """
1049
+ from ctypes.wintypes import DWORD, HMODULE, MAX_PATH
1050
+
1051
+ PROCESS_QUERY_INFORMATION = 0x0400
1052
+ PROCESS_VM_READ = 0x0010
1053
+
1054
+ LIST_LIBRARIES_ALL = 0x03
1055
+
1056
+ ps_api = self._get_windll("Psapi")
1057
+ kernel_32 = self._get_windll("kernel32")
1058
+
1059
+ h_process = kernel_32.OpenProcess(
1060
+ PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, os.getpid()
1061
+ )
1062
+ if not h_process: # pragma: no cover
1063
+ raise OSError(f"Could not open PID {os.getpid()}")
1064
+
1065
+ try:
1066
+ buf_count = 256
1067
+ needed = DWORD()
1068
+ # Grow the buffer until it becomes large enough to hold all the
1069
+ # module headers
1070
+ while True:
1071
+ buf = (HMODULE * buf_count)()
1072
+ buf_size = ctypes.sizeof(buf)
1073
+ if not ps_api.EnumProcessModulesEx(
1074
+ h_process,
1075
+ ctypes.byref(buf),
1076
+ buf_size,
1077
+ ctypes.byref(needed),
1078
+ LIST_LIBRARIES_ALL,
1079
+ ):
1080
+ raise OSError("EnumProcessModulesEx failed")
1081
+ if buf_size >= needed.value:
1082
+ break
1083
+ buf_count = needed.value // (buf_size // buf_count)
1084
+
1085
+ count = needed.value // (buf_size // buf_count)
1086
+ h_modules = map(HMODULE, buf[:count])
1087
+
1088
+ # Loop through all the module headers and get the library path
1089
+ # Allocate a buffer for the path 10 times the size of MAX_PATH to take
1090
+ # into account long path names.
1091
+ max_path = 10 * MAX_PATH
1092
+ buf = ctypes.create_unicode_buffer(max_path)
1093
+ n_size = DWORD()
1094
+ for h_module in h_modules:
1095
+ # Get the path of the current module
1096
+ if not ps_api.GetModuleFileNameExW(
1097
+ h_process, h_module, ctypes.byref(buf), ctypes.byref(n_size)
1098
+ ):
1099
+ raise OSError("GetModuleFileNameEx failed")
1100
+ filepath = buf.value
1101
+
1102
+ if len(filepath) == max_path: # pragma: no cover
1103
+ warnings.warn(
1104
+ "Could not get the full path of a dynamic library (path too "
1105
+ "long). This library will be ignored and threadpoolctl might "
1106
+ "not be able to control or display information about all "
1107
+ f"loaded libraries. Here's the truncated path: {filepath!r}",
1108
+ RuntimeWarning,
1109
+ )
1110
+ else:
1111
+ # Store the library controller if it is supported and selected
1112
+ self._make_controller_from_path(filepath)
1113
+ finally:
1114
+ kernel_32.CloseHandle(h_process)
1115
+
1116
+ def _find_libraries_pyodide(self):
1117
+ """Pyodide specific implementation for finding loaded libraries.
1118
+
1119
+ Adapted from suggestion in https://github.com/joblib/threadpoolctl/pull/169#issuecomment-1946696449.
1120
+
1121
+ One day, we may have a simpler solution. libc dl_iterate_phdr needs to
1122
+ be implemented in Emscripten and exposed in Pyodide, see
1123
+ https://github.com/emscripten-core/emscripten/issues/21354 for more
1124
+ details.
1125
+ """
1126
+ try:
1127
+ from pyodide_js._module import LDSO
1128
+ except ImportError:
1129
+ warnings.warn(
1130
+ "Unable to import LDSO from pyodide_js._module. This should never "
1131
+ "happen."
1132
+ )
1133
+ return
1134
+
1135
+ for filepath in LDSO.loadedLibsByName.as_object_map():
1136
+ # Some libraries are duplicated by Pyodide and do not exist in the
1137
+ # filesystem, so we first check for the existence of the file. For
1138
+ # more details, see
1139
+ # https://github.com/joblib/threadpoolctl/pull/169#issuecomment-1947946728
1140
+ if os.path.exists(filepath):
1141
+ self._make_controller_from_path(filepath)
1142
+
1143
+ def _make_controller_from_path(self, filepath):
1144
+ """Store a library controller if it is supported and selected"""
1145
+ # Required to resolve symlinks
1146
+ filepath = _realpath(filepath)
1147
+ # `lower` required to take account of OpenMP dll case on Windows
1148
+ # (vcomp, VCOMP, Vcomp, ...)
1149
+ filename = os.path.basename(filepath).lower()
1150
+
1151
+ # Loop through supported libraries to find if this filename corresponds
1152
+ # to a supported one.
1153
+ for controller_class in _ALL_CONTROLLERS:
1154
+ # check if filename matches a supported prefix
1155
+ prefix = self._check_prefix(filename, controller_class.filename_prefixes)
1156
+
1157
+ # filename does not match any of the prefixes of the candidate
1158
+ # library. move to next library.
1159
+ if prefix is None:
1160
+ continue
1161
+
1162
+ # workaround for BLAS libraries packaged by conda-forge on windows, which
1163
+ # are all renamed "libblas.dll". We thus have to check to which BLAS
1164
+ # implementation it actually corresponds looking for implementation
1165
+ # specific symbols.
1166
+ if prefix == "libblas":
1167
+ if filename.endswith(".dll"):
1168
+ libblas = ctypes.CDLL(filepath, _RTLD_NOLOAD)
1169
+ if not any(
1170
+ hasattr(libblas, func)
1171
+ for func in controller_class.check_symbols
1172
+ ):
1173
+ continue
1174
+ else:
1175
+ # We ignore libblas on other platforms than windows because there
1176
+ # might be a libblas dso comming with openblas for instance that
1177
+ # can't be used to instantiate a pertinent LibController (many
1178
+ # symbols are missing) and would create confusion by making a
1179
+ # duplicate entry in threadpool_info.
1180
+ continue
1181
+
1182
+ # filename matches a prefix. Now we check if the library has the symbols we
1183
+ # are looking for. If none of the symbols exists, it's very likely not the
1184
+ # expected library (e.g. a library having a common prefix with one of the
1185
+ # our supported libraries). Otherwise, create and store the library
1186
+ # controller.
1187
+ lib_controller = controller_class(
1188
+ filepath=filepath, prefix=prefix, parent=self
1189
+ )
1190
+
1191
+ if filepath in (lib.filepath for lib in self.lib_controllers):
1192
+ # We already have a controller for this library.
1193
+ continue
1194
+
1195
+ if not hasattr(controller_class, "check_symbols") or any(
1196
+ hasattr(lib_controller.dynlib, func)
1197
+ for func in controller_class.check_symbols
1198
+ ):
1199
+ self.lib_controllers.append(lib_controller)
1200
+
1201
+ def _check_prefix(self, library_basename, filename_prefixes):
1202
+ """Return the prefix library_basename starts with
1203
+
1204
+ Return None if none matches.
1205
+ """
1206
+ for prefix in filename_prefixes:
1207
+ if library_basename.startswith(prefix):
1208
+ return prefix
1209
+ return None
1210
+
1211
+ def _warn_if_incompatible_openmp(self):
1212
+ """Raise a warning if llvm-OpenMP and intel-OpenMP are both loaded"""
1213
+ prefixes = [lib_controller.prefix for lib_controller in self.lib_controllers]
1214
+ msg = textwrap.dedent(
1215
+ """
1216
+ Found Intel OpenMP ('libiomp') and LLVM OpenMP ('libomp') loaded at
1217
+ the same time. Both libraries are known to be incompatible and this
1218
+ can cause random crashes or deadlocks on Linux when loaded in the
1219
+ same Python program.
1220
+ Using threadpoolctl may cause crashes or deadlocks. For more
1221
+ information and possible workarounds, please see
1222
+ https://github.com/joblib/threadpoolctl/blob/master/multiple_openmp.md
1223
+ """
1224
+ )
1225
+ if "libomp" in prefixes and "libiomp" in prefixes:
1226
+ warnings.warn(msg, RuntimeWarning)
1227
+
1228
+ @classmethod
1229
+ def _get_libc(cls):
1230
+ """Load the lib-C for unix systems."""
1231
+ libc = cls._system_libraries.get("libc")
1232
+ if libc is None:
1233
+ # Remark: If libc is statically linked or if Python is linked against an
1234
+ # alternative implementation of libc like musl, find_library will return
1235
+ # None and CDLL will load the main program itself which should contain the
1236
+ # libc symbols. We still name it libc for convenience.
1237
+ # If the main program does not contain the libc symbols, it's ok because
1238
+ # we check their presence later anyway.
1239
+ libc = ctypes.CDLL(find_library("c"), mode=_RTLD_NOLOAD)
1240
+ cls._system_libraries["libc"] = libc
1241
+ return libc
1242
+
1243
+ @classmethod
1244
+ def _get_windll(cls, dll_name):
1245
+ """Load a windows DLL"""
1246
+ dll = cls._system_libraries.get(dll_name)
1247
+ if dll is None:
1248
+ dll = ctypes.WinDLL(f"{dll_name}.dll")
1249
+ cls._system_libraries[dll_name] = dll
1250
+ return dll
1251
+
1252
+
1253
+ def _main():
1254
+ """Commandline interface to display thread-pool information and exit."""
1255
+ import argparse
1256
+ import importlib
1257
+ import json
1258
+ import sys
1259
+
1260
+ parser = argparse.ArgumentParser(
1261
+ usage="python -m threadpoolctl -i numpy scipy.linalg xgboost",
1262
+ description="Display thread-pool information and exit.",
1263
+ )
1264
+ parser.add_argument(
1265
+ "-i",
1266
+ "--import",
1267
+ dest="modules",
1268
+ nargs="*",
1269
+ default=(),
1270
+ help="Python modules to import before introspecting thread-pools.",
1271
+ )
1272
+ parser.add_argument(
1273
+ "-c",
1274
+ "--command",
1275
+ help="a Python statement to execute before introspecting thread-pools.",
1276
+ )
1277
+
1278
+ options = parser.parse_args(sys.argv[1:])
1279
+ for module in options.modules:
1280
+ try:
1281
+ importlib.import_module(module, package=None)
1282
+ except ImportError:
1283
+ print("WARNING: could not import", module, file=sys.stderr)
1284
+
1285
+ if options.command:
1286
+ exec(options.command)
1287
+
1288
+ print(json.dumps(threadpool_info(), indent=2))
1289
+
1290
+
1291
+ if __name__ == "__main__":
1292
+ _main()
venv/lib/python3.10/site-packages/typing_extensions.py ADDED
The diff for this file is too large to render. See raw diff
 
venv/pyvenv.cfg ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ home = /usr/bin
2
+ include-system-site-packages = false
3
+ version = 3.10.12
venv/requirements.txt ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cffi
2
+ cpplint
3
+ Cython
4
+ decorator
5
+ docutils
6
+ dtlib
7
+ numpy>=1.23.5
8
+ pytest>=6.2.4
9
+ pytest_xdist>=2.2.1
10
+ packaging>=21.0
11
+ PyYAML
12
+ tqdm>=4.62.3
13
+ typing_extensions>=4.10.0
14
+ requests
15
+ attrs
16
+ cloudpickle
17
+ ml_dtypes
18
+ psutil
19
+ scipy
20
+ tornado
21
+ torch
22
+ thefuzz
23
+ tabulate