assassinlike commited on
Commit
628418d
·
verified ·
1 Parent(s): fdfa2b4

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. data/diffusion/.venv/lib/python3.11/site-packages/_distutils_hack/__init__.py +239 -0
  2. data/diffusion/.venv/lib/python3.11/site-packages/_distutils_hack/override.py +1 -0
  3. data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer/__main__.py +6 -0
  4. data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer/api.py +1065 -0
  5. data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer/cd.cpython-311-x86_64-linux-gnu.so +0 -0
  6. data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer/cd.py +467 -0
  7. data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer/constant.py +2055 -0
  8. data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer/legacy.py +79 -0
  9. data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer/md.cpython-311-x86_64-linux-gnu.so +0 -0
  10. data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer/md.py +1002 -0
  11. data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer/models.py +370 -0
  12. data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer/utils.py +455 -0
  13. data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer/version.py +8 -0
  14. data/diffusion/.venv/lib/python3.11/site-packages/packaging-26.2.dist-info/INSTALLER +1 -0
  15. data/diffusion/.venv/lib/python3.11/site-packages/packaging-26.2.dist-info/METADATA +112 -0
  16. data/diffusion/.venv/lib/python3.11/site-packages/packaging-26.2.dist-info/RECORD +29 -0
  17. data/diffusion/.venv/lib/python3.11/site-packages/packaging-26.2.dist-info/REQUESTED +0 -0
  18. data/diffusion/.venv/lib/python3.11/site-packages/packaging-26.2.dist-info/WHEEL +4 -0
  19. data/diffusion/.venv/lib/python3.11/site-packages/requests/__init__.py +219 -0
  20. data/diffusion/.venv/lib/python3.11/site-packages/requests/__version__.py +14 -0
  21. data/diffusion/.venv/lib/python3.11/site-packages/requests/_internal_utils.py +51 -0
  22. data/diffusion/.venv/lib/python3.11/site-packages/requests/_types.py +183 -0
  23. data/diffusion/.venv/lib/python3.11/site-packages/requests/adapters.py +748 -0
  24. data/diffusion/.venv/lib/python3.11/site-packages/requests/api.py +180 -0
  25. data/diffusion/.venv/lib/python3.11/site-packages/requests/auth.py +354 -0
  26. data/diffusion/.venv/lib/python3.11/site-packages/requests/certs.py +18 -0
  27. data/diffusion/.venv/lib/python3.11/site-packages/requests/compat.py +113 -0
  28. data/diffusion/.venv/lib/python3.11/site-packages/requests/cookies.py +625 -0
  29. data/diffusion/.venv/lib/python3.11/site-packages/requests/exceptions.py +162 -0
  30. data/diffusion/.venv/lib/python3.11/site-packages/requests/help.py +134 -0
  31. data/diffusion/.venv/lib/python3.11/site-packages/requests/hooks.py +48 -0
  32. data/diffusion/.venv/lib/python3.11/site-packages/requests/models.py +1180 -0
  33. data/diffusion/.venv/lib/python3.11/site-packages/requests/packages.py +23 -0
  34. data/diffusion/.venv/lib/python3.11/site-packages/requests/py.typed +0 -0
  35. data/diffusion/.venv/lib/python3.11/site-packages/requests/sessions.py +920 -0
  36. data/diffusion/.venv/lib/python3.11/site-packages/requests/status_codes.py +128 -0
  37. data/diffusion/.venv/lib/python3.11/site-packages/requests/structures.py +130 -0
  38. data/diffusion/.venv/lib/python3.11/site-packages/requests/utils.py +1155 -0
  39. data/diffusion/.venv/lib/python3.11/site-packages/setuptools-83.0.0.dist-info/INSTALLER +1 -0
  40. data/diffusion/.venv/lib/python3.11/site-packages/setuptools-83.0.0.dist-info/METADATA +140 -0
  41. data/diffusion/.venv/lib/python3.11/site-packages/setuptools-83.0.0.dist-info/RECORD +443 -0
  42. data/diffusion/.venv/lib/python3.11/site-packages/setuptools-83.0.0.dist-info/REQUESTED +0 -0
  43. data/diffusion/.venv/lib/python3.11/site-packages/setuptools-83.0.0.dist-info/WHEEL +5 -0
  44. data/diffusion/.venv/lib/python3.11/site-packages/setuptools-83.0.0.dist-info/entry_points.txt +51 -0
  45. data/diffusion/.venv/lib/python3.11/site-packages/setuptools-83.0.0.dist-info/top_level.txt +2 -0
  46. data/diffusion/.venv/lib/python3.11/site-packages/setuptools/__init__.py +256 -0
  47. data/diffusion/.venv/lib/python3.11/site-packages/setuptools/_discovery.py +33 -0
  48. data/diffusion/.venv/lib/python3.11/site-packages/setuptools/_entry_points.py +94 -0
  49. data/diffusion/.venv/lib/python3.11/site-packages/setuptools/_importlib.py +2 -0
  50. data/diffusion/.venv/lib/python3.11/site-packages/setuptools/_itertools.py +23 -0
data/diffusion/.venv/lib/python3.11/site-packages/_distutils_hack/__init__.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # don't import any costly modules
2
+ import os
3
+ import sys
4
+
5
+ report_url = (
6
+ "https://github.com/pypa/setuptools/issues/new?template=distutils-deprecation.yml"
7
+ )
8
+
9
+
10
+ def warn_distutils_present():
11
+ if 'distutils' not in sys.modules:
12
+ return
13
+ import warnings
14
+
15
+ warnings.warn(
16
+ "Distutils was imported before Setuptools, but importing Setuptools "
17
+ "also replaces the `distutils` module in `sys.modules`. This may lead "
18
+ "to undesirable behaviors or errors. To avoid these issues, avoid "
19
+ "using distutils directly, ensure that setuptools is installed in the "
20
+ "traditional way (e.g. not an editable install), and/or make sure "
21
+ "that setuptools is always imported before distutils."
22
+ )
23
+
24
+
25
+ def clear_distutils():
26
+ if 'distutils' not in sys.modules:
27
+ return
28
+ import warnings
29
+
30
+ warnings.warn(
31
+ "Setuptools is replacing distutils. Support for replacing "
32
+ "an already imported distutils is deprecated. In the future, "
33
+ "this condition will fail. "
34
+ f"Register concerns at {report_url}"
35
+ )
36
+ mods = [
37
+ name
38
+ for name in sys.modules
39
+ if name == "distutils" or name.startswith("distutils.")
40
+ ]
41
+ for name in mods:
42
+ del sys.modules[name]
43
+
44
+
45
+ def enabled():
46
+ """
47
+ Allow selection of distutils by environment variable.
48
+ """
49
+ which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'local')
50
+ if which == 'stdlib':
51
+ import warnings
52
+
53
+ warnings.warn(
54
+ "Reliance on distutils from stdlib is deprecated. Users "
55
+ "must rely on setuptools to provide the distutils module. "
56
+ "Avoid importing distutils or import setuptools first, "
57
+ "and avoid setting SETUPTOOLS_USE_DISTUTILS=stdlib. "
58
+ f"Register concerns at {report_url}"
59
+ )
60
+ return which == 'local'
61
+
62
+
63
+ def ensure_local_distutils():
64
+ import importlib
65
+
66
+ clear_distutils()
67
+
68
+ # With the DistutilsMetaFinder in place,
69
+ # perform an import to cause distutils to be
70
+ # loaded from setuptools._distutils. Ref #2906.
71
+ with shim():
72
+ importlib.import_module('distutils')
73
+
74
+ # check that submodules load as expected
75
+ core = importlib.import_module('distutils.core')
76
+ assert '_distutils' in core.__file__, core.__file__
77
+ assert 'setuptools._distutils.log' not in sys.modules
78
+
79
+
80
+ def do_override():
81
+ """
82
+ Ensure that the local copy of distutils is preferred over stdlib.
83
+
84
+ See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401
85
+ for more motivation.
86
+ """
87
+ if enabled():
88
+ warn_distutils_present()
89
+ ensure_local_distutils()
90
+
91
+
92
+ class _TrivialRe:
93
+ def __init__(self, *patterns) -> None:
94
+ self._patterns = patterns
95
+
96
+ def match(self, string):
97
+ return all(pat in string for pat in self._patterns)
98
+
99
+
100
+ class DistutilsMetaFinder:
101
+ def find_spec(self, fullname, path, target=None):
102
+ # optimization: only consider top level modules and those
103
+ # found in the CPython test suite.
104
+ if path is not None and not fullname.startswith('test.'):
105
+ return None
106
+
107
+ method_name = 'spec_for_{fullname}'.format(**locals())
108
+ method = getattr(self, method_name, lambda: None)
109
+ return method()
110
+
111
+ def spec_for_distutils(self):
112
+ if self.is_cpython():
113
+ return None
114
+
115
+ import importlib
116
+ import importlib.abc
117
+ import importlib.util
118
+
119
+ try:
120
+ mod = importlib.import_module('setuptools._distutils')
121
+ except Exception:
122
+ # There are a couple of cases where setuptools._distutils
123
+ # may not be present:
124
+ # - An older Setuptools without a local distutils is
125
+ # taking precedence. Ref #2957.
126
+ # - Path manipulation during sitecustomize removes
127
+ # setuptools from the path but only after the hook
128
+ # has been loaded. Ref #2980.
129
+ # In either case, fall back to stdlib behavior.
130
+ return None
131
+
132
+ class DistutilsLoader(importlib.abc.Loader):
133
+ def create_module(self, spec):
134
+ mod.__name__ = 'distutils'
135
+ return mod
136
+
137
+ def exec_module(self, module):
138
+ pass
139
+
140
+ return importlib.util.spec_from_loader(
141
+ 'distutils', DistutilsLoader(), origin=mod.__file__
142
+ )
143
+
144
+ @staticmethod
145
+ def is_cpython():
146
+ """
147
+ Suppress supplying distutils for CPython (build and tests).
148
+ Ref #2965 and #3007.
149
+ """
150
+ return os.path.isfile('pybuilddir.txt')
151
+
152
+ def spec_for_pip(self):
153
+ """
154
+ Ensure stdlib distutils when running under pip.
155
+ See pypa/pip#8761 for rationale.
156
+ """
157
+ if sys.version_info >= (3, 12) or self.pip_imported_during_build():
158
+ return
159
+ clear_distutils()
160
+ self.spec_for_distutils = lambda: None
161
+
162
+ @classmethod
163
+ def pip_imported_during_build(cls):
164
+ """
165
+ Detect if pip is being imported in a build script. Ref #2355.
166
+ """
167
+ import traceback
168
+
169
+ return any(
170
+ cls.frame_file_is_setup(frame) for frame, line in traceback.walk_stack(None)
171
+ )
172
+
173
+ @staticmethod
174
+ def frame_file_is_setup(frame):
175
+ """
176
+ Return True if the indicated frame suggests a setup.py file.
177
+ """
178
+ # some frames may not have __file__ (#2940)
179
+ return frame.f_globals.get('__file__', '').endswith('setup.py')
180
+
181
+ def spec_for_sensitive_tests(self):
182
+ """
183
+ Ensure stdlib distutils when running select tests under CPython.
184
+
185
+ python/cpython#91169
186
+ """
187
+ clear_distutils()
188
+ self.spec_for_distutils = lambda: None
189
+
190
+ sensitive_tests = (
191
+ [
192
+ 'test.test_distutils',
193
+ 'test.test_peg_generator',
194
+ 'test.test_importlib',
195
+ ]
196
+ if sys.version_info < (3, 10)
197
+ else [
198
+ 'test.test_distutils',
199
+ ]
200
+ )
201
+
202
+
203
+ for name in DistutilsMetaFinder.sensitive_tests:
204
+ setattr(
205
+ DistutilsMetaFinder,
206
+ f'spec_for_{name}',
207
+ DistutilsMetaFinder.spec_for_sensitive_tests,
208
+ )
209
+
210
+
211
+ DISTUTILS_FINDER = DistutilsMetaFinder()
212
+
213
+
214
+ def add_shim():
215
+ DISTUTILS_FINDER in sys.meta_path or insert_shim()
216
+
217
+
218
+ class shim:
219
+ def __enter__(self) -> None:
220
+ insert_shim()
221
+
222
+ def __exit__(self, exc: object, value: object, tb: object) -> None:
223
+ _remove_shim()
224
+
225
+
226
+ def insert_shim():
227
+ sys.meta_path.insert(0, DISTUTILS_FINDER)
228
+
229
+
230
+ def _remove_shim():
231
+ try:
232
+ sys.meta_path.remove(DISTUTILS_FINDER)
233
+ except ValueError:
234
+ pass
235
+
236
+
237
+ if sys.version_info < (3, 12):
238
+ # DistutilsMetaFinder can only be disabled in Python < 3.12 (PEP 632)
239
+ remove_shim = _remove_shim
data/diffusion/.venv/lib/python3.11/site-packages/_distutils_hack/override.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __import__('_distutils_hack').do_override()
data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer/__main__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from .cli import cli_detect
4
+
5
+ if __name__ == "__main__":
6
+ cli_detect()
data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer/api.py ADDED
@@ -0,0 +1,1065 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from functools import lru_cache
5
+ from os import PathLike
6
+ from typing import BinaryIO
7
+
8
+ from .cd import (
9
+ coherence_ratio,
10
+ encoding_languages,
11
+ mb_encoding_languages,
12
+ merge_coherence_ratios,
13
+ )
14
+ from .constant import (
15
+ IANA_SUPPORTED,
16
+ IANA_SUPPORTED_SIMILAR,
17
+ TOO_BIG_SEQUENCE,
18
+ TOO_SMALL_SEQUENCE,
19
+ TRACE,
20
+ )
21
+ from .md import mess_ratio
22
+ from .models import CharsetMatch, CharsetMatches
23
+ from .utils import (
24
+ any_specified_encoding,
25
+ cut_sequence_chunks,
26
+ iana_name,
27
+ identify_sig_or_bom,
28
+ is_multi_byte_encoding,
29
+ should_strip_sig_or_bom,
30
+ )
31
+
32
+ logger = logging.getLogger("charset_normalizer")
33
+ explain_handler = logging.StreamHandler()
34
+ explain_handler.setFormatter(
35
+ logging.Formatter("%(asctime)s | %(levelname)s | %(message)s")
36
+ )
37
+
38
+ # Pre-compute a reordered encoding list: multibyte first, then single-byte.
39
+ # This allows the mb_definitive_match optimization to fire earlier, skipping
40
+ # all single-byte encodings for genuine CJK content. Multibyte codecs
41
+ # hard-fail (UnicodeDecodeError) on single-byte data almost instantly, so
42
+ # testing them first costs negligible time for non-CJK files.
43
+ # Stable sort on a boolean key: multibyte (False) first, IANA order kept
44
+ # within each group.
45
+ IANA_SUPPORTED_MB_FIRST: list[str] = sorted(
46
+ IANA_SUPPORTED, key=lambda encoding: not is_multi_byte_encoding(encoding)
47
+ )
48
+
49
+
50
+ def from_bytes(
51
+ sequences: bytes | bytearray,
52
+ steps: int = 5,
53
+ chunk_size: int = 512,
54
+ threshold: float = 0.2,
55
+ cp_isolation: list[str] | None = None,
56
+ cp_exclusion: list[str] | None = None,
57
+ preemptive_behaviour: bool = True,
58
+ explain: bool = False,
59
+ language_threshold: float = 0.1,
60
+ enable_fallback: bool = True,
61
+ ) -> CharsetMatches:
62
+ """
63
+ Given a raw bytes sequence, return the best possibles charset usable to render str objects.
64
+ If there is no results, it is a strong indicator that the source is binary/not text.
65
+ By default, the process will extract 5 blocks of 512o each to assess the mess and coherence of a given sequence.
66
+ And will give up a particular code page after 20% of measured mess. Those criteria are customizable at will.
67
+
68
+ The preemptive behavior DOES NOT replace the traditional detection workflow, it prioritize a particular code page
69
+ but never take it for granted. Can improve the performance.
70
+
71
+ You may want to focus your attention to some code page or/and not others, use cp_isolation and cp_exclusion for that
72
+ purpose.
73
+
74
+ This function will strip the SIG in the payload/sequence every time except on UTF-16, UTF-32.
75
+ By default the library does not setup any handler other than the NullHandler, if you choose to set the 'explain'
76
+ toggle to True it will alter the logger configuration to add a StreamHandler that is suitable for debugging.
77
+ Custom logging format and handler can be set manually.
78
+ """
79
+
80
+ if not isinstance(sequences, (bytearray, bytes)):
81
+ raise TypeError(
82
+ "Expected object of type bytes or bytearray, got: {}".format(
83
+ type(sequences)
84
+ )
85
+ )
86
+
87
+ if explain:
88
+ previous_logger_level: int = logger.level
89
+ logger.addHandler(explain_handler)
90
+ logger.setLevel(TRACE)
91
+
92
+ length: int = len(sequences)
93
+
94
+ if length == 0:
95
+ logger.debug("Encoding detection on empty bytes, assuming utf_8 intention.")
96
+ if explain: # Defensive: ensure exit path clean handler
97
+ logger.removeHandler(explain_handler)
98
+ logger.setLevel(previous_logger_level)
99
+ return CharsetMatches([CharsetMatch(sequences, "utf_8", 0.0, False, [], "")])
100
+
101
+ if cp_isolation is not None:
102
+ logger.log(
103
+ TRACE,
104
+ "cp_isolation is set. use this flag for debugging purpose. "
105
+ "limited list of encoding allowed : %s.",
106
+ ", ".join(cp_isolation),
107
+ )
108
+ cp_isolation = [iana_name(cp, False) for cp in cp_isolation]
109
+ else:
110
+ cp_isolation = []
111
+
112
+ if cp_exclusion is not None:
113
+ logger.log(
114
+ TRACE,
115
+ "cp_exclusion is set. use this flag for debugging purpose. "
116
+ "limited list of encoding excluded : %s.",
117
+ ", ".join(cp_exclusion),
118
+ )
119
+ cp_exclusion = [iana_name(cp, False) for cp in cp_exclusion]
120
+ else:
121
+ cp_exclusion = []
122
+
123
+ if length <= (chunk_size * steps):
124
+ logger.log(
125
+ TRACE,
126
+ "override steps (%i) and chunk_size (%i) as content does not fit (%i byte(s) given) parameters.",
127
+ steps,
128
+ chunk_size,
129
+ length,
130
+ )
131
+ steps = 1
132
+ chunk_size = length
133
+
134
+ if steps > 1 and length / steps < chunk_size:
135
+ chunk_size = int(length / steps)
136
+
137
+ is_too_small_sequence: bool = len(sequences) < TOO_SMALL_SEQUENCE
138
+ is_too_large_sequence: bool = len(sequences) >= TOO_BIG_SEQUENCE
139
+
140
+ if is_too_small_sequence:
141
+ logger.log(
142
+ TRACE,
143
+ "Trying to detect encoding from a tiny portion of ({}) byte(s).".format(
144
+ length
145
+ ),
146
+ )
147
+ elif is_too_large_sequence:
148
+ logger.log(
149
+ TRACE,
150
+ "Using lazy str decoding because the payload is quite large, ({}) byte(s).".format(
151
+ length
152
+ ),
153
+ )
154
+
155
+ prioritized_encodings: list[str] = []
156
+
157
+ specified_encoding: str | None = (
158
+ any_specified_encoding(sequences) if preemptive_behaviour else None
159
+ )
160
+
161
+ if specified_encoding is not None:
162
+ prioritized_encodings.append(specified_encoding)
163
+ logger.log(
164
+ TRACE,
165
+ "Detected declarative mark in sequence. Priority +1 given for %s.",
166
+ specified_encoding,
167
+ )
168
+
169
+ tested: set[str] = set()
170
+ tested_but_hard_failure: list[str] = []
171
+ tested_but_soft_failure: list[str] = []
172
+ soft_failure_skip: set[str] = set()
173
+ success_fast_tracked: set[str] = set()
174
+
175
+ # Cache for decoded payload deduplication: hash(decoded_payload) -> (mean_mess_ratio, cd_ratios_merged, passed)
176
+ # When multiple encodings decode to the exact same string, we can skip the expensive
177
+ # mess_ratio and coherence_ratio analysis and reuse the results from the first encoding.
178
+ payload_result_cache: dict[int, tuple[float, list[tuple[str, float]], bool]] = {}
179
+
180
+ # Avoid unoptimized RSS usage.
181
+ # this cache is mostly interesting for
182
+ # local usage. Garbage collected at the
183
+ # end. Like it should.
184
+ cached_mess_ratio = lru_cache(maxsize=None)(mess_ratio)
185
+ cached_coherence_ratio = lru_cache(maxsize=None)(coherence_ratio)
186
+
187
+ # When a definitive result (chaos=0.0 and good coherence) is found after testing
188
+ # the prioritized encodings (ascii, utf_8), we can significantly reduce the remaining
189
+ # work. Encodings that target completely different language families (e.g., Cyrillic
190
+ # when the definitive match is Latin) are skipped entirely.
191
+ # Additionally, for same-family encodings that pass chaos probing, we reuse the
192
+ # definitive match's coherence ratios instead of recomputing them — a major savings
193
+ # since coherence_ratio accounts for ~30% of total time on slow Latin files.
194
+ definitive_match_found: bool = False
195
+ definitive_target_languages: set[str] = set()
196
+ # After the definitive match fires, we cap the number of additional same-family
197
+ # single-byte encodings that pass chaos probing. Once we've accumulated enough
198
+ # good candidates (N), further same-family SB encodings are unlikely to produce
199
+ # a better best() result and just waste mess_ratio + coherence_ratio time.
200
+ # The first encoding to trigger the definitive match is NOT counted (it's already in).
201
+ post_definitive_sb_success_count: int = 0
202
+ POST_DEFINITIVE_SB_CAP: int = 7
203
+
204
+ # When a non-UTF multibyte encoding passes chaos probing with significant multibyte
205
+ # content (decoded length < 98% of raw length), skip all remaining single-byte encodings.
206
+ # Rationale: multi-byte decoders (CJK) have strict byte-sequence validation — if they
207
+ # decode without error AND pass chaos probing with substantial multibyte content, the
208
+ # data is genuinely multibyte encoded. Single-byte encodings will always decode (every
209
+ # byte maps to something) but waste time on mess_ratio before failing.
210
+ # The 98% threshold prevents false triggers on files that happen to have a few valid
211
+ # multibyte pairs (e.g., cp424/_ude_1.txt where big5 decodes with 99% ratio).
212
+ mb_definitive_match_found: bool = False
213
+
214
+ fallback_ascii: CharsetMatch | None = None
215
+ fallback_u8: CharsetMatch | None = None
216
+ fallback_specified: CharsetMatch | None = None
217
+
218
+ results: CharsetMatches = CharsetMatches()
219
+
220
+ early_stop_results: CharsetMatches = CharsetMatches()
221
+
222
+ sig_encoding, sig_payload = identify_sig_or_bom(sequences)
223
+
224
+ if sig_encoding is not None:
225
+ prioritized_encodings.append(sig_encoding)
226
+ logger.log(
227
+ TRACE,
228
+ "Detected a SIG or BOM mark on first %i byte(s). Priority +1 given for %s.",
229
+ len(sig_payload),
230
+ sig_encoding,
231
+ )
232
+
233
+ prioritized_encodings.append("ascii")
234
+
235
+ if "utf_8" not in prioritized_encodings:
236
+ prioritized_encodings.append("utf_8")
237
+
238
+ for encoding_iana in prioritized_encodings + IANA_SUPPORTED_MB_FIRST:
239
+ if cp_isolation and encoding_iana not in cp_isolation:
240
+ continue
241
+
242
+ if cp_exclusion and encoding_iana in cp_exclusion:
243
+ continue
244
+
245
+ if encoding_iana in tested:
246
+ continue
247
+
248
+ tested.add(encoding_iana)
249
+
250
+ decoded_payload: str | None = None
251
+ bom_or_sig_available: bool = sig_encoding == encoding_iana
252
+ strip_sig_or_bom: bool = bom_or_sig_available and should_strip_sig_or_bom(
253
+ encoding_iana
254
+ )
255
+
256
+ if encoding_iana in {"utf_16", "utf_32"} and not bom_or_sig_available:
257
+ logger.log(
258
+ TRACE,
259
+ "Encoding %s won't be tested as-is because it require a BOM. Will try some sub-encoder LE/BE.",
260
+ encoding_iana,
261
+ )
262
+ continue
263
+ if encoding_iana in {"utf_7"} and not bom_or_sig_available:
264
+ logger.log(
265
+ TRACE,
266
+ "Encoding %s won't be tested as-is because detection is unreliable without BOM/SIG.",
267
+ encoding_iana,
268
+ )
269
+ continue
270
+
271
+ # Skip encodings similar to ones that already soft-failed (high mess ratio).
272
+ # Checked BEFORE the expensive decode attempt.
273
+ if encoding_iana in soft_failure_skip:
274
+ logger.log(
275
+ TRACE,
276
+ "%s is deemed too similar to a code page that was already considered unsuited. Continuing!",
277
+ encoding_iana,
278
+ )
279
+ continue
280
+
281
+ # Skip encodings that were already fast-tracked from a similar successful encoding.
282
+ if encoding_iana in success_fast_tracked:
283
+ logger.log(
284
+ TRACE,
285
+ "Skipping %s: already fast-tracked from a similar successful encoding.",
286
+ encoding_iana,
287
+ )
288
+ continue
289
+
290
+ try:
291
+ is_multi_byte_decoder: bool = is_multi_byte_encoding(encoding_iana)
292
+ except (ModuleNotFoundError, ImportError): # Defensive:
293
+ logger.log(
294
+ TRACE,
295
+ "Encoding %s does not provide an IncrementalDecoder",
296
+ encoding_iana,
297
+ )
298
+ continue
299
+
300
+ # When we've already found a definitive match (chaos=0.0 with good coherence)
301
+ # after testing the prioritized encodings, skip encodings that target
302
+ # completely different language families. This avoids running expensive
303
+ # mess_ratio + coherence_ratio on clearly unrelated candidates (e.g., Cyrillic
304
+ # when the definitive match is Latin-based).
305
+ if definitive_match_found:
306
+ if not is_multi_byte_decoder:
307
+ enc_languages = set(encoding_languages(encoding_iana))
308
+ else:
309
+ enc_languages = set(mb_encoding_languages(encoding_iana))
310
+ if not enc_languages.intersection(definitive_target_languages):
311
+ logger.log(
312
+ TRACE,
313
+ "Skipping %s: definitive match already found, this encoding targets different languages (%s vs %s).",
314
+ encoding_iana,
315
+ enc_languages,
316
+ definitive_target_languages,
317
+ )
318
+ continue
319
+
320
+ # After the definitive match, cap the number of additional same-family
321
+ # single-byte encodings that pass chaos probing. This avoids testing the
322
+ # tail of rare, low-value same-family encodings (mac_iceland, cp860, etc.)
323
+ # that almost never change best() but each cost ~1-2ms of mess_ratio + coherence.
324
+ if (
325
+ definitive_match_found
326
+ and not is_multi_byte_decoder
327
+ and post_definitive_sb_success_count >= POST_DEFINITIVE_SB_CAP
328
+ ):
329
+ logger.log(
330
+ TRACE,
331
+ "Skipping %s: already accumulated %d same-family results after definitive match (cap=%d).",
332
+ encoding_iana,
333
+ post_definitive_sb_success_count,
334
+ POST_DEFINITIVE_SB_CAP,
335
+ )
336
+ continue
337
+
338
+ # When a multibyte encoding with significant multibyte content has already
339
+ # passed chaos probing, skip all single-byte encodings. They will either fail
340
+ # chaos probing (wasting mess_ratio time) or produce inferior results.
341
+ if mb_definitive_match_found and not is_multi_byte_decoder:
342
+ logger.log(
343
+ TRACE,
344
+ "Skipping single-byte %s: multi-byte definitive match already found.",
345
+ encoding_iana,
346
+ )
347
+ continue
348
+
349
+ # Single-byte candidates of regular size defer the expensive whole
350
+ # payload decode until after chunk probing: single-byte codecs are
351
+ # stateless (1 byte == 1 char) so decoding chunk slices is provably
352
+ # identical to slicing the decoded payload, and candidates rejected
353
+ # by chaos probing (the common case) never pay the full decode nor
354
+ # the payload hash.
355
+ deferred_decoding: bool = (
356
+ not is_multi_byte_decoder and not is_too_large_sequence
357
+ )
358
+
359
+ try:
360
+ if is_too_large_sequence and not is_multi_byte_decoder:
361
+ str(
362
+ (
363
+ sequences[: int(50e4)]
364
+ if not strip_sig_or_bom
365
+ else sequences[len(sig_payload) : int(50e4)]
366
+ ),
367
+ encoding=encoding_iana,
368
+ )
369
+ elif not deferred_decoding:
370
+ # UTF-7 BOM is encoded in modified Base64 whose byte boundary
371
+ # can overlap with the next character. Stripping raw SIG bytes
372
+ # before decoding may leave stray bytes that decode as garbage.
373
+ # Decode the full sequence and remove the leading BOM char instead.
374
+ # see https://github.com/jawah/charset_normalizer/issues/718
375
+ # and https://github.com/jawah/charset_normalizer/issues/716
376
+ if encoding_iana == "utf_7" and bom_or_sig_available:
377
+ decoded_payload = str(
378
+ sequences,
379
+ encoding=encoding_iana,
380
+ )
381
+ if decoded_payload and decoded_payload[0] == "\ufeff":
382
+ decoded_payload = decoded_payload[1:]
383
+ else:
384
+ decoded_payload = str(
385
+ (
386
+ sequences
387
+ if not strip_sig_or_bom
388
+ else sequences[len(sig_payload) :]
389
+ ),
390
+ encoding=encoding_iana,
391
+ )
392
+ except (UnicodeDecodeError, LookupError) as e:
393
+ if not isinstance(e, LookupError):
394
+ logger.log(
395
+ TRACE,
396
+ "Code page %s does not fit given bytes sequence at ALL. %s",
397
+ encoding_iana,
398
+ str(e),
399
+ )
400
+ tested_but_hard_failure.append(encoding_iana)
401
+ continue
402
+
403
+ r_ = range(
404
+ 0 if not bom_or_sig_available else len(sig_payload),
405
+ length,
406
+ int(length / steps),
407
+ )
408
+
409
+ multi_byte_bonus: bool = (
410
+ is_multi_byte_decoder
411
+ and decoded_payload is not None
412
+ and len(decoded_payload) < length
413
+ )
414
+
415
+ if multi_byte_bonus:
416
+ logger.log(
417
+ TRACE,
418
+ "Code page %s is a multi byte encoding table and it appear that at least one character "
419
+ "was encoded using n-bytes.",
420
+ encoding_iana,
421
+ )
422
+
423
+ max_chunk_gave_up: int = int(len(r_) / 4)
424
+
425
+ max_chunk_gave_up = max(max_chunk_gave_up, 2)
426
+ early_stop_count: int = 0
427
+ lazy_str_hard_failure = False
428
+
429
+ md_chunks: list[str] = []
430
+ md_ratios = []
431
+
432
+ try:
433
+ for chunk in cut_sequence_chunks(
434
+ sequences,
435
+ encoding_iana,
436
+ r_,
437
+ chunk_size,
438
+ bom_or_sig_available,
439
+ strip_sig_or_bom,
440
+ sig_payload,
441
+ is_multi_byte_decoder,
442
+ decoded_payload,
443
+ deferred_decoding,
444
+ ):
445
+ md_chunks.append(chunk)
446
+
447
+ md_ratios.append(
448
+ cached_mess_ratio(
449
+ chunk,
450
+ threshold,
451
+ explain and 1 <= len(cp_isolation) <= 2,
452
+ )
453
+ )
454
+
455
+ if md_ratios[-1] >= threshold:
456
+ early_stop_count += 1
457
+
458
+ if (early_stop_count >= max_chunk_gave_up) or (
459
+ bom_or_sig_available and not strip_sig_or_bom
460
+ ):
461
+ break
462
+ except (
463
+ UnicodeDecodeError,
464
+ LookupError,
465
+ ) as e: # Lazy str loading may have missed something there
466
+ if deferred_decoding:
467
+ # Deferred single-byte validation failed on a chunk (or the
468
+ # codec is unavailable on this interpreter build): identical
469
+ # outcome and bookkeeping to the eager full-decode failure.
470
+ logger.log(
471
+ TRACE,
472
+ "Code page %s does not fit given bytes sequence at ALL. %s",
473
+ encoding_iana,
474
+ str(e),
475
+ )
476
+ tested_but_hard_failure.append(encoding_iana)
477
+ continue
478
+ logger.log(
479
+ TRACE,
480
+ "LazyStr Loading: After MD chunk decode, code page %s does not fit given bytes sequence at ALL. %s",
481
+ encoding_iana,
482
+ str(e),
483
+ )
484
+ early_stop_count = max_chunk_gave_up
485
+ lazy_str_hard_failure = True
486
+
487
+ # We might want to check the sequence again with the whole content
488
+ # Only if initial MD tests passes
489
+ if (
490
+ not lazy_str_hard_failure
491
+ and is_too_large_sequence
492
+ and not is_multi_byte_decoder
493
+ ):
494
+ try:
495
+ sequences[int(50e3) :].decode(encoding_iana, errors="strict")
496
+ except UnicodeDecodeError as e:
497
+ logger.log(
498
+ TRACE,
499
+ "LazyStr Loading: After final lookup, code page %s does not fit given bytes sequence at ALL. %s",
500
+ encoding_iana,
501
+ str(e),
502
+ )
503
+ tested_but_hard_failure.append(encoding_iana)
504
+ continue
505
+
506
+ mean_mess_ratio: float = sum(md_ratios) / len(md_ratios) if md_ratios else 0.0
507
+ if mean_mess_ratio >= threshold or early_stop_count >= max_chunk_gave_up:
508
+ tested_but_soft_failure.append(encoding_iana)
509
+ if encoding_iana in IANA_SUPPORTED_SIMILAR:
510
+ soft_failure_skip.update(IANA_SUPPORTED_SIMILAR[encoding_iana])
511
+ # Cache this soft-failure so identical decoding from other encodings
512
+ # can be skipped immediately.
513
+ if decoded_payload is not None and not is_multi_byte_decoder:
514
+ payload_result_cache.setdefault(
515
+ hash(decoded_payload), (mean_mess_ratio, [], False)
516
+ )
517
+ logger.log(
518
+ TRACE,
519
+ "%s was excluded because of initial chaos probing. Gave up %i time(s). "
520
+ "Computed mean chaos is %f %%.",
521
+ encoding_iana,
522
+ early_stop_count,
523
+ round(mean_mess_ratio * 100, ndigits=3),
524
+ )
525
+ # Preparing those fallbacks in case we got nothing.
526
+ if (
527
+ enable_fallback
528
+ and encoding_iana
529
+ in ["ascii", "utf_8", specified_encoding, "utf_16", "utf_32"]
530
+ and not lazy_str_hard_failure
531
+ ):
532
+ # Always fully decode payload before.
533
+ # We've missed a UnicodeDecodeError proof
534
+ # while issuing release 3.4.8
535
+ # see https://github.com/jawah/charset_normalizer/issues/771
536
+ if decoded_payload is None:
537
+ try:
538
+ decoded_payload = str(
539
+ (
540
+ sequences
541
+ if not strip_sig_or_bom
542
+ else sequences[len(sig_payload) :]
543
+ ),
544
+ encoding=encoding_iana,
545
+ )
546
+ except (UnicodeDecodeError, LookupError):
547
+ logger.log(
548
+ TRACE,
549
+ "%s does not decode the whole payload: fallback entry withheld.",
550
+ encoding_iana,
551
+ )
552
+ continue
553
+ if is_too_large_sequence:
554
+ # Don't retain huge payload in RAM.
555
+ decoded_payload = None
556
+
557
+ fallback_entry = CharsetMatch(
558
+ sequences,
559
+ encoding_iana,
560
+ threshold,
561
+ bom_or_sig_available,
562
+ [],
563
+ decoded_payload,
564
+ preemptive_declaration=specified_encoding,
565
+ )
566
+ if encoding_iana == specified_encoding:
567
+ fallback_specified = fallback_entry
568
+ elif encoding_iana == "ascii":
569
+ fallback_ascii = fallback_entry
570
+ else:
571
+ fallback_u8 = fallback_entry
572
+ continue
573
+
574
+ if deferred_decoding:
575
+ # The candidate passed chaos probing: perform the whole payload
576
+ # decode (validation + payload reuse) that was deferred earlier.
577
+ try:
578
+ decoded_payload = str(
579
+ (
580
+ sequences
581
+ if not strip_sig_or_bom
582
+ else sequences[len(sig_payload) :]
583
+ ),
584
+ encoding=encoding_iana,
585
+ )
586
+ except (UnicodeDecodeError, LookupError) as e:
587
+ logger.log(
588
+ TRACE,
589
+ "Code page %s does not fit given bytes sequence at ALL. %s",
590
+ encoding_iana,
591
+ str(e),
592
+ )
593
+ tested_but_hard_failure.append(encoding_iana)
594
+ continue
595
+
596
+ # Payload-hash deduplication: if another encoding already decoded to the
597
+ # exact same string, reuse its mess_ratio and coherence results entirely.
598
+ # This is strictly more general than the old IANA_SUPPORTED_SIMILAR approach
599
+ # because it catches ALL identical decoding, not just pre-mapped ones.
600
+ if decoded_payload is not None and not is_multi_byte_decoder:
601
+ payload_hash: int = hash(decoded_payload)
602
+ cached = payload_result_cache.get(payload_hash)
603
+ if cached is not None:
604
+ cached_mess, cached_cd, cached_passed = cached
605
+ if cached_passed:
606
+ # The previous encoding with identical output passed chaos probing.
607
+ fast_match = CharsetMatch(
608
+ sequences,
609
+ encoding_iana,
610
+ cached_mess,
611
+ bom_or_sig_available,
612
+ cached_cd,
613
+ (
614
+ decoded_payload
615
+ if (
616
+ not is_too_large_sequence
617
+ or encoding_iana
618
+ in [specified_encoding, "ascii", "utf_8"]
619
+ )
620
+ else None
621
+ ),
622
+ preemptive_declaration=specified_encoding,
623
+ )
624
+ results.append(fast_match)
625
+ success_fast_tracked.add(encoding_iana)
626
+ logger.log(
627
+ TRACE,
628
+ "%s fast-tracked (identical decoded payload to a prior encoding, chaos=%f %%).",
629
+ encoding_iana,
630
+ round(cached_mess * 100, ndigits=3),
631
+ )
632
+
633
+ if (
634
+ encoding_iana in [specified_encoding, "ascii", "utf_8"]
635
+ and cached_mess < 0.1
636
+ ):
637
+ if cached_mess == 0.0:
638
+ logger.debug(
639
+ "Encoding detection: %s is most likely the one.",
640
+ fast_match.encoding,
641
+ )
642
+ if explain:
643
+ logger.removeHandler(explain_handler)
644
+ logger.setLevel(previous_logger_level)
645
+ return CharsetMatches([fast_match])
646
+ early_stop_results.append(fast_match)
647
+
648
+ if (
649
+ len(early_stop_results)
650
+ and (specified_encoding is None or specified_encoding in tested)
651
+ and "ascii" in tested
652
+ and "utf_8" in tested
653
+ ):
654
+ probable_result: CharsetMatch = early_stop_results.best() # type: ignore[assignment]
655
+ logger.debug(
656
+ "Encoding detection: %s is most likely the one.",
657
+ probable_result.encoding,
658
+ )
659
+ if explain:
660
+ logger.removeHandler(explain_handler)
661
+ logger.setLevel(previous_logger_level)
662
+ return CharsetMatches([probable_result])
663
+
664
+ continue
665
+ else:
666
+ # The previous encoding with identical output failed chaos
667
+ # probing. Unreachable when the current candidate passed
668
+ # probing on the identical payload (deterministic ratios),
669
+ # kept for structural parity with the historic flow.
670
+ tested_but_soft_failure.append(encoding_iana)
671
+ logger.log(
672
+ TRACE,
673
+ "%s fast-skipped (identical decoded payload to a prior encoding that failed chaos probing).",
674
+ encoding_iana,
675
+ )
676
+ # Prepare fallbacks for special encodings even when skipped.
677
+ if enable_fallback and encoding_iana in [
678
+ "ascii",
679
+ "utf_8",
680
+ specified_encoding,
681
+ "utf_16",
682
+ "utf_32",
683
+ ]:
684
+ fallback_entry = CharsetMatch(
685
+ sequences,
686
+ encoding_iana,
687
+ threshold,
688
+ bom_or_sig_available,
689
+ [],
690
+ decoded_payload,
691
+ preemptive_declaration=specified_encoding,
692
+ )
693
+ if encoding_iana == specified_encoding:
694
+ fallback_specified = fallback_entry
695
+ elif encoding_iana == "ascii":
696
+ fallback_ascii = fallback_entry
697
+ else:
698
+ fallback_u8 = fallback_entry
699
+ continue
700
+
701
+ logger.log(
702
+ TRACE,
703
+ "%s passed initial chaos probing. Mean measured chaos is %f %%",
704
+ encoding_iana,
705
+ round(mean_mess_ratio * 100, ndigits=3),
706
+ )
707
+
708
+ if not is_multi_byte_decoder:
709
+ target_languages: list[str] = encoding_languages(encoding_iana)
710
+ else:
711
+ target_languages = mb_encoding_languages(encoding_iana)
712
+
713
+ if target_languages:
714
+ logger.log(
715
+ TRACE,
716
+ "{} should target any language(s) of {}".format(
717
+ encoding_iana, str(target_languages)
718
+ ),
719
+ )
720
+
721
+ cd_ratios = []
722
+
723
+ # Run coherence detection on all chunks. We previously tried limiting to
724
+ # 1-2 chunks for post-definitive encodings to save time, but this caused
725
+ # coverage regressions by producing unrepresentative coherence scores.
726
+ # The SB cap and language-family skip optimizations provide sufficient
727
+ # speedup without sacrificing coherence accuracy.
728
+ if encoding_iana != "ascii":
729
+ # We shall skip the CD when its about ASCII
730
+ # Most of the time its not relevant to run "language-detection" on it.
731
+ lg_inclusion: str | None = (
732
+ ",".join(target_languages) if target_languages else None
733
+ )
734
+
735
+ for chunk in md_chunks:
736
+ chunk_languages = cached_coherence_ratio(
737
+ chunk,
738
+ language_threshold,
739
+ lg_inclusion,
740
+ )
741
+
742
+ cd_ratios.append(chunk_languages)
743
+
744
+ cd_ratios_merged = merge_coherence_ratios(cd_ratios)
745
+
746
+ if cd_ratios_merged:
747
+ logger.log(
748
+ TRACE,
749
+ "We detected language {} using {}".format(
750
+ cd_ratios_merged, encoding_iana
751
+ ),
752
+ )
753
+
754
+ current_match = CharsetMatch(
755
+ sequences,
756
+ encoding_iana,
757
+ mean_mess_ratio,
758
+ bom_or_sig_available,
759
+ cd_ratios_merged,
760
+ (
761
+ decoded_payload
762
+ if (
763
+ not is_too_large_sequence
764
+ or encoding_iana in [specified_encoding, "ascii", "utf_8"]
765
+ )
766
+ else None
767
+ ),
768
+ preemptive_declaration=specified_encoding,
769
+ )
770
+
771
+ results.append(current_match)
772
+
773
+ # Cache the successful result for payload-hash deduplication.
774
+ if decoded_payload is not None and not is_multi_byte_decoder:
775
+ payload_result_cache.setdefault(
776
+ hash(decoded_payload),
777
+ (mean_mess_ratio, cd_ratios_merged, True),
778
+ )
779
+
780
+ # Count post-definitive same-family SB successes for the early termination cap.
781
+ # Only count low-mess encodings (< 2%) toward the cap. High-mess encodings are
782
+ # marginal results that shouldn't prevent better-quality candidates from being
783
+ # tested. For example, iso8859_4 (mess=0%) should not be skipped just because
784
+ # 7 high-mess Latin encodings (cp1252 at 8%, etc.) were tried first.
785
+ if (
786
+ definitive_match_found
787
+ and not is_multi_byte_decoder
788
+ and mean_mess_ratio < 0.02
789
+ ):
790
+ post_definitive_sb_success_count += 1
791
+
792
+ if (
793
+ encoding_iana in [specified_encoding, "ascii", "utf_8"]
794
+ and mean_mess_ratio < 0.1
795
+ ):
796
+ # If md says nothing to worry about, then... stop immediately!
797
+ if mean_mess_ratio == 0.0:
798
+ logger.debug(
799
+ "Encoding detection: %s is most likely the one.",
800
+ current_match.encoding,
801
+ )
802
+ if explain: # Defensive: ensure exit path clean handler
803
+ logger.removeHandler(explain_handler)
804
+ logger.setLevel(previous_logger_level)
805
+ return CharsetMatches([current_match])
806
+
807
+ early_stop_results.append(current_match)
808
+
809
+ if (
810
+ len(early_stop_results)
811
+ and (specified_encoding is None or specified_encoding in tested)
812
+ and "ascii" in tested
813
+ and "utf_8" in tested
814
+ ):
815
+ probable_result = early_stop_results.best() # type: ignore[assignment]
816
+ logger.debug(
817
+ "Encoding detection: %s is most likely the one.",
818
+ probable_result.encoding, # type: ignore[union-attr]
819
+ )
820
+ if explain: # Defensive: ensure exit path clean handler
821
+ logger.removeHandler(explain_handler)
822
+ logger.setLevel(previous_logger_level)
823
+
824
+ return CharsetMatches([probable_result])
825
+
826
+ # Once we find a result with good coherence (>= 0.5) after testing the
827
+ # prioritized encodings (ascii, utf_8), activate "definitive mode": skip
828
+ # encodings that target completely different language families. This avoids
829
+ # running expensive mess_ratio + coherence_ratio on clearly unrelated
830
+ # candidates (e.g., Cyrillic encodings when the match is Latin-based).
831
+ # We require coherence >= 0.5 to avoid false positives (e.g., cp1251 decoding
832
+ # Hebrew text with 0.0 chaos but wrong language detection at coherence 0.33).
833
+ if not definitive_match_found and not is_multi_byte_decoder:
834
+ best_coherence = (
835
+ max((v for _, v in cd_ratios_merged), default=0.0)
836
+ if cd_ratios_merged
837
+ else 0.0
838
+ )
839
+ if best_coherence >= 0.5 and "ascii" in tested and "utf_8" in tested:
840
+ definitive_match_found = True
841
+ definitive_target_languages.update(target_languages)
842
+ logger.log(
843
+ TRACE,
844
+ "Definitive match found: %s (chaos=%.3f, coherence=%.2f). Encodings targeting different language families will be skipped.",
845
+ encoding_iana,
846
+ mean_mess_ratio,
847
+ best_coherence,
848
+ )
849
+
850
+ # When a non-UTF multibyte encoding passes chaos probing with significant
851
+ # multibyte content (decoded < 98% of raw), activate mb_definitive_match.
852
+ # This skips all remaining single-byte encodings which would either soft-fail
853
+ # (running expensive mess_ratio for nothing) or produce inferior results.
854
+ if (
855
+ not mb_definitive_match_found
856
+ and is_multi_byte_decoder
857
+ and multi_byte_bonus
858
+ and decoded_payload is not None
859
+ and len(decoded_payload) < length * 0.98
860
+ and encoding_iana
861
+ not in {
862
+ "utf_8",
863
+ "utf_8_sig",
864
+ "utf_16",
865
+ "utf_16_be",
866
+ "utf_16_le",
867
+ "utf_32",
868
+ "utf_32_be",
869
+ "utf_32_le",
870
+ "utf_7",
871
+ }
872
+ and "ascii" in tested
873
+ and "utf_8" in tested
874
+ ):
875
+ mb_definitive_match_found = True
876
+ logger.log(
877
+ TRACE,
878
+ "Multi-byte definitive match: %s (chaos=%.3f, decoded=%d/%d=%.1f%%). Single-byte encodings will be skipped.",
879
+ encoding_iana,
880
+ mean_mess_ratio,
881
+ len(decoded_payload),
882
+ length,
883
+ len(decoded_payload) / length * 100,
884
+ )
885
+
886
+ if encoding_iana == sig_encoding:
887
+ logger.debug(
888
+ "Encoding detection: %s is most likely the one as we detected a BOM or SIG within "
889
+ "the beginning of the sequence.",
890
+ encoding_iana,
891
+ )
892
+ if explain: # Defensive: ensure exit path clean handler
893
+ logger.removeHandler(explain_handler)
894
+ logger.setLevel(previous_logger_level)
895
+ return CharsetMatches([results[encoding_iana]])
896
+
897
+ if len(results) == 0:
898
+ if fallback_u8 or fallback_ascii or fallback_specified:
899
+ logger.log(
900
+ TRACE,
901
+ "Nothing got out of the detection process. Using ASCII/UTF-8/Specified fallback.",
902
+ )
903
+
904
+ if fallback_specified:
905
+ logger.debug(
906
+ "Encoding detection: %s will be used as a fallback match",
907
+ fallback_specified.encoding,
908
+ )
909
+ results.append(fallback_specified)
910
+ elif (
911
+ (fallback_u8 and fallback_ascii is None)
912
+ or (
913
+ fallback_u8
914
+ and fallback_ascii
915
+ and fallback_u8.fingerprint != fallback_ascii.fingerprint
916
+ )
917
+ or (fallback_u8 is not None)
918
+ ):
919
+ logger.debug("Encoding detection: utf_8 will be used as a fallback match")
920
+ results.append(fallback_u8)
921
+ elif fallback_ascii:
922
+ logger.debug("Encoding detection: ascii will be used as a fallback match")
923
+ results.append(fallback_ascii)
924
+
925
+ if results:
926
+ logger.debug(
927
+ "Encoding detection: Found %s as plausible (best-candidate) for content. With %i alternatives.",
928
+ results.best().encoding, # type: ignore
929
+ len(results) - 1,
930
+ )
931
+ else:
932
+ logger.debug("Encoding detection: Unable to determine any suitable charset.")
933
+
934
+ if explain:
935
+ logger.removeHandler(explain_handler)
936
+ logger.setLevel(previous_logger_level)
937
+
938
+ return results
939
+
940
+
941
+ def from_fp(
942
+ fp: BinaryIO,
943
+ steps: int = 5,
944
+ chunk_size: int = 512,
945
+ threshold: float = 0.20,
946
+ cp_isolation: list[str] | None = None,
947
+ cp_exclusion: list[str] | None = None,
948
+ preemptive_behaviour: bool = True,
949
+ explain: bool = False,
950
+ language_threshold: float = 0.1,
951
+ enable_fallback: bool = True,
952
+ ) -> CharsetMatches:
953
+ """
954
+ Same thing than the function from_bytes but using a file pointer that is already ready.
955
+ Will not close the file pointer.
956
+ """
957
+ return from_bytes(
958
+ fp.read(),
959
+ steps,
960
+ chunk_size,
961
+ threshold,
962
+ cp_isolation,
963
+ cp_exclusion,
964
+ preemptive_behaviour,
965
+ explain,
966
+ language_threshold,
967
+ enable_fallback,
968
+ )
969
+
970
+
971
+ def from_path(
972
+ path: str | bytes | PathLike, # type: ignore[type-arg]
973
+ steps: int = 5,
974
+ chunk_size: int = 512,
975
+ threshold: float = 0.20,
976
+ cp_isolation: list[str] | None = None,
977
+ cp_exclusion: list[str] | None = None,
978
+ preemptive_behaviour: bool = True,
979
+ explain: bool = False,
980
+ language_threshold: float = 0.1,
981
+ enable_fallback: bool = True,
982
+ ) -> CharsetMatches:
983
+ """
984
+ Same thing than the function from_bytes but with one extra step. Opening and reading given file path in binary mode.
985
+ Can raise IOError.
986
+ """
987
+ with open(path, "rb") as fp:
988
+ return from_fp(
989
+ fp,
990
+ steps,
991
+ chunk_size,
992
+ threshold,
993
+ cp_isolation,
994
+ cp_exclusion,
995
+ preemptive_behaviour,
996
+ explain,
997
+ language_threshold,
998
+ enable_fallback,
999
+ )
1000
+
1001
+
1002
+ def is_binary(
1003
+ fp_or_path_or_payload: PathLike | str | BinaryIO | bytes, # type: ignore[type-arg]
1004
+ steps: int = 5,
1005
+ chunk_size: int = 512,
1006
+ threshold: float = 0.20,
1007
+ cp_isolation: list[str] | None = None,
1008
+ cp_exclusion: list[str] | None = None,
1009
+ preemptive_behaviour: bool = True,
1010
+ explain: bool = False,
1011
+ language_threshold: float = 0.1,
1012
+ enable_fallback: bool = False,
1013
+ ) -> bool:
1014
+ """
1015
+ Detect if the given input (file, bytes, or path) points to a binary file. aka. not a string.
1016
+ Based on the same main heuristic algorithms and default kwargs at the sole exception that fallbacks match
1017
+ are disabled to be stricter around ASCII-compatible but unlikely to be a string.
1018
+ """
1019
+ if isinstance(fp_or_path_or_payload, (str, PathLike)):
1020
+ guesses = from_path(
1021
+ fp_or_path_or_payload,
1022
+ steps=steps,
1023
+ chunk_size=chunk_size,
1024
+ threshold=threshold,
1025
+ cp_isolation=cp_isolation,
1026
+ cp_exclusion=cp_exclusion,
1027
+ preemptive_behaviour=preemptive_behaviour,
1028
+ explain=explain,
1029
+ language_threshold=language_threshold,
1030
+ enable_fallback=enable_fallback,
1031
+ )
1032
+ elif isinstance(
1033
+ fp_or_path_or_payload,
1034
+ (
1035
+ bytes,
1036
+ bytearray,
1037
+ ),
1038
+ ):
1039
+ guesses = from_bytes(
1040
+ fp_or_path_or_payload,
1041
+ steps=steps,
1042
+ chunk_size=chunk_size,
1043
+ threshold=threshold,
1044
+ cp_isolation=cp_isolation,
1045
+ cp_exclusion=cp_exclusion,
1046
+ preemptive_behaviour=preemptive_behaviour,
1047
+ explain=explain,
1048
+ language_threshold=language_threshold,
1049
+ enable_fallback=enable_fallback,
1050
+ )
1051
+ else:
1052
+ guesses = from_fp(
1053
+ fp_or_path_or_payload,
1054
+ steps=steps,
1055
+ chunk_size=chunk_size,
1056
+ threshold=threshold,
1057
+ cp_isolation=cp_isolation,
1058
+ cp_exclusion=cp_exclusion,
1059
+ preemptive_behaviour=preemptive_behaviour,
1060
+ explain=explain,
1061
+ language_threshold=language_threshold,
1062
+ enable_fallback=enable_fallback,
1063
+ )
1064
+
1065
+ return not guesses
data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer/cd.cpython-311-x86_64-linux-gnu.so ADDED
Binary file (16 kB). View file
 
data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer/cd.py ADDED
@@ -0,0 +1,467 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import importlib
4
+ from codecs import IncrementalDecoder
5
+ from functools import lru_cache
6
+
7
+ from .constant import (
8
+ FREQUENCIES,
9
+ KO_NAMES,
10
+ LANGUAGE_SUPPORTED_COUNT,
11
+ TOO_SMALL_SEQUENCE,
12
+ ZH_NAMES,
13
+ _FREQUENCIES_SET,
14
+ _FREQUENCIES_RANK,
15
+ )
16
+ from .md import _ASCII_CHAR_INFO, _char_info, is_suspiciously_successive_range
17
+ from .models import CoherenceMatches
18
+ from .utils import (
19
+ is_multi_byte_encoding,
20
+ is_unicode_range_secondary,
21
+ )
22
+
23
+
24
+ def encoding_unicode_range(iana_name: str) -> list[str]:
25
+ """
26
+ Return associated unicode ranges in a single byte code page.
27
+ """
28
+ if is_multi_byte_encoding(iana_name):
29
+ raise OSError( # Defensive:
30
+ "Function not supported on multi-byte code page"
31
+ )
32
+
33
+ decoder = importlib.import_module(f"encodings.{iana_name}").IncrementalDecoder
34
+
35
+ p: IncrementalDecoder = decoder(errors="ignore")
36
+ seen_ranges: dict[str, int] = {}
37
+ character_count: int = 0
38
+
39
+ for i in range(0x40, 0xFF):
40
+ chunk: str = p.decode(bytes([i]))
41
+
42
+ if chunk:
43
+ chunk_codepoint = ord(chunk)
44
+ character_range: str | None = (
45
+ _ASCII_CHAR_INFO[chunk_codepoint].range
46
+ if chunk_codepoint < 128
47
+ else _char_info(chunk).range
48
+ )
49
+
50
+ if character_range is None:
51
+ continue
52
+
53
+ if not is_unicode_range_secondary(character_range):
54
+ if character_range not in seen_ranges:
55
+ seen_ranges[character_range] = 0
56
+ seen_ranges[character_range] += 1
57
+ character_count += 1
58
+
59
+ return sorted(
60
+ [
61
+ character_range
62
+ for character_range in seen_ranges
63
+ if seen_ranges[character_range] / character_count >= 0.15
64
+ ]
65
+ )
66
+
67
+
68
+ def unicode_range_languages(primary_range: str) -> list[str]:
69
+ """
70
+ Return inferred languages used with a unicode range.
71
+ """
72
+ languages: list[str] = []
73
+
74
+ for language, characters in FREQUENCIES.items():
75
+ for character in characters:
76
+ codepoint = ord(character)
77
+ info = (
78
+ _ASCII_CHAR_INFO[codepoint]
79
+ if codepoint < 128
80
+ else _char_info(character)
81
+ )
82
+ if info.range == primary_range:
83
+ languages.append(language)
84
+ break
85
+
86
+ return languages
87
+
88
+
89
+ @lru_cache()
90
+ def encoding_languages(iana_name: str) -> list[str]:
91
+ """
92
+ Single-byte encoding language association. Some code page are heavily linked to particular language(s).
93
+ This function does the correspondence.
94
+ """
95
+ try:
96
+ unicode_ranges: list[str] = encoding_unicode_range(iana_name)
97
+ except ImportError: # Defensive: encoding unavailable on this build.
98
+ return []
99
+
100
+ primary_range: str | None = None
101
+
102
+ for specified_range in unicode_ranges:
103
+ if "Latin" not in specified_range:
104
+ primary_range = specified_range
105
+ break
106
+
107
+ if primary_range is None:
108
+ return ["Latin Based"]
109
+
110
+ return unicode_range_languages(primary_range)
111
+
112
+
113
+ @lru_cache()
114
+ def mb_encoding_languages(iana_name: str) -> list[str]:
115
+ """
116
+ Multi-byte encoding language association. Some code page are heavily linked to particular language(s).
117
+ This function does the correspondence.
118
+ """
119
+ if (
120
+ iana_name.startswith("shift_")
121
+ or iana_name.startswith("iso2022_jp")
122
+ or iana_name.startswith("euc_j")
123
+ or iana_name == "cp932"
124
+ ):
125
+ return ["Japanese"]
126
+ if iana_name.startswith("gb") or iana_name in ZH_NAMES:
127
+ return ["Chinese"]
128
+ if iana_name.startswith("iso2022_kr") or iana_name in KO_NAMES:
129
+ return ["Korean"]
130
+
131
+ return []
132
+
133
+
134
+ @lru_cache(maxsize=LANGUAGE_SUPPORTED_COUNT)
135
+ def get_target_features(language: str) -> tuple[bool, bool]:
136
+ """
137
+ Determine main aspects from a supported language if it contains accents and if is pure Latin.
138
+ """
139
+ target_have_accents: bool = False
140
+ target_pure_latin: bool = True
141
+
142
+ for character in FREQUENCIES[language]:
143
+ codepoint = ord(character)
144
+ info = _ASCII_CHAR_INFO[codepoint] if codepoint < 128 else _char_info(character)
145
+ if not target_have_accents and info.accentuated:
146
+ target_have_accents = True
147
+ if target_pure_latin and not info.latin:
148
+ target_pure_latin = False
149
+
150
+ return target_have_accents, target_pure_latin
151
+
152
+
153
+ def alphabet_languages(
154
+ characters: list[str], ignore_non_latin: bool = False
155
+ ) -> list[str]:
156
+ """
157
+ Return associated languages associated to given characters.
158
+ """
159
+ languages: list[tuple[str, float]] = []
160
+
161
+ characters_set: frozenset[str] = frozenset(characters)
162
+ source_have_accents = False
163
+ for character in characters:
164
+ codepoint = ord(character)
165
+ info = _ASCII_CHAR_INFO[codepoint] if codepoint < 128 else _char_info(character)
166
+ if info.accentuated:
167
+ source_have_accents = True
168
+ break
169
+
170
+ for language, language_characters in FREQUENCIES.items():
171
+ target_have_accents, target_pure_latin = get_target_features(language)
172
+
173
+ if ignore_non_latin and not target_pure_latin:
174
+ continue
175
+
176
+ if not target_have_accents and source_have_accents:
177
+ continue
178
+
179
+ character_count: int = len(language_characters)
180
+
181
+ character_match_count: int = len(_FREQUENCIES_SET[language] & characters_set)
182
+
183
+ ratio: float = character_match_count / character_count
184
+
185
+ if ratio >= 0.2:
186
+ languages.append((language, ratio))
187
+
188
+ languages = sorted(languages, key=lambda x: x[1], reverse=True)
189
+
190
+ return [compatible_language[0] for compatible_language in languages]
191
+
192
+
193
+ def characters_popularity_compare(
194
+ language: str, ordered_characters: list[str]
195
+ ) -> float:
196
+ """
197
+ Determine if a ordered characters list (by occurrence from most appearance to rarest) match a particular language.
198
+ The result is a ratio between 0. (absolutely no correspondence) and 1. (near perfect fit).
199
+ Beware that is function is not strict on the match in order to ease the detection. (Meaning close match is 1.)
200
+ """
201
+ if language not in FREQUENCIES:
202
+ raise ValueError(f"{language} not available") # Defensive:
203
+
204
+ character_approved_count: int = 0
205
+ lang_rank: dict[str, int] = _FREQUENCIES_RANK[language]
206
+
207
+ ordered_characters_count: int = len(ordered_characters)
208
+ target_language_characters_count: int = len(FREQUENCIES[language])
209
+
210
+ large_alphabet: bool = target_language_characters_count > 26
211
+ large_alphabet_threshold: float = target_language_characters_count / 3
212
+
213
+ expected_projection_ratio: float = (
214
+ target_language_characters_count / ordered_characters_count
215
+ )
216
+
217
+ # Single pass: characters present in the language vocabulary, as
218
+ # (language rank, popularity rank) pairs. The scoring below only ever
219
+ # needs ranks, never the characters themselves.
220
+ common_lr: list[int] = []
221
+ common_orr: list[int] = []
222
+ for popularity_rank, character in enumerate(ordered_characters):
223
+ language_rank = lang_rank.get(character)
224
+ if language_rank is not None:
225
+ common_lr.append(language_rank)
226
+ common_orr.append(popularity_rank)
227
+
228
+ for character_rank_in_language, character_rank in zip(common_lr, common_orr):
229
+ character_rank_projection: int = int(character_rank * expected_projection_ratio)
230
+
231
+ if (
232
+ not large_alphabet
233
+ and abs(character_rank_projection - character_rank_in_language) > 4
234
+ ):
235
+ continue
236
+
237
+ if (
238
+ large_alphabet
239
+ and abs(character_rank_projection - character_rank_in_language)
240
+ < large_alphabet_threshold
241
+ ):
242
+ character_approved_count += 1
243
+ continue
244
+
245
+ if character_rank_in_language == 0:
246
+ # before_match_count is structurally 0 here (no pair can have a
247
+ # smaller language rank): the historic "before <= 4" acceptance
248
+ # always holds. (The symmetric "after_len == 0" case is
249
+ # impossible: language ranks are strictly below the language
250
+ # character count, hence after_len >= 1.)
251
+ character_approved_count += 1
252
+ continue
253
+
254
+ after_len: int = target_language_characters_count - character_rank_in_language
255
+
256
+ # Count how many characters appear "before" in both orderings, and
257
+ # how many appear "at or after" in both orderings. Both counts grow
258
+ # monotonically and the approval thresholds
259
+ # (before / rank >= 0.4 or after / after_len >= 0.4) are known
260
+ # upfront, expressed below as exact integer comparisons: exit as
261
+ # soon as one is crossed.
262
+ before_match_count: int = 0
263
+ after_match_count: int = 0
264
+
265
+ for lr_i, orr_i in zip(common_lr, common_orr):
266
+ if lr_i < character_rank_in_language:
267
+ if orr_i < character_rank:
268
+ before_match_count += 1
269
+ if 5 * before_match_count >= 2 * character_rank_in_language:
270
+ character_approved_count += 1
271
+ break
272
+ else:
273
+ if orr_i >= character_rank:
274
+ after_match_count += 1
275
+ if 5 * after_match_count >= 2 * after_len:
276
+ character_approved_count += 1
277
+ break
278
+
279
+ return character_approved_count / len(ordered_characters)
280
+
281
+
282
+ def alpha_unicode_split(decoded_sequence: str) -> list[str]:
283
+ """
284
+ Given a decoded text sequence, return a list of str. Unicode range / alphabet separation.
285
+ Ex. a text containing English/Latin with a bit a Hebrew will return two items in the resulting list;
286
+ One containing the latin letters and the other hebrew.
287
+ """
288
+ layers: dict[str, list[str]] = {}
289
+
290
+ # Fast path: track single-layer key to skip dict iteration for single-script text.
291
+ single_layer_key: str | None = None
292
+ multi_layer: bool = False
293
+
294
+ # Cache the last character_range and its resolved layer to avoid repeated
295
+ # is_suspiciously_successive_range calls for consecutive same-range chars.
296
+ prev_character_range: str | None = None
297
+ prev_layer_target: str | None = None
298
+
299
+ for character in decoded_sequence:
300
+ # Reuse the per-codepoint CharInfo cache: info.alpha and info.range
301
+ # are computed with the very same str.isalpha() / unicode_range()
302
+ # calls this loop historically made per character occurrence.
303
+ codepoint: int = ord(character)
304
+ if codepoint < 128:
305
+ info = _ASCII_CHAR_INFO[codepoint]
306
+ else:
307
+ info = _char_info(character)
308
+
309
+ if not info.alpha:
310
+ continue
311
+
312
+ character_range: str | None = info.range
313
+
314
+ if character_range is None:
315
+ continue
316
+
317
+ # Fast path: same range as previous character → reuse cached layer target.
318
+ if character_range == prev_character_range:
319
+ if prev_layer_target is not None:
320
+ layers[prev_layer_target].append(character)
321
+ continue
322
+
323
+ layer_target_range: str | None = None
324
+
325
+ if multi_layer:
326
+ for discovered_range in layers:
327
+ if not is_suspiciously_successive_range(
328
+ discovered_range, character_range
329
+ ):
330
+ layer_target_range = discovered_range
331
+ break
332
+ elif single_layer_key is not None:
333
+ if not is_suspiciously_successive_range(single_layer_key, character_range):
334
+ layer_target_range = single_layer_key
335
+
336
+ if layer_target_range is None:
337
+ layer_target_range = character_range
338
+
339
+ if layer_target_range not in layers:
340
+ layers[layer_target_range] = []
341
+ if single_layer_key is None:
342
+ single_layer_key = layer_target_range
343
+ else:
344
+ multi_layer = True
345
+
346
+ layers[layer_target_range].append(character)
347
+
348
+ # Cache for next iteration
349
+ prev_character_range = character_range
350
+ prev_layer_target = layer_target_range
351
+
352
+ return ["".join(chars).lower() for chars in layers.values()]
353
+
354
+
355
+ def merge_coherence_ratios(results: list[CoherenceMatches]) -> CoherenceMatches:
356
+ """
357
+ This function merge results previously given by the function coherence_ratio.
358
+ The return type is the same as coherence_ratio.
359
+ """
360
+ per_language_ratios: dict[str, list[float]] = {}
361
+ for result in results:
362
+ for sub_result in result:
363
+ language, ratio = sub_result
364
+ if language not in per_language_ratios:
365
+ per_language_ratios[language] = [ratio]
366
+ continue
367
+ per_language_ratios[language].append(ratio)
368
+
369
+ merge = [
370
+ (
371
+ language,
372
+ round(
373
+ sum(per_language_ratios[language]) / len(per_language_ratios[language]),
374
+ 4,
375
+ ),
376
+ )
377
+ for language in per_language_ratios
378
+ ]
379
+
380
+ return sorted(merge, key=lambda x: x[1], reverse=True)
381
+
382
+
383
+ def filter_alt_coherence_matches(results: CoherenceMatches) -> CoherenceMatches:
384
+ """
385
+ We shall NOT return "English—" in CoherenceMatches because it is an alternative
386
+ of "English". This function only keeps the best match and remove the em-dash in it.
387
+ """
388
+ index_results: dict[str, list[float]] = dict()
389
+
390
+ for result in results:
391
+ language, ratio = result
392
+ no_em_name: str = language.replace("—", "")
393
+
394
+ if no_em_name not in index_results:
395
+ index_results[no_em_name] = []
396
+
397
+ index_results[no_em_name].append(ratio)
398
+
399
+ if any(len(index_results[e]) > 1 for e in index_results):
400
+ filtered_results: CoherenceMatches = []
401
+
402
+ for language in index_results:
403
+ filtered_results.append((language, max(index_results[language])))
404
+
405
+ return filtered_results
406
+
407
+ return results
408
+
409
+
410
+ def coherence_ratio(
411
+ decoded_sequence: str, threshold: float = 0.1, lg_inclusion: str | None = None
412
+ ) -> CoherenceMatches:
413
+ """
414
+ Detect ANY language that can be identified in given sequence. The sequence will be analysed by layers.
415
+ A layer = Character extraction by alphabets/ranges.
416
+ """
417
+
418
+ results: list[tuple[str, float]] = []
419
+ ignore_non_latin: bool = False
420
+
421
+ sufficient_match_count: int = 0
422
+
423
+ lg_inclusion_list = lg_inclusion.split(",") if lg_inclusion is not None else []
424
+ if "Latin Based" in lg_inclusion_list:
425
+ ignore_non_latin = True
426
+ lg_inclusion_list.remove("Latin Based")
427
+
428
+ for layer in alpha_unicode_split(decoded_sequence):
429
+ # Native counting + stable sort reproduce Counter.most_common()
430
+ # ordering exactly (ties keep first-appearance order) without the
431
+ # interpreted Counter machinery in the compiled hot path.
432
+ char_counts: dict[str, int] = {}
433
+ for layer_character in layer:
434
+ char_counts[layer_character] = char_counts.get(layer_character, 0) + 1
435
+
436
+ character_count: int = len(layer)
437
+
438
+ if character_count <= TOO_SMALL_SEQUENCE:
439
+ continue
440
+
441
+ popular_character_ordered: list[str] = [
442
+ item[0]
443
+ for item in sorted(
444
+ char_counts.items(), key=lambda item: item[1], reverse=True
445
+ )
446
+ ]
447
+
448
+ for language in lg_inclusion_list or alphabet_languages(
449
+ popular_character_ordered, ignore_non_latin
450
+ ):
451
+ ratio: float = characters_popularity_compare(
452
+ language, popular_character_ordered
453
+ )
454
+
455
+ if ratio < threshold:
456
+ continue
457
+ elif ratio >= 0.8:
458
+ sufficient_match_count += 1
459
+
460
+ results.append((language, round(ratio, 4)))
461
+
462
+ if sufficient_match_count >= 3:
463
+ break
464
+
465
+ return sorted(
466
+ filter_alt_coherence_matches(results), key=lambda x: x[1], reverse=True
467
+ )
data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer/constant.py ADDED
@@ -0,0 +1,2055 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from codecs import BOM_UTF8, BOM_UTF16_BE, BOM_UTF16_LE, BOM_UTF32_BE, BOM_UTF32_LE
4
+ from encodings.aliases import aliases
5
+ from re import IGNORECASE
6
+ from re import compile as re_compile
7
+
8
+ # Contain for each eligible encoding a list of/item bytes SIG/BOM
9
+ ENCODING_MARKS: dict[str, bytes | list[bytes]] = {
10
+ "utf_8": BOM_UTF8,
11
+ "utf_7": [
12
+ b"\x2b\x2f\x76\x38",
13
+ b"\x2b\x2f\x76\x39",
14
+ b"\x2b\x2f\x76\x2b",
15
+ b"\x2b\x2f\x76\x2f",
16
+ ],
17
+ "gb18030": b"\x84\x31\x95\x33",
18
+ "utf_32": [BOM_UTF32_BE, BOM_UTF32_LE],
19
+ "utf_16": [BOM_UTF16_BE, BOM_UTF16_LE],
20
+ }
21
+
22
+ TOO_SMALL_SEQUENCE: int = 32
23
+ TOO_BIG_SEQUENCE: int = int(10e6)
24
+
25
+ UTF8_MAXIMAL_ALLOCATION: int = 1_112_064
26
+
27
+ # Up-to-date Unicode ucd/17.0.0
28
+ UNICODE_RANGES_COMBINED: dict[str, range] = {
29
+ "Control character": range(32),
30
+ "Basic Latin": range(32, 128),
31
+ "Latin-1 Supplement": range(128, 256),
32
+ "Latin Extended-A": range(256, 384),
33
+ "Latin Extended-B": range(384, 592),
34
+ "IPA Extensions": range(592, 688),
35
+ "Spacing Modifier Letters": range(688, 768),
36
+ "Combining Diacritical Marks": range(768, 880),
37
+ "Greek and Coptic": range(880, 1024),
38
+ "Cyrillic": range(1024, 1280),
39
+ "Cyrillic Supplement": range(1280, 1328),
40
+ "Armenian": range(1328, 1424),
41
+ "Hebrew": range(1424, 1536),
42
+ "Arabic": range(1536, 1792),
43
+ "Syriac": range(1792, 1872),
44
+ "Arabic Supplement": range(1872, 1920),
45
+ "Thaana": range(1920, 1984),
46
+ "NKo": range(1984, 2048),
47
+ "Samaritan": range(2048, 2112),
48
+ "Mandaic": range(2112, 2144),
49
+ "Syriac Supplement": range(2144, 2160),
50
+ "Arabic Extended-B": range(2160, 2208),
51
+ "Arabic Extended-A": range(2208, 2304),
52
+ "Devanagari": range(2304, 2432),
53
+ "Bengali": range(2432, 2560),
54
+ "Gurmukhi": range(2560, 2688),
55
+ "Gujarati": range(2688, 2816),
56
+ "Oriya": range(2816, 2944),
57
+ "Tamil": range(2944, 3072),
58
+ "Telugu": range(3072, 3200),
59
+ "Kannada": range(3200, 3328),
60
+ "Malayalam": range(3328, 3456),
61
+ "Sinhala": range(3456, 3584),
62
+ "Thai": range(3584, 3712),
63
+ "Lao": range(3712, 3840),
64
+ "Tibetan": range(3840, 4096),
65
+ "Myanmar": range(4096, 4256),
66
+ "Georgian": range(4256, 4352),
67
+ "Hangul Jamo": range(4352, 4608),
68
+ "Ethiopic": range(4608, 4992),
69
+ "Ethiopic Supplement": range(4992, 5024),
70
+ "Cherokee": range(5024, 5120),
71
+ "Unified Canadian Aboriginal Syllabics": range(5120, 5760),
72
+ "Ogham": range(5760, 5792),
73
+ "Runic": range(5792, 5888),
74
+ "Tagalog": range(5888, 5920),
75
+ "Hanunoo": range(5920, 5952),
76
+ "Buhid": range(5952, 5984),
77
+ "Tagbanwa": range(5984, 6016),
78
+ "Khmer": range(6016, 6144),
79
+ "Mongolian": range(6144, 6320),
80
+ "Unified Canadian Aboriginal Syllabics Extended": range(6320, 6400),
81
+ "Limbu": range(6400, 6480),
82
+ "Tai Le": range(6480, 6528),
83
+ "New Tai Lue": range(6528, 6624),
84
+ "Khmer Symbols": range(6624, 6656),
85
+ "Buginese": range(6656, 6688),
86
+ "Tai Tham": range(6688, 6832),
87
+ "Combining Diacritical Marks Extended": range(6832, 6912),
88
+ "Balinese": range(6912, 7040),
89
+ "Sundanese": range(7040, 7104),
90
+ "Batak": range(7104, 7168),
91
+ "Lepcha": range(7168, 7248),
92
+ "Ol Chiki": range(7248, 7296),
93
+ "Cyrillic Extended-C": range(7296, 7312),
94
+ "Georgian Extended": range(7312, 7360),
95
+ "Sundanese Supplement": range(7360, 7376),
96
+ "Vedic Extensions": range(7376, 7424),
97
+ "Phonetic Extensions": range(7424, 7552),
98
+ "Phonetic Extensions Supplement": range(7552, 7616),
99
+ "Combining Diacritical Marks Supplement": range(7616, 7680),
100
+ "Latin Extended Additional": range(7680, 7936),
101
+ "Greek Extended": range(7936, 8192),
102
+ "General Punctuation": range(8192, 8304),
103
+ "Superscripts and Subscripts": range(8304, 8352),
104
+ "Currency Symbols": range(8352, 8400),
105
+ "Combining Diacritical Marks for Symbols": range(8400, 8448),
106
+ "Letterlike Symbols": range(8448, 8528),
107
+ "Number Forms": range(8528, 8592),
108
+ "Arrows": range(8592, 8704),
109
+ "Mathematical Operators": range(8704, 8960),
110
+ "Miscellaneous Technical": range(8960, 9216),
111
+ "Control Pictures": range(9216, 9280),
112
+ "Optical Character Recognition": range(9280, 9312),
113
+ "Enclosed Alphanumerics": range(9312, 9472),
114
+ "Box Drawing": range(9472, 9600),
115
+ "Block Elements": range(9600, 9632),
116
+ "Geometric Shapes": range(9632, 9728),
117
+ "Miscellaneous Symbols": range(9728, 9984),
118
+ "Dingbats": range(9984, 10176),
119
+ "Miscellaneous Mathematical Symbols-A": range(10176, 10224),
120
+ "Supplemental Arrows-A": range(10224, 10240),
121
+ "Braille Patterns": range(10240, 10496),
122
+ "Supplemental Arrows-B": range(10496, 10624),
123
+ "Miscellaneous Mathematical Symbols-B": range(10624, 10752),
124
+ "Supplemental Mathematical Operators": range(10752, 11008),
125
+ "Miscellaneous Symbols and Arrows": range(11008, 11264),
126
+ "Glagolitic": range(11264, 11360),
127
+ "Latin Extended-C": range(11360, 11392),
128
+ "Coptic": range(11392, 11520),
129
+ "Georgian Supplement": range(11520, 11568),
130
+ "Tifinagh": range(11568, 11648),
131
+ "Ethiopic Extended": range(11648, 11744),
132
+ "Cyrillic Extended-A": range(11744, 11776),
133
+ "Supplemental Punctuation": range(11776, 11904),
134
+ "CJK Radicals Supplement": range(11904, 12032),
135
+ "Kangxi Radicals": range(12032, 12256),
136
+ "Ideographic Description Characters": range(12272, 12288),
137
+ "CJK Symbols and Punctuation": range(12288, 12352),
138
+ "Hiragana": range(12352, 12448),
139
+ "Katakana": range(12448, 12544),
140
+ "Bopomofo": range(12544, 12592),
141
+ "Hangul Compatibility Jamo": range(12592, 12688),
142
+ "Kanbun": range(12688, 12704),
143
+ "Bopomofo Extended": range(12704, 12736),
144
+ "CJK Strokes": range(12736, 12784),
145
+ "Katakana Phonetic Extensions": range(12784, 12800),
146
+ "Enclosed CJK Letters and Months": range(12800, 13056),
147
+ "CJK Compatibility": range(13056, 13312),
148
+ "CJK Unified Ideographs Extension A": range(13312, 19904),
149
+ "Yijing Hexagram Symbols": range(19904, 19968),
150
+ "CJK Unified Ideographs": range(19968, 40960),
151
+ "Yi Syllables": range(40960, 42128),
152
+ "Yi Radicals": range(42128, 42192),
153
+ "Lisu": range(42192, 42240),
154
+ "Vai": range(42240, 42560),
155
+ "Cyrillic Extended-B": range(42560, 42656),
156
+ "Bamum": range(42656, 42752),
157
+ "Modifier Tone Letters": range(42752, 42784),
158
+ "Latin Extended-D": range(42784, 43008),
159
+ "Syloti Nagri": range(43008, 43056),
160
+ "Common Indic Number Forms": range(43056, 43072),
161
+ "Phags-pa": range(43072, 43136),
162
+ "Saurashtra": range(43136, 43232),
163
+ "Devanagari Extended": range(43232, 43264),
164
+ "Kayah Li": range(43264, 43312),
165
+ "Rejang": range(43312, 43360),
166
+ "Hangul Jamo Extended-A": range(43360, 43392),
167
+ "Javanese": range(43392, 43488),
168
+ "Myanmar Extended-B": range(43488, 43520),
169
+ "Cham": range(43520, 43616),
170
+ "Myanmar Extended-A": range(43616, 43648),
171
+ "Tai Viet": range(43648, 43744),
172
+ "Meetei Mayek Extensions": range(43744, 43776),
173
+ "Ethiopic Extended-A": range(43776, 43824),
174
+ "Latin Extended-E": range(43824, 43888),
175
+ "Cherokee Supplement": range(43888, 43968),
176
+ "Meetei Mayek": range(43968, 44032),
177
+ "Hangul Syllables": range(44032, 55216),
178
+ "Hangul Jamo Extended-B": range(55216, 55296),
179
+ "High Surrogates": range(55296, 56192),
180
+ "High Private Use Surrogates": range(56192, 56320),
181
+ "Low Surrogates": range(56320, 57344),
182
+ "Private Use Area": range(57344, 63744),
183
+ "CJK Compatibility Ideographs": range(63744, 64256),
184
+ "Alphabetic Presentation Forms": range(64256, 64336),
185
+ "Arabic Presentation Forms-A": range(64336, 65024),
186
+ "Variation Selectors": range(65024, 65040),
187
+ "Vertical Forms": range(65040, 65056),
188
+ "Combining Half Marks": range(65056, 65072),
189
+ "CJK Compatibility Forms": range(65072, 65104),
190
+ "Small Form Variants": range(65104, 65136),
191
+ "Arabic Presentation Forms-B": range(65136, 65280),
192
+ "Halfwidth and Fullwidth Forms": range(65280, 65520),
193
+ "Specials": range(65520, 65536),
194
+ "Linear B Syllabary": range(65536, 65664),
195
+ "Linear B Ideograms": range(65664, 65792),
196
+ "Aegean Numbers": range(65792, 65856),
197
+ "Ancient Greek Numbers": range(65856, 65936),
198
+ "Ancient Symbols": range(65936, 66000),
199
+ "Phaistos Disc": range(66000, 66048),
200
+ "Lycian": range(66176, 66208),
201
+ "Carian": range(66208, 66272),
202
+ "Coptic Epact Numbers": range(66272, 66304),
203
+ "Old Italic": range(66304, 66352),
204
+ "Gothic": range(66352, 66384),
205
+ "Old Permic": range(66384, 66432),
206
+ "Ugaritic": range(66432, 66464),
207
+ "Old Persian": range(66464, 66528),
208
+ "Deseret": range(66560, 66640),
209
+ "Shavian": range(66640, 66688),
210
+ "Osmanya": range(66688, 66736),
211
+ "Osage": range(66736, 66816),
212
+ "Elbasan": range(66816, 66864),
213
+ "Caucasian Albanian": range(66864, 66928),
214
+ "Vithkuqi": range(66928, 67008),
215
+ "Todhri": range(67008, 67072),
216
+ "Linear A": range(67072, 67456),
217
+ "Latin Extended-F": range(67456, 67520),
218
+ "Cypriot Syllabary": range(67584, 67648),
219
+ "Imperial Aramaic": range(67648, 67680),
220
+ "Palmyrene": range(67680, 67712),
221
+ "Nabataean": range(67712, 67760),
222
+ "Hatran": range(67808, 67840),
223
+ "Phoenician": range(67840, 67872),
224
+ "Lydian": range(67872, 67904),
225
+ "Sidetic": range(67904, 67936),
226
+ "Meroitic Hieroglyphs": range(67968, 68000),
227
+ "Meroitic Cursive": range(68000, 68096),
228
+ "Kharoshthi": range(68096, 68192),
229
+ "Old South Arabian": range(68192, 68224),
230
+ "Old North Arabian": range(68224, 68256),
231
+ "Manichaean": range(68288, 68352),
232
+ "Avestan": range(68352, 68416),
233
+ "Inscriptional Parthian": range(68416, 68448),
234
+ "Inscriptional Pahlavi": range(68448, 68480),
235
+ "Psalter Pahlavi": range(68480, 68528),
236
+ "Old Turkic": range(68608, 68688),
237
+ "Old Hungarian": range(68736, 68864),
238
+ "Hanifi Rohingya": range(68864, 68928),
239
+ "Garay": range(68928, 69008),
240
+ "Rumi Numeral Symbols": range(69216, 69248),
241
+ "Yezidi": range(69248, 69312),
242
+ "Arabic Extended-C": range(69312, 69376),
243
+ "Old Sogdian": range(69376, 69424),
244
+ "Sogdian": range(69424, 69488),
245
+ "Old Uyghur": range(69488, 69552),
246
+ "Chorasmian": range(69552, 69600),
247
+ "Elymaic": range(69600, 69632),
248
+ "Brahmi": range(69632, 69760),
249
+ "Kaithi": range(69760, 69840),
250
+ "Sora Sompeng": range(69840, 69888),
251
+ "Chakma": range(69888, 69968),
252
+ "Mahajani": range(69968, 70016),
253
+ "Sharada": range(70016, 70112),
254
+ "Sinhala Archaic Numbers": range(70112, 70144),
255
+ "Khojki": range(70144, 70224),
256
+ "Multani": range(70272, 70320),
257
+ "Khudawadi": range(70320, 70400),
258
+ "Grantha": range(70400, 70528),
259
+ "Tulu-Tigalari": range(70528, 70656),
260
+ "Newa": range(70656, 70784),
261
+ "Tirhuta": range(70784, 70880),
262
+ "Siddham": range(71040, 71168),
263
+ "Modi": range(71168, 71264),
264
+ "Mongolian Supplement": range(71264, 71296),
265
+ "Takri": range(71296, 71376),
266
+ "Myanmar Extended-C": range(71376, 71424),
267
+ "Ahom": range(71424, 71504),
268
+ "Dogra": range(71680, 71760),
269
+ "Warang Citi": range(71840, 71936),
270
+ "Dives Akuru": range(71936, 72032),
271
+ "Nandinagari": range(72096, 72192),
272
+ "Zanabazar Square": range(72192, 72272),
273
+ "Soyombo": range(72272, 72368),
274
+ "Unified Canadian Aboriginal Syllabics Extended-A": range(72368, 72384),
275
+ "Pau Cin Hau": range(72384, 72448),
276
+ "Devanagari Extended-A": range(72448, 72544),
277
+ "Sharada Supplement": range(72544, 72576),
278
+ "Sunuwar": range(72640, 72704),
279
+ "Bhaiksuki": range(72704, 72816),
280
+ "Marchen": range(72816, 72896),
281
+ "Masaram Gondi": range(72960, 73056),
282
+ "Gunjala Gondi": range(73056, 73136),
283
+ "Tolong Siki": range(73136, 73200),
284
+ "Makasar": range(73440, 73472),
285
+ "Kawi": range(73472, 73568),
286
+ "Lisu Supplement": range(73648, 73664),
287
+ "Tamil Supplement": range(73664, 73728),
288
+ "Cuneiform": range(73728, 74752),
289
+ "Cuneiform Numbers and Punctuation": range(74752, 74880),
290
+ "Early Dynastic Cuneiform": range(74880, 75088),
291
+ "Cypro-Minoan": range(77712, 77824),
292
+ "Egyptian Hieroglyphs": range(77824, 78896),
293
+ "Egyptian Hieroglyph Format Controls": range(78896, 78944),
294
+ "Egyptian Hieroglyphs Extended-A": range(78944, 82944),
295
+ "Anatolian Hieroglyphs": range(82944, 83584),
296
+ "Gurung Khema": range(90368, 90432),
297
+ "Bamum Supplement": range(92160, 92736),
298
+ "Mro": range(92736, 92784),
299
+ "Tangsa": range(92784, 92880),
300
+ "Bassa Vah": range(92880, 92928),
301
+ "Pahawh Hmong": range(92928, 93072),
302
+ "Kirat Rai": range(93504, 93568),
303
+ "Medefaidrin": range(93760, 93856),
304
+ "Beria Erfe": range(93856, 93920),
305
+ "Miao": range(93952, 94112),
306
+ "Ideographic Symbols and Punctuation": range(94176, 94208),
307
+ "Tangut": range(94208, 100352),
308
+ "Tangut Components": range(100352, 101120),
309
+ "Khitan Small Script": range(101120, 101632),
310
+ "Tangut Supplement": range(101632, 101760),
311
+ "Tangut Components Supplement": range(101760, 101888),
312
+ "Kana Extended-B": range(110576, 110592),
313
+ "Kana Supplement": range(110592, 110848),
314
+ "Kana Extended-A": range(110848, 110896),
315
+ "Small Kana Extension": range(110896, 110960),
316
+ "Nushu": range(110960, 111360),
317
+ "Duployan": range(113664, 113824),
318
+ "Shorthand Format Controls": range(113824, 113840),
319
+ "Symbols for Legacy Computing Supplement": range(117760, 118464),
320
+ "Miscellaneous Symbols Supplement": range(118464, 118528),
321
+ "Znamenny Musical Notation": range(118528, 118736),
322
+ "Byzantine Musical Symbols": range(118784, 119040),
323
+ "Musical Symbols": range(119040, 119296),
324
+ "Ancient Greek Musical Notation": range(119296, 119376),
325
+ "Kaktovik Numerals": range(119488, 119520),
326
+ "Mayan Numerals": range(119520, 119552),
327
+ "Tai Xuan Jing Symbols": range(119552, 119648),
328
+ "Counting Rod Numerals": range(119648, 119680),
329
+ "Mathematical Alphanumeric Symbols": range(119808, 120832),
330
+ "Sutton SignWriting": range(120832, 121520),
331
+ "Latin Extended-G": range(122624, 122880),
332
+ "Glagolitic Supplement": range(122880, 122928),
333
+ "Cyrillic Extended-D": range(122928, 123024),
334
+ "Nyiakeng Puachue Hmong": range(123136, 123216),
335
+ "Toto": range(123536, 123584),
336
+ "Wancho": range(123584, 123648),
337
+ "Nag Mundari": range(124112, 124160),
338
+ "Ol Onal": range(124368, 124416),
339
+ "Tai Yo": range(124608, 124672),
340
+ "Ethiopic Extended-B": range(124896, 124928),
341
+ "Mende Kikakui": range(124928, 125152),
342
+ "Adlam": range(125184, 125280),
343
+ "Indic Siyaq Numbers": range(126064, 126144),
344
+ "Ottoman Siyaq Numbers": range(126208, 126288),
345
+ "Arabic Mathematical Alphabetic Symbols": range(126464, 126720),
346
+ "Mahjong Tiles": range(126976, 127024),
347
+ "Domino Tiles": range(127024, 127136),
348
+ "Playing Cards": range(127136, 127232),
349
+ "Enclosed Alphanumeric Supplement": range(127232, 127488),
350
+ "Enclosed Ideographic Supplement": range(127488, 127744),
351
+ "Miscellaneous Symbols and Pictographs": range(127744, 128512),
352
+ "Emoticons": range(128512, 128592),
353
+ "Ornamental Dingbats": range(128592, 128640),
354
+ "Transport and Map Symbols": range(128640, 128768),
355
+ "Alchemical Symbols": range(128768, 128896),
356
+ "Geometric Shapes Extended": range(128896, 129024),
357
+ "Supplemental Arrows-C": range(129024, 129280),
358
+ "Supplemental Symbols and Pictographs": range(129280, 129536),
359
+ "Chess Symbols": range(129536, 129648),
360
+ "Symbols and Pictographs Extended-A": range(129648, 129792),
361
+ "Symbols for Legacy Computing": range(129792, 130048),
362
+ "CJK Unified Ideographs Extension B": range(131072, 173792),
363
+ "CJK Unified Ideographs Extension C": range(173824, 177984),
364
+ "CJK Unified Ideographs Extension D": range(177984, 178208),
365
+ "CJK Unified Ideographs Extension E": range(178208, 183984),
366
+ "CJK Unified Ideographs Extension F": range(183984, 191472),
367
+ "CJK Unified Ideographs Extension I": range(191472, 192096),
368
+ "CJK Compatibility Ideographs Supplement": range(194560, 195104),
369
+ "CJK Unified Ideographs Extension G": range(196608, 201552),
370
+ "CJK Unified Ideographs Extension H": range(201552, 205744),
371
+ "CJK Unified Ideographs Extension J": range(205744, 210048),
372
+ "Tags": range(917504, 917632),
373
+ "Variation Selectors Supplement": range(917760, 918000),
374
+ "Supplementary Private Use Area-A": range(983040, 1048576),
375
+ "Supplementary Private Use Area-B": range(1048576, 1114112),
376
+ }
377
+
378
+
379
+ UNICODE_SECONDARY_RANGE_KEYWORD: list[str] = [
380
+ "Supplement",
381
+ "Extended",
382
+ "Extensions",
383
+ "Modifier",
384
+ "Marks",
385
+ "Punctuation",
386
+ "Symbols",
387
+ "Forms",
388
+ "Operators",
389
+ "Miscellaneous",
390
+ "Drawing",
391
+ "Block",
392
+ "Shapes",
393
+ "Supplemental",
394
+ "Tags",
395
+ ]
396
+
397
+ RE_POSSIBLE_ENCODING_INDICATION = re_compile(
398
+ r"(?:(?:encoding)|(?:charset)|(?:coding))(?:[\:= ]{1,10})(?:[\"\']?)([a-zA-Z0-9\-_]+)(?:[\"\']?)",
399
+ IGNORECASE,
400
+ )
401
+
402
+ IANA_NO_ALIASES = [
403
+ "cp720",
404
+ "cp737",
405
+ "cp856",
406
+ "cp874",
407
+ "cp875",
408
+ "cp1006",
409
+ "koi8_r",
410
+ "koi8_t",
411
+ "koi8_u",
412
+ ]
413
+
414
+ IANA_SUPPORTED: list[str] = sorted(
415
+ filter(
416
+ lambda x: not x.endswith("_codec") and x not in {"rot_13", "tactis", "mbcs"},
417
+ list(set(aliases.values())) + IANA_NO_ALIASES,
418
+ )
419
+ )
420
+
421
+ IANA_SUPPORTED_COUNT: int = len(IANA_SUPPORTED)
422
+
423
+ # pre-computed code page that are similar using the function cp_similarity.
424
+ IANA_SUPPORTED_SIMILAR: dict[str, list[str]] = {
425
+ "cp037": ["cp1026", "cp1140", "cp273", "cp500"],
426
+ "cp1026": ["cp037", "cp1140", "cp273", "cp500"],
427
+ "cp1125": ["cp866"],
428
+ "cp1140": ["cp037", "cp1026", "cp273", "cp500"],
429
+ "cp1250": ["iso8859_2"],
430
+ "cp1251": ["kz1048", "ptcp154"],
431
+ "cp1252": ["iso8859_15", "iso8859_9", "latin_1"],
432
+ "cp1253": ["iso8859_7"],
433
+ "cp1254": ["iso8859_15", "iso8859_9", "latin_1"],
434
+ "cp1257": ["iso8859_13"],
435
+ "cp273": ["cp037", "cp1026", "cp1140", "cp500"],
436
+ "cp437": ["cp850", "cp858", "cp860", "cp861", "cp862", "cp863", "cp865"],
437
+ "cp500": ["cp037", "cp1026", "cp1140", "cp273"],
438
+ "cp850": ["cp437", "cp857", "cp858", "cp865"],
439
+ "cp857": ["cp850", "cp858", "cp865"],
440
+ "cp858": ["cp437", "cp850", "cp857", "cp865"],
441
+ "cp860": ["cp437", "cp861", "cp862", "cp863", "cp865"],
442
+ "cp861": ["cp437", "cp860", "cp862", "cp863", "cp865"],
443
+ "cp862": ["cp437", "cp860", "cp861", "cp863", "cp865"],
444
+ "cp863": ["cp437", "cp860", "cp861", "cp862", "cp865"],
445
+ "cp865": ["cp437", "cp850", "cp857", "cp858", "cp860", "cp861", "cp862", "cp863"],
446
+ "cp866": ["cp1125"],
447
+ "iso8859_10": ["iso8859_14", "iso8859_15", "iso8859_4", "iso8859_9", "latin_1"],
448
+ "iso8859_11": ["tis_620"],
449
+ "iso8859_13": ["cp1257"],
450
+ "iso8859_14": [
451
+ "iso8859_10",
452
+ "iso8859_15",
453
+ "iso8859_16",
454
+ "iso8859_3",
455
+ "iso8859_9",
456
+ "latin_1",
457
+ ],
458
+ "iso8859_15": [
459
+ "cp1252",
460
+ "cp1254",
461
+ "iso8859_10",
462
+ "iso8859_14",
463
+ "iso8859_16",
464
+ "iso8859_3",
465
+ "iso8859_9",
466
+ "latin_1",
467
+ ],
468
+ "iso8859_16": [
469
+ "iso8859_14",
470
+ "iso8859_15",
471
+ "iso8859_2",
472
+ "iso8859_3",
473
+ "iso8859_9",
474
+ "latin_1",
475
+ ],
476
+ "iso8859_2": ["cp1250", "iso8859_16", "iso8859_4"],
477
+ "iso8859_3": ["iso8859_14", "iso8859_15", "iso8859_16", "iso8859_9", "latin_1"],
478
+ "iso8859_4": ["iso8859_10", "iso8859_2", "iso8859_9", "latin_1"],
479
+ "iso8859_7": ["cp1253"],
480
+ "iso8859_9": [
481
+ "cp1252",
482
+ "cp1254",
483
+ "cp1258",
484
+ "iso8859_10",
485
+ "iso8859_14",
486
+ "iso8859_15",
487
+ "iso8859_16",
488
+ "iso8859_3",
489
+ "iso8859_4",
490
+ "latin_1",
491
+ ],
492
+ "kz1048": ["cp1251", "ptcp154"],
493
+ "latin_1": [
494
+ "cp1252",
495
+ "cp1254",
496
+ "cp1258",
497
+ "iso8859_10",
498
+ "iso8859_14",
499
+ "iso8859_15",
500
+ "iso8859_16",
501
+ "iso8859_3",
502
+ "iso8859_4",
503
+ "iso8859_9",
504
+ ],
505
+ "mac_iceland": ["mac_roman", "mac_turkish"],
506
+ "mac_roman": ["mac_iceland", "mac_turkish"],
507
+ "mac_turkish": ["mac_iceland", "mac_roman"],
508
+ "ptcp154": ["cp1251", "kz1048"],
509
+ "tis_620": ["iso8859_11"],
510
+ }
511
+
512
+
513
+ CHARDET_CORRESPONDENCE: dict[str, str] = {
514
+ "iso2022_kr": "ISO-2022-KR",
515
+ "iso2022_jp": "ISO-2022-JP",
516
+ "euc_kr": "EUC-KR",
517
+ "tis_620": "TIS-620",
518
+ "utf_32": "UTF-32",
519
+ "euc_jp": "EUC-JP",
520
+ "koi8_r": "KOI8-R",
521
+ "iso8859_1": "ISO-8859-1",
522
+ "iso8859_2": "ISO-8859-2",
523
+ "iso8859_5": "ISO-8859-5",
524
+ "iso8859_6": "ISO-8859-6",
525
+ "iso8859_7": "ISO-8859-7",
526
+ "iso8859_8": "ISO-8859-8",
527
+ "utf_16": "UTF-16",
528
+ "cp855": "IBM855",
529
+ "mac_cyrillic": "MacCyrillic",
530
+ "gb2312": "GB2312",
531
+ "gb18030": "GB18030",
532
+ "cp932": "CP932",
533
+ "cp866": "IBM866",
534
+ "utf_8": "utf-8",
535
+ "utf_8_sig": "UTF-8-SIG",
536
+ "shift_jis": "SHIFT_JIS",
537
+ "big5": "Big5",
538
+ "cp1250": "windows-1250",
539
+ "cp1251": "windows-1251",
540
+ "cp1252": "Windows-1252",
541
+ "cp1253": "windows-1253",
542
+ "cp1255": "windows-1255",
543
+ "cp1256": "windows-1256",
544
+ "cp1254": "Windows-1254",
545
+ "cp949": "CP949",
546
+ }
547
+
548
+
549
+ COMMON_SAFE_ASCII_CHARACTERS: frozenset[str] = frozenset(
550
+ {
551
+ "<",
552
+ ">",
553
+ "=",
554
+ ":",
555
+ "/",
556
+ "&",
557
+ ";",
558
+ "{",
559
+ "}",
560
+ "[",
561
+ "]",
562
+ ",",
563
+ "|",
564
+ '"',
565
+ "-",
566
+ "(",
567
+ ")",
568
+ }
569
+ )
570
+
571
+ # Sample character sets — replace with full lists if needed
572
+ COMMON_CHINESE_CHARACTERS = "的一是在不了有和人这中大为上个国我以要他时来用们生到作地于出就分对成会可主发年动同工也能下过子说产种面而方后多定行学法所民得经十三之进着等部度家电力里如水化高自二理起小物现实加量都两体制机当使点从业本去把性好应开它合还因由其些然前外天政四日那社义事平形相全表间样与关各重新线内数正心反你明看原又么利比或但质气第向道命此变条只没结解问意建月公无系军很情者最立代想已通并提直题党程展五果料象员革位入常文总次品式活设及管特件长求老头基资边流路级少图山统接知较将组见计别她手角期根论运农指几九区强放决西被干做必战先回则任取据处队南给色光门即保治北造百规热领七海口东导器压志世金增争济阶油思术极交受联什认六共权收证改清己美再采转更单风切打白教速花带安场身车例真务具万每目至达走积示议声报斗完类八离华名确才科张信马节话米整空元况今集温传土许步群广石记需段研界拉林律叫且究观越织装影算低持音众书布复容儿须际商非验连断深难近矿千周委素技备半办青省列习响约支般史感劳便团往酸历市克何除消构府太准精值号率族维划选标写存候毛亲快效斯院查江型眼王按格养易置派层片始却专状育厂京识适属圆包火住调满县局照参红细引听该铁价严龙飞"
573
+
574
+ COMMON_JAPANESE_CHARACTERS = "日一国年大十二本中長出三時行見月分後前生五間上東四今金九入学高円子外八六下来気小七山話女北午百書先名川千水半男西電校語土木聞食車何南万毎白天母火右読友左休父雨"
575
+
576
+ COMMON_KOREAN_CHARACTERS = "一二三四五六七八九十百千萬上下左右中人女子大小山川日月火水木金土父母天地國名年時文校學生"
577
+
578
+ # Combine all into a frozenset
579
+ COMMON_CJK_CHARACTERS = frozenset(
580
+ "".join(
581
+ [
582
+ COMMON_CHINESE_CHARACTERS,
583
+ COMMON_JAPANESE_CHARACTERS,
584
+ COMMON_KOREAN_CHARACTERS,
585
+ ]
586
+ )
587
+ )
588
+
589
+ KO_NAMES: frozenset[str] = frozenset({"johab", "cp949", "euc_kr"})
590
+ ZH_NAMES: frozenset[str] = frozenset({"big5", "cp950", "big5hkscs", "hz"})
591
+
592
+ # Logging LEVEL below DEBUG
593
+ TRACE: int = 5
594
+
595
+
596
+ # Language label that contain the em dash "—"
597
+ # character are to be considered alternative seq to origin
598
+ FREQUENCIES: dict[str, list[str]] = {
599
+ "English": [
600
+ "e",
601
+ "a",
602
+ "t",
603
+ "i",
604
+ "o",
605
+ "n",
606
+ "s",
607
+ "r",
608
+ "h",
609
+ "l",
610
+ "d",
611
+ "c",
612
+ "u",
613
+ "m",
614
+ "f",
615
+ "p",
616
+ "g",
617
+ "w",
618
+ "y",
619
+ "b",
620
+ "v",
621
+ "k",
622
+ "x",
623
+ "j",
624
+ "z",
625
+ "q",
626
+ ],
627
+ "English—": [
628
+ "e",
629
+ "a",
630
+ "t",
631
+ "i",
632
+ "o",
633
+ "n",
634
+ "s",
635
+ "r",
636
+ "h",
637
+ "l",
638
+ "d",
639
+ "c",
640
+ "m",
641
+ "u",
642
+ "f",
643
+ "p",
644
+ "g",
645
+ "w",
646
+ "b",
647
+ "y",
648
+ "v",
649
+ "k",
650
+ "j",
651
+ "x",
652
+ "z",
653
+ "q",
654
+ ],
655
+ "German": [
656
+ "e",
657
+ "n",
658
+ "i",
659
+ "r",
660
+ "s",
661
+ "t",
662
+ "a",
663
+ "d",
664
+ "h",
665
+ "u",
666
+ "l",
667
+ "g",
668
+ "o",
669
+ "c",
670
+ "m",
671
+ "b",
672
+ "f",
673
+ "k",
674
+ "w",
675
+ "z",
676
+ "p",
677
+ "v",
678
+ "ü",
679
+ "ä",
680
+ "ö",
681
+ "j",
682
+ ],
683
+ "French": [
684
+ "e",
685
+ "a",
686
+ "s",
687
+ "n",
688
+ "i",
689
+ "t",
690
+ "r",
691
+ "l",
692
+ "u",
693
+ "o",
694
+ "d",
695
+ "c",
696
+ "p",
697
+ "m",
698
+ "é",
699
+ "v",
700
+ "g",
701
+ "f",
702
+ "b",
703
+ "h",
704
+ "q",
705
+ "à",
706
+ "x",
707
+ "è",
708
+ "y",
709
+ "j",
710
+ ],
711
+ "Dutch": [
712
+ "e",
713
+ "n",
714
+ "a",
715
+ "i",
716
+ "r",
717
+ "t",
718
+ "o",
719
+ "d",
720
+ "s",
721
+ "l",
722
+ "g",
723
+ "h",
724
+ "v",
725
+ "m",
726
+ "u",
727
+ "k",
728
+ "c",
729
+ "p",
730
+ "b",
731
+ "w",
732
+ "j",
733
+ "z",
734
+ "f",
735
+ "y",
736
+ "x",
737
+ "ë",
738
+ ],
739
+ "Italian": [
740
+ "e",
741
+ "i",
742
+ "a",
743
+ "o",
744
+ "n",
745
+ "l",
746
+ "t",
747
+ "r",
748
+ "s",
749
+ "c",
750
+ "d",
751
+ "u",
752
+ "p",
753
+ "m",
754
+ "g",
755
+ "v",
756
+ "f",
757
+ "b",
758
+ "z",
759
+ "h",
760
+ "q",
761
+ "è",
762
+ "à",
763
+ "k",
764
+ "y",
765
+ "ò",
766
+ ],
767
+ "Polish": [
768
+ "a",
769
+ "i",
770
+ "o",
771
+ "e",
772
+ "n",
773
+ "r",
774
+ "z",
775
+ "w",
776
+ "s",
777
+ "c",
778
+ "t",
779
+ "k",
780
+ "y",
781
+ "d",
782
+ "p",
783
+ "m",
784
+ "u",
785
+ "l",
786
+ "j",
787
+ "ł",
788
+ "g",
789
+ "b",
790
+ "h",
791
+ "ą",
792
+ "ę",
793
+ "ó",
794
+ ],
795
+ "Spanish": [
796
+ "e",
797
+ "a",
798
+ "o",
799
+ "n",
800
+ "s",
801
+ "r",
802
+ "i",
803
+ "l",
804
+ "d",
805
+ "t",
806
+ "c",
807
+ "u",
808
+ "m",
809
+ "p",
810
+ "b",
811
+ "g",
812
+ "v",
813
+ "f",
814
+ "y",
815
+ "ó",
816
+ "h",
817
+ "q",
818
+ "í",
819
+ "j",
820
+ "z",
821
+ "á",
822
+ ],
823
+ "Russian": [
824
+ "о",
825
+ "е",
826
+ "а",
827
+ "и",
828
+ "н",
829
+ "т",
830
+ "с",
831
+ "р",
832
+ "в",
833
+ "л",
834
+ "к",
835
+ "м",
836
+ "д",
837
+ "п",
838
+ "у",
839
+ "г",
840
+ "я",
841
+ "ы",
842
+ "з",
843
+ "б",
844
+ "й",
845
+ "ь",
846
+ "ч",
847
+ "х",
848
+ "ж",
849
+ "ц",
850
+ ],
851
+ # Jap-Kanji
852
+ "Japanese": [
853
+ "日",
854
+ "一",
855
+ "人",
856
+ "年",
857
+ "大",
858
+ "十",
859
+ "二",
860
+ "本",
861
+ "中",
862
+ "長",
863
+ "出",
864
+ "三",
865
+ "時",
866
+ "行",
867
+ "見",
868
+ "月",
869
+ "分",
870
+ "後",
871
+ "前",
872
+ "生",
873
+ "五",
874
+ "間",
875
+ "上",
876
+ "東",
877
+ "四",
878
+ "今",
879
+ "金",
880
+ "九",
881
+ "入",
882
+ "学",
883
+ "高",
884
+ "円",
885
+ "子",
886
+ "外",
887
+ "八",
888
+ "六",
889
+ "下",
890
+ "来",
891
+ "気",
892
+ "小",
893
+ "七",
894
+ "山",
895
+ "話",
896
+ "女",
897
+ "北",
898
+ "午",
899
+ "百",
900
+ "書",
901
+ "先",
902
+ "名",
903
+ "川",
904
+ "千",
905
+ "水",
906
+ "半",
907
+ "男",
908
+ "西",
909
+ "電",
910
+ "校",
911
+ "語",
912
+ "土",
913
+ "木",
914
+ "聞",
915
+ "食",
916
+ "車",
917
+ "何",
918
+ "南",
919
+ "万",
920
+ "毎",
921
+ "白",
922
+ "天",
923
+ "母",
924
+ "火",
925
+ "右",
926
+ "読",
927
+ "友",
928
+ "左",
929
+ "休",
930
+ "父",
931
+ "雨",
932
+ ],
933
+ # Jap-Katakana
934
+ "Japanese—": [
935
+ "ー",
936
+ "ン",
937
+ "ス",
938
+ "・",
939
+ "ル",
940
+ "ト",
941
+ "リ",
942
+ "イ",
943
+ "ア",
944
+ "ラ",
945
+ "ッ",
946
+ "ク",
947
+ "ド",
948
+ "シ",
949
+ "レ",
950
+ "ジ",
951
+ "タ",
952
+ "フ",
953
+ "ロ",
954
+ "カ",
955
+ "テ",
956
+ "マ",
957
+ "ィ",
958
+ "グ",
959
+ "バ",
960
+ "ム",
961
+ "プ",
962
+ "オ",
963
+ "コ",
964
+ "デ",
965
+ "ニ",
966
+ "ウ",
967
+ "メ",
968
+ "サ",
969
+ "ビ",
970
+ "ナ",
971
+ "ブ",
972
+ "ャ",
973
+ "エ",
974
+ "ュ",
975
+ "チ",
976
+ "キ",
977
+ "ズ",
978
+ "ダ",
979
+ "パ",
980
+ "ミ",
981
+ "ェ",
982
+ "ョ",
983
+ "ハ",
984
+ "セ",
985
+ "ベ",
986
+ "ガ",
987
+ "モ",
988
+ "ツ",
989
+ "ネ",
990
+ "ボ",
991
+ "ソ",
992
+ "ノ",
993
+ "ァ",
994
+ "ヴ",
995
+ "ワ",
996
+ "ポ",
997
+ "ペ",
998
+ "ピ",
999
+ "ケ",
1000
+ "ゴ",
1001
+ "ギ",
1002
+ "ザ",
1003
+ "ホ",
1004
+ "ゲ",
1005
+ "ォ",
1006
+ "ヤ",
1007
+ "ヒ",
1008
+ "ユ",
1009
+ "ヨ",
1010
+ "ヘ",
1011
+ "ゼ",
1012
+ "ヌ",
1013
+ "ゥ",
1014
+ "ゾ",
1015
+ "ヶ",
1016
+ "ヂ",
1017
+ "ヲ",
1018
+ "ヅ",
1019
+ "ヵ",
1020
+ "ヱ",
1021
+ "ヰ",
1022
+ "ヮ",
1023
+ "ヽ",
1024
+ "゠",
1025
+ "ヾ",
1026
+ "ヷ",
1027
+ "ヿ",
1028
+ "ヸ",
1029
+ "ヹ",
1030
+ "ヺ",
1031
+ ],
1032
+ # Jap-Hiragana
1033
+ "Japanese——": [
1034
+ "の",
1035
+ "に",
1036
+ "る",
1037
+ "た",
1038
+ "と",
1039
+ "は",
1040
+ "し",
1041
+ "い",
1042
+ "を",
1043
+ "で",
1044
+ "て",
1045
+ "が",
1046
+ "な",
1047
+ "れ",
1048
+ "か",
1049
+ "ら",
1050
+ "さ",
1051
+ "っ",
1052
+ "り",
1053
+ "す",
1054
+ "あ",
1055
+ "も",
1056
+ "こ",
1057
+ "ま",
1058
+ "う",
1059
+ "く",
1060
+ "よ",
1061
+ "き",
1062
+ "ん",
1063
+ "め",
1064
+ "お",
1065
+ "け",
1066
+ "そ",
1067
+ "つ",
1068
+ "だ",
1069
+ "や",
1070
+ "え",
1071
+ "ど",
1072
+ "わ",
1073
+ "ち",
1074
+ "み",
1075
+ "せ",
1076
+ "じ",
1077
+ "ば",
1078
+ "へ",
1079
+ "び",
1080
+ "ず",
1081
+ "ろ",
1082
+ "ほ",
1083
+ "げ",
1084
+ "む",
1085
+ "べ",
1086
+ "ひ",
1087
+ "ょ",
1088
+ "ゆ",
1089
+ "ぶ",
1090
+ "ご",
1091
+ "ゃ",
1092
+ "ね",
1093
+ "ふ",
1094
+ "ぐ",
1095
+ "ぎ",
1096
+ "ぼ",
1097
+ "ゅ",
1098
+ "づ",
1099
+ "ざ",
1100
+ "ぞ",
1101
+ "ぬ",
1102
+ "ぜ",
1103
+ "ぱ",
1104
+ "ぽ",
1105
+ "ぷ",
1106
+ "ぴ",
1107
+ "ぃ",
1108
+ "ぁ",
1109
+ "ぇ",
1110
+ "ぺ",
1111
+ "ゞ",
1112
+ "ぢ",
1113
+ "ぉ",
1114
+ "ぅ",
1115
+ "ゐ",
1116
+ "ゝ",
1117
+ "ゑ",
1118
+ "゛",
1119
+ "゜",
1120
+ "ゎ",
1121
+ "ゔ",
1122
+ "゚",
1123
+ "ゟ",
1124
+ "゙",
1125
+ "ゕ",
1126
+ "ゖ",
1127
+ ],
1128
+ "Portuguese": [
1129
+ "a",
1130
+ "e",
1131
+ "o",
1132
+ "s",
1133
+ "i",
1134
+ "r",
1135
+ "d",
1136
+ "n",
1137
+ "t",
1138
+ "m",
1139
+ "u",
1140
+ "c",
1141
+ "l",
1142
+ "p",
1143
+ "g",
1144
+ "v",
1145
+ "b",
1146
+ "f",
1147
+ "h",
1148
+ "ã",
1149
+ "q",
1150
+ "é",
1151
+ "ç",
1152
+ "á",
1153
+ "z",
1154
+ "í",
1155
+ ],
1156
+ "Swedish": [
1157
+ "e",
1158
+ "a",
1159
+ "n",
1160
+ "r",
1161
+ "t",
1162
+ "s",
1163
+ "i",
1164
+ "l",
1165
+ "d",
1166
+ "o",
1167
+ "m",
1168
+ "k",
1169
+ "g",
1170
+ "v",
1171
+ "h",
1172
+ "f",
1173
+ "u",
1174
+ "p",
1175
+ "ä",
1176
+ "c",
1177
+ "b",
1178
+ "ö",
1179
+ "å",
1180
+ "y",
1181
+ "j",
1182
+ "x",
1183
+ ],
1184
+ "Chinese": [
1185
+ "的",
1186
+ "一",
1187
+ "是",
1188
+ "不",
1189
+ "了",
1190
+ "在",
1191
+ "人",
1192
+ "有",
1193
+ "我",
1194
+ "他",
1195
+ "这",
1196
+ "个",
1197
+ "们",
1198
+ "中",
1199
+ "来",
1200
+ "上",
1201
+ "大",
1202
+ "为",
1203
+ "和",
1204
+ "国",
1205
+ "地",
1206
+ "到",
1207
+ "以",
1208
+ "说",
1209
+ "时",
1210
+ "要",
1211
+ "就",
1212
+ "出",
1213
+ "会",
1214
+ "可",
1215
+ "也",
1216
+ "你",
1217
+ "对",
1218
+ "生",
1219
+ "能",
1220
+ "而",
1221
+ "子",
1222
+ "那",
1223
+ "得",
1224
+ "于",
1225
+ "着",
1226
+ "下",
1227
+ "自",
1228
+ "之",
1229
+ "年",
1230
+ "过",
1231
+ "发",
1232
+ "后",
1233
+ "作",
1234
+ "里",
1235
+ "用",
1236
+ "道",
1237
+ "行",
1238
+ "所",
1239
+ "然",
1240
+ "家",
1241
+ "种",
1242
+ "事",
1243
+ "成",
1244
+ "方",
1245
+ "多",
1246
+ "经",
1247
+ "么",
1248
+ "去",
1249
+ "法",
1250
+ "学",
1251
+ "如",
1252
+ "都",
1253
+ "同",
1254
+ "现",
1255
+ "当",
1256
+ "没",
1257
+ "动",
1258
+ "面",
1259
+ "起",
1260
+ "看",
1261
+ "定",
1262
+ "天",
1263
+ "分",
1264
+ "还",
1265
+ "进",
1266
+ "好",
1267
+ "小",
1268
+ "部",
1269
+ "其",
1270
+ "些",
1271
+ "主",
1272
+ "样",
1273
+ "理",
1274
+ "心",
1275
+ "她",
1276
+ "本",
1277
+ "前",
1278
+ "开",
1279
+ "但",
1280
+ "因",
1281
+ "只",
1282
+ "从",
1283
+ "想",
1284
+ "实",
1285
+ ],
1286
+ "Ukrainian": [
1287
+ "о",
1288
+ "а",
1289
+ "н",
1290
+ "і",
1291
+ "и",
1292
+ "р",
1293
+ "в",
1294
+ "т",
1295
+ "е",
1296
+ "с",
1297
+ "к",
1298
+ "л",
1299
+ "у",
1300
+ "д",
1301
+ "м",
1302
+ "п",
1303
+ "з",
1304
+ "я",
1305
+ "ь",
1306
+ "б",
1307
+ "г",
1308
+ "й",
1309
+ "ч",
1310
+ "х",
1311
+ "ц",
1312
+ "ї",
1313
+ ],
1314
+ "Norwegian": [
1315
+ "e",
1316
+ "r",
1317
+ "n",
1318
+ "t",
1319
+ "a",
1320
+ "s",
1321
+ "i",
1322
+ "o",
1323
+ "l",
1324
+ "d",
1325
+ "g",
1326
+ "k",
1327
+ "m",
1328
+ "v",
1329
+ "f",
1330
+ "p",
1331
+ "u",
1332
+ "b",
1333
+ "h",
1334
+ "å",
1335
+ "y",
1336
+ "j",
1337
+ "ø",
1338
+ "c",
1339
+ "æ",
1340
+ "w",
1341
+ ],
1342
+ "Finnish": [
1343
+ "a",
1344
+ "i",
1345
+ "n",
1346
+ "t",
1347
+ "e",
1348
+ "s",
1349
+ "l",
1350
+ "o",
1351
+ "u",
1352
+ "k",
1353
+ "ä",
1354
+ "m",
1355
+ "r",
1356
+ "v",
1357
+ "j",
1358
+ "h",
1359
+ "p",
1360
+ "y",
1361
+ "d",
1362
+ "ö",
1363
+ "g",
1364
+ "c",
1365
+ "b",
1366
+ "f",
1367
+ "w",
1368
+ "z",
1369
+ ],
1370
+ "Vietnamese": [
1371
+ "n",
1372
+ "h",
1373
+ "t",
1374
+ "i",
1375
+ "c",
1376
+ "g",
1377
+ "a",
1378
+ "o",
1379
+ "u",
1380
+ "m",
1381
+ "l",
1382
+ "r",
1383
+ "à",
1384
+ "đ",
1385
+ "s",
1386
+ "e",
1387
+ "v",
1388
+ "p",
1389
+ "b",
1390
+ "y",
1391
+ "ư",
1392
+ "d",
1393
+ "á",
1394
+ "k",
1395
+ "ộ",
1396
+ "ế",
1397
+ ],
1398
+ "Czech": [
1399
+ "o",
1400
+ "e",
1401
+ "a",
1402
+ "n",
1403
+ "t",
1404
+ "s",
1405
+ "i",
1406
+ "l",
1407
+ "v",
1408
+ "r",
1409
+ "k",
1410
+ "d",
1411
+ "u",
1412
+ "m",
1413
+ "p",
1414
+ "í",
1415
+ "c",
1416
+ "h",
1417
+ "z",
1418
+ "á",
1419
+ "y",
1420
+ "j",
1421
+ "b",
1422
+ "ě",
1423
+ "é",
1424
+ "ř",
1425
+ ],
1426
+ "Hungarian": [
1427
+ "e",
1428
+ "a",
1429
+ "t",
1430
+ "l",
1431
+ "s",
1432
+ "n",
1433
+ "k",
1434
+ "r",
1435
+ "i",
1436
+ "o",
1437
+ "z",
1438
+ "á",
1439
+ "é",
1440
+ "g",
1441
+ "m",
1442
+ "b",
1443
+ "y",
1444
+ "v",
1445
+ "d",
1446
+ "h",
1447
+ "u",
1448
+ "p",
1449
+ "j",
1450
+ "ö",
1451
+ "f",
1452
+ "c",
1453
+ ],
1454
+ "Korean": [
1455
+ "이",
1456
+ "다",
1457
+ "에",
1458
+ "의",
1459
+ "는",
1460
+ "로",
1461
+ "하",
1462
+ "을",
1463
+ "가",
1464
+ "고",
1465
+ "지",
1466
+ "서",
1467
+ "한",
1468
+ "은",
1469
+ "기",
1470
+ "으",
1471
+ "년",
1472
+ "대",
1473
+ "사",
1474
+ "시",
1475
+ "를",
1476
+ "리",
1477
+ "도",
1478
+ "인",
1479
+ "스",
1480
+ "일",
1481
+ ],
1482
+ "Indonesian": [
1483
+ "a",
1484
+ "n",
1485
+ "e",
1486
+ "i",
1487
+ "r",
1488
+ "t",
1489
+ "u",
1490
+ "s",
1491
+ "d",
1492
+ "k",
1493
+ "m",
1494
+ "l",
1495
+ "g",
1496
+ "p",
1497
+ "b",
1498
+ "o",
1499
+ "h",
1500
+ "y",
1501
+ "j",
1502
+ "c",
1503
+ "w",
1504
+ "f",
1505
+ "v",
1506
+ "z",
1507
+ "x",
1508
+ "q",
1509
+ ],
1510
+ "Turkish": [
1511
+ "a",
1512
+ "e",
1513
+ "i",
1514
+ "n",
1515
+ "r",
1516
+ "l",
1517
+ "ı",
1518
+ "k",
1519
+ "d",
1520
+ "t",
1521
+ "s",
1522
+ "m",
1523
+ "y",
1524
+ "u",
1525
+ "o",
1526
+ "b",
1527
+ "ü",
1528
+ "ş",
1529
+ "v",
1530
+ "g",
1531
+ "z",
1532
+ "h",
1533
+ "c",
1534
+ "p",
1535
+ "ç",
1536
+ "ğ",
1537
+ ],
1538
+ "Romanian": [
1539
+ "e",
1540
+ "i",
1541
+ "a",
1542
+ "r",
1543
+ "n",
1544
+ "t",
1545
+ "u",
1546
+ "l",
1547
+ "o",
1548
+ "c",
1549
+ "s",
1550
+ "d",
1551
+ "p",
1552
+ "m",
1553
+ "ă",
1554
+ "f",
1555
+ "v",
1556
+ "î",
1557
+ "g",
1558
+ "b",
1559
+ "ș",
1560
+ "ț",
1561
+ "z",
1562
+ "h",
1563
+ "â",
1564
+ "j",
1565
+ ],
1566
+ "Farsi": [
1567
+ "ا",
1568
+ "ی",
1569
+ "ر",
1570
+ "د",
1571
+ "ن",
1572
+ "ه",
1573
+ "و",
1574
+ "م",
1575
+ "ت",
1576
+ "ب",
1577
+ "س",
1578
+ "ل",
1579
+ "ک",
1580
+ "ش",
1581
+ "ز",
1582
+ "ف",
1583
+ "گ",
1584
+ "ع",
1585
+ "خ",
1586
+ "ق",
1587
+ "ج",
1588
+ "آ",
1589
+ "پ",
1590
+ "ح",
1591
+ "ط",
1592
+ "ص",
1593
+ ],
1594
+ "Arabic": [
1595
+ "ا",
1596
+ "ل",
1597
+ "ي",
1598
+ "م",
1599
+ "و",
1600
+ "ن",
1601
+ "ر",
1602
+ "ت",
1603
+ "ب",
1604
+ "ة",
1605
+ "ع",
1606
+ "د",
1607
+ "س",
1608
+ "ف",
1609
+ "ه",
1610
+ "ك",
1611
+ "ق",
1612
+ "أ",
1613
+ "ح",
1614
+ "ج",
1615
+ "ش",
1616
+ "ط",
1617
+ "ص",
1618
+ "ى",
1619
+ "خ",
1620
+ "إ",
1621
+ ],
1622
+ "Danish": [
1623
+ "e",
1624
+ "r",
1625
+ "n",
1626
+ "t",
1627
+ "a",
1628
+ "i",
1629
+ "s",
1630
+ "d",
1631
+ "l",
1632
+ "o",
1633
+ "g",
1634
+ "m",
1635
+ "k",
1636
+ "f",
1637
+ "v",
1638
+ "u",
1639
+ "b",
1640
+ "h",
1641
+ "p",
1642
+ "å",
1643
+ "y",
1644
+ "ø",
1645
+ "æ",
1646
+ "c",
1647
+ "j",
1648
+ "w",
1649
+ ],
1650
+ "Serbian": [
1651
+ "а",
1652
+ "и",
1653
+ "о",
1654
+ "е",
1655
+ "н",
1656
+ "р",
1657
+ "с",
1658
+ "у",
1659
+ "т",
1660
+ "к",
1661
+ "ј",
1662
+ "в",
1663
+ "д",
1664
+ "м",
1665
+ "п",
1666
+ "л",
1667
+ "г",
1668
+ "з",
1669
+ "б",
1670
+ "a",
1671
+ "i",
1672
+ "e",
1673
+ "o",
1674
+ "n",
1675
+ "ц",
1676
+ "ш",
1677
+ ],
1678
+ "Lithuanian": [
1679
+ "i",
1680
+ "a",
1681
+ "s",
1682
+ "o",
1683
+ "r",
1684
+ "e",
1685
+ "t",
1686
+ "n",
1687
+ "u",
1688
+ "k",
1689
+ "m",
1690
+ "l",
1691
+ "p",
1692
+ "v",
1693
+ "d",
1694
+ "j",
1695
+ "g",
1696
+ "ė",
1697
+ "b",
1698
+ "y",
1699
+ "ų",
1700
+ "š",
1701
+ "ž",
1702
+ "c",
1703
+ "ą",
1704
+ "į",
1705
+ ],
1706
+ "Slovene": [
1707
+ "e",
1708
+ "a",
1709
+ "i",
1710
+ "o",
1711
+ "n",
1712
+ "r",
1713
+ "s",
1714
+ "l",
1715
+ "t",
1716
+ "j",
1717
+ "v",
1718
+ "k",
1719
+ "d",
1720
+ "p",
1721
+ "m",
1722
+ "u",
1723
+ "z",
1724
+ "b",
1725
+ "g",
1726
+ "h",
1727
+ "č",
1728
+ "c",
1729
+ "š",
1730
+ "ž",
1731
+ "f",
1732
+ "y",
1733
+ ],
1734
+ "Slovak": [
1735
+ "o",
1736
+ "a",
1737
+ "e",
1738
+ "n",
1739
+ "i",
1740
+ "r",
1741
+ "v",
1742
+ "t",
1743
+ "s",
1744
+ "l",
1745
+ "k",
1746
+ "d",
1747
+ "m",
1748
+ "p",
1749
+ "u",
1750
+ "c",
1751
+ "h",
1752
+ "j",
1753
+ "b",
1754
+ "z",
1755
+ "á",
1756
+ "y",
1757
+ "ý",
1758
+ "í",
1759
+ "č",
1760
+ "é",
1761
+ ],
1762
+ "Hebrew": [
1763
+ "י",
1764
+ "ו",
1765
+ "ה",
1766
+ "ל",
1767
+ "ר",
1768
+ "ב",
1769
+ "ת",
1770
+ "מ",
1771
+ "א",
1772
+ "ש",
1773
+ "נ",
1774
+ "ע",
1775
+ "ם",
1776
+ "ד",
1777
+ "ק",
1778
+ "ח",
1779
+ "פ",
1780
+ "ס",
1781
+ "כ",
1782
+ "ג",
1783
+ "ט",
1784
+ "צ",
1785
+ "ן",
1786
+ "ז",
1787
+ "ך",
1788
+ ],
1789
+ "Bulgarian": [
1790
+ "а",
1791
+ "и",
1792
+ "о",
1793
+ "е",
1794
+ "н",
1795
+ "т",
1796
+ "р",
1797
+ "с",
1798
+ "в",
1799
+ "л",
1800
+ "к",
1801
+ "д",
1802
+ "п",
1803
+ "м",
1804
+ "з",
1805
+ "г",
1806
+ "я",
1807
+ "ъ",
1808
+ "у",
1809
+ "б",
1810
+ "ч",
1811
+ "ц",
1812
+ "й",
1813
+ "ж",
1814
+ "щ",
1815
+ "х",
1816
+ ],
1817
+ "Croatian": [
1818
+ "a",
1819
+ "i",
1820
+ "o",
1821
+ "e",
1822
+ "n",
1823
+ "r",
1824
+ "j",
1825
+ "s",
1826
+ "t",
1827
+ "u",
1828
+ "k",
1829
+ "l",
1830
+ "v",
1831
+ "d",
1832
+ "m",
1833
+ "p",
1834
+ "g",
1835
+ "z",
1836
+ "b",
1837
+ "c",
1838
+ "č",
1839
+ "h",
1840
+ "š",
1841
+ "ž",
1842
+ "ć",
1843
+ "f",
1844
+ ],
1845
+ "Hindi": [
1846
+ "क",
1847
+ "र",
1848
+ "स",
1849
+ "न",
1850
+ "त",
1851
+ "म",
1852
+ "ह",
1853
+ "प",
1854
+ "य",
1855
+ "ल",
1856
+ "व",
1857
+ "ज",
1858
+ "द",
1859
+ "ग",
1860
+ "ब",
1861
+ "श",
1862
+ "ट",
1863
+ "अ",
1864
+ "ए",
1865
+ "थ",
1866
+ "भ",
1867
+ "ड",
1868
+ "च",
1869
+ "ध",
1870
+ "ष",
1871
+ "इ",
1872
+ ],
1873
+ "Estonian": [
1874
+ "a",
1875
+ "i",
1876
+ "e",
1877
+ "s",
1878
+ "t",
1879
+ "l",
1880
+ "u",
1881
+ "n",
1882
+ "o",
1883
+ "k",
1884
+ "r",
1885
+ "d",
1886
+ "m",
1887
+ "v",
1888
+ "g",
1889
+ "p",
1890
+ "j",
1891
+ "h",
1892
+ "ä",
1893
+ "b",
1894
+ "õ",
1895
+ "ü",
1896
+ "f",
1897
+ "c",
1898
+ "ö",
1899
+ "y",
1900
+ ],
1901
+ "Thai": [
1902
+ "า",
1903
+ "น",
1904
+ "ร",
1905
+ "อ",
1906
+ "ก",
1907
+ "เ",
1908
+ "ง",
1909
+ "ม",
1910
+ "ย",
1911
+ "ล",
1912
+ "ว",
1913
+ "ด",
1914
+ "ท",
1915
+ "ส",
1916
+ "ต",
1917
+ "ะ",
1918
+ "ป",
1919
+ "บ",
1920
+ "ค",
1921
+ "ห",
1922
+ "แ",
1923
+ "จ",
1924
+ "พ",
1925
+ "ช",
1926
+ "ข",
1927
+ "ใ",
1928
+ ],
1929
+ "Greek": [
1930
+ "α",
1931
+ "τ",
1932
+ "ο",
1933
+ "ι",
1934
+ "ε",
1935
+ "ν",
1936
+ "ρ",
1937
+ "σ",
1938
+ "κ",
1939
+ "η",
1940
+ "π",
1941
+ "ς",
1942
+ "υ",
1943
+ "μ",
1944
+ "λ",
1945
+ "ί",
1946
+ "ό",
1947
+ "ά",
1948
+ "γ",
1949
+ "έ",
1950
+ "δ",
1951
+ "ή",
1952
+ "ω",
1953
+ "χ",
1954
+ "θ",
1955
+ "ύ",
1956
+ ],
1957
+ "Tamil": [
1958
+ "க",
1959
+ "த",
1960
+ "ப",
1961
+ "ட",
1962
+ "ர",
1963
+ "ம",
1964
+ "ல",
1965
+ "ன",
1966
+ "வ",
1967
+ "ற",
1968
+ "ய",
1969
+ "ள",
1970
+ "ச",
1971
+ "ந",
1972
+ "இ",
1973
+ "ண",
1974
+ "அ",
1975
+ "ஆ",
1976
+ "ழ",
1977
+ "ங",
1978
+ "எ",
1979
+ "உ",
1980
+ "ஒ",
1981
+ "ஸ",
1982
+ ],
1983
+ "Kazakh": [
1984
+ "а",
1985
+ "ы",
1986
+ "е",
1987
+ "н",
1988
+ "т",
1989
+ "р",
1990
+ "л",
1991
+ "і",
1992
+ "д",
1993
+ "с",
1994
+ "м",
1995
+ "қ",
1996
+ "к",
1997
+ "о",
1998
+ "б",
1999
+ "и",
2000
+ "у",
2001
+ "ғ",
2002
+ "ж",
2003
+ "ң",
2004
+ "з",
2005
+ "ш",
2006
+ "й",
2007
+ "п",
2008
+ "г",
2009
+ "ө",
2010
+ ],
2011
+ }
2012
+
2013
+ LANGUAGE_SUPPORTED_COUNT: int = len(FREQUENCIES)
2014
+
2015
+ # Bit flags for unified character classification.
2016
+ # A single unicodedata.name() call sets all relevant flags at once.
2017
+ _LATIN: int = 1
2018
+ _ACCENTUATED: int = 1 << 1
2019
+ _CJK: int = 1 << 2
2020
+ _HANGUL: int = 1 << 3
2021
+ _KATAKANA: int = 1 << 4
2022
+ _HIRAGANA: int = 1 << 5
2023
+ _THAI: int = 1 << 6
2024
+ _ARABIC: int = 1 << 7
2025
+ _ARABIC_ISOLATED_FORM: int = 1 << 8
2026
+
2027
+ _ACCENT_KEYWORDS: tuple[str, ...] = (
2028
+ "WITH GRAVE",
2029
+ "WITH ACUTE",
2030
+ "WITH CEDILLA",
2031
+ "WITH DIAERESIS",
2032
+ "WITH CIRCUMFLEX",
2033
+ "WITH TILDE",
2034
+ "WITH MACRON",
2035
+ "WITH RING ABOVE",
2036
+ )
2037
+
2038
+ # Pre-built lookup structures for FREQUENCIES (computed once at import time).
2039
+ # character -> rank mapping per language (replaces list .index() calls).
2040
+ _FREQUENCIES_RANK: dict[str, dict[str, int]] = {
2041
+ lang: {char: rank for rank, char in enumerate(chars)}
2042
+ for lang, chars in FREQUENCIES.items()
2043
+ }
2044
+
2045
+ # frozenset per language (avoids rebuilding set() per call).
2046
+ _FREQUENCIES_SET: dict[str, frozenset[str]] = {
2047
+ lang: frozenset(chars) for lang, chars in FREQUENCIES.items()
2048
+ }
2049
+
2050
+ # prebuilt list of secondary range names.
2051
+ _SECONDARY_RANGE_NAMES: frozenset[str] = frozenset(
2052
+ range_name
2053
+ for range_name in UNICODE_RANGES_COMBINED
2054
+ if any(keyword in range_name for keyword in UNICODE_SECONDARY_RANGE_KEYWORD)
2055
+ )
data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer/legacy.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Any
4
+ from warnings import warn
5
+
6
+ from .api import from_bytes
7
+ from .constant import CHARDET_CORRESPONDENCE, TOO_SMALL_SEQUENCE
8
+
9
+ if TYPE_CHECKING:
10
+ from typing import TypedDict
11
+
12
+ class ResultDict(TypedDict):
13
+ encoding: str | None
14
+ language: str
15
+ confidence: float | None
16
+
17
+
18
+ def detect(
19
+ byte_str: bytes, should_rename_legacy: bool = False, **kwargs: Any
20
+ ) -> ResultDict:
21
+ """
22
+ chardet legacy method
23
+ Detect the encoding of the given byte string. It should be mostly backward-compatible.
24
+ Encoding name will match Chardet own writing whenever possible. (Not on encoding name unsupported by it)
25
+ This function is deprecated and should be used to migrate your project easily, consult the documentation for
26
+ further information. Not planned for removal.
27
+
28
+ :param byte_str: The byte sequence to examine.
29
+ :param should_rename_legacy: Should we rename legacy encodings
30
+ to their more modern equivalents?
31
+ """
32
+ if len(kwargs):
33
+ warn(
34
+ f"charset-normalizer disregard arguments '{','.join(list(kwargs.keys()))}' in legacy function detect()"
35
+ )
36
+
37
+ if not isinstance(byte_str, (bytearray, bytes)):
38
+ raise TypeError( # pragma: nocover
39
+ f"Expected object of type bytes or bytearray, got: {type(byte_str)}"
40
+ )
41
+
42
+ if isinstance(byte_str, bytearray):
43
+ byte_str = bytes(byte_str)
44
+
45
+ r = from_bytes(byte_str).best()
46
+
47
+ encoding = r.encoding if r is not None else None
48
+ language = r.language if r is not None and r.language != "Unknown" else ""
49
+ confidence = 1.0 - r.chaos if r is not None else None
50
+
51
+ # automatically lower confidence
52
+ # on small bytes samples.
53
+ # https://github.com/jawah/charset_normalizer/issues/391
54
+ if (
55
+ confidence is not None
56
+ and confidence >= 0.9
57
+ and encoding
58
+ not in {
59
+ "utf_8",
60
+ "ascii",
61
+ }
62
+ and not r.bom # type: ignore[union-attr]
63
+ and len(byte_str) < TOO_SMALL_SEQUENCE
64
+ ):
65
+ confidence -= 0.2
66
+
67
+ # Note: CharsetNormalizer does not return 'UTF-8-SIG' as the sig get stripped in the detection/normalization process
68
+ # but chardet does return 'utf-8-sig' and it is a valid codec name.
69
+ if r is not None and encoding == "utf_8" and r.bom:
70
+ encoding += "_sig"
71
+
72
+ if not should_rename_legacy and encoding in CHARDET_CORRESPONDENCE:
73
+ encoding = CHARDET_CORRESPONDENCE[encoding]
74
+
75
+ return {
76
+ "encoding": encoding,
77
+ "language": language,
78
+ "confidence": confidence,
79
+ }
data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer/md.cpython-311-x86_64-linux-gnu.so ADDED
Binary file (16 kB). View file
 
data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer/md.py ADDED
@@ -0,0 +1,1002 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from functools import lru_cache
5
+ from logging import getLogger
6
+
7
+ if sys.version_info >= (3, 8):
8
+ from typing import final
9
+ else:
10
+ try:
11
+ from typing_extensions import final
12
+ except ImportError:
13
+
14
+ def final(cls): # type: ignore[misc,no-untyped-def]
15
+ return cls
16
+
17
+
18
+ from .constant import (
19
+ COMMON_CJK_CHARACTERS,
20
+ COMMON_SAFE_ASCII_CHARACTERS,
21
+ TRACE,
22
+ UNICODE_SECONDARY_RANGE_KEYWORD,
23
+ _ACCENTUATED,
24
+ _ARABIC,
25
+ _ARABIC_ISOLATED_FORM,
26
+ _CJK,
27
+ _HANGUL,
28
+ _HIRAGANA,
29
+ _KATAKANA,
30
+ _LATIN,
31
+ _THAI,
32
+ )
33
+ from .utils import (
34
+ _character_flags,
35
+ is_emoticon,
36
+ is_punctuation,
37
+ is_separator,
38
+ is_symbol,
39
+ remove_accent,
40
+ unicode_range,
41
+ )
42
+
43
+ # Combined bitmask for CJK/Hangul/Katakana/Hiragana/Thai glyph detection.
44
+ _GLYPH_MASK: int = _CJK | _HANGUL | _KATAKANA | _HIRAGANA | _THAI
45
+
46
+
47
+ @final
48
+ class CharInfo:
49
+ """Pre-computed character properties shared across all detectors."""
50
+
51
+ __slots__ = (
52
+ "character",
53
+ "printable",
54
+ "alpha",
55
+ "upper",
56
+ "lower",
57
+ "space",
58
+ "digit",
59
+ "is_ascii",
60
+ "case_variable",
61
+ "flags",
62
+ "accentuated",
63
+ "latin",
64
+ "is_cjk",
65
+ "is_arabic",
66
+ "is_glyph",
67
+ "punct",
68
+ "sym",
69
+ "range",
70
+ "sep",
71
+ "emoticon",
72
+ "safe",
73
+ "common_cjk",
74
+ )
75
+
76
+ character: str
77
+ printable: bool
78
+ alpha: bool
79
+ upper: bool
80
+ lower: bool
81
+ space: bool
82
+ digit: bool
83
+ is_ascii: bool
84
+ case_variable: bool
85
+ flags: int
86
+ accentuated: bool
87
+ latin: bool
88
+ is_cjk: bool
89
+ is_arabic: bool
90
+ is_glyph: bool
91
+ punct: bool
92
+ sym: bool
93
+ range: str | None
94
+ sep: bool
95
+ emoticon: bool
96
+ safe: bool
97
+ common_cjk: bool
98
+
99
+ def __init__(self, character: str) -> None:
100
+ """Compute all properties for *character* (built once per codepoint,
101
+ every branch assigns every slot)."""
102
+ self.character = character
103
+
104
+ # ASCII fast-path: for characters with ord < 128, we can skip
105
+ # _character_flags() entirely and derive most properties from ord.
106
+ o: int = ord(character)
107
+ if o < 128:
108
+ self.is_ascii = True
109
+ self.accentuated = False
110
+ self.is_cjk = False
111
+ self.is_arabic = False
112
+ self.is_glyph = False
113
+ # ASCII alpha: a-z (97-122) or A-Z (65-90)
114
+ if 65 <= o <= 90:
115
+ # Uppercase ASCII letter
116
+ self.alpha = True
117
+ self.upper = True
118
+ self.lower = False
119
+ self.space = False
120
+ self.digit = False
121
+ self.printable = True
122
+ self.case_variable = True
123
+ self.flags = _LATIN
124
+ self.latin = True
125
+ self.punct = False
126
+ self.sym = False
127
+ elif 97 <= o <= 122:
128
+ # Lowercase ASCII letter
129
+ self.alpha = True
130
+ self.upper = False
131
+ self.lower = True
132
+ self.space = False
133
+ self.digit = False
134
+ self.printable = True
135
+ self.case_variable = True
136
+ self.flags = _LATIN
137
+ self.latin = True
138
+ self.punct = False
139
+ self.sym = False
140
+ elif 48 <= o <= 57:
141
+ # ASCII digit 0-9
142
+ self.alpha = False
143
+ self.upper = False
144
+ self.lower = False
145
+ self.space = False
146
+ self.digit = True
147
+ self.printable = True
148
+ self.case_variable = False
149
+ self.flags = 0
150
+ self.latin = False
151
+ self.punct = False
152
+ self.sym = False
153
+ elif o == 32 or (9 <= o <= 13):
154
+ # Space, tab, newline, etc.
155
+ self.alpha = False
156
+ self.upper = False
157
+ self.lower = False
158
+ self.space = True
159
+ self.digit = False
160
+ self.printable = o == 32
161
+ self.case_variable = False
162
+ self.flags = 0
163
+ self.latin = False
164
+ self.punct = False
165
+ self.sym = False
166
+ else:
167
+ # Other ASCII (punctuation, symbols, control chars)
168
+ self.printable = character.isprintable()
169
+ self.alpha = False
170
+ self.upper = False
171
+ self.lower = False
172
+ self.space = False
173
+ self.digit = False
174
+ self.case_variable = False
175
+ self.flags = 0
176
+ self.latin = False
177
+ self.punct = is_punctuation(character) if self.printable else False
178
+ self.sym = is_symbol(character) if self.printable else False
179
+ else:
180
+ # Non-ASCII path
181
+ self.is_ascii = False
182
+ self.printable = character.isprintable()
183
+ self.alpha = character.isalpha()
184
+ self.upper = character.isupper()
185
+ self.lower = character.islower()
186
+ self.space = character.isspace()
187
+ self.digit = character.isdigit()
188
+ self.case_variable = self.lower != self.upper
189
+
190
+ # Flag-based classification (single unicodedata.name() call, lru-cached)
191
+ flags: int
192
+ if self.alpha:
193
+ flags = _character_flags(character)
194
+ else:
195
+ flags = 0
196
+ self.flags = flags
197
+ self.accentuated = bool(flags & _ACCENTUATED)
198
+ self.latin = bool(flags & _LATIN)
199
+ self.is_cjk = bool(flags & _CJK)
200
+ self.is_arabic = bool(flags & _ARABIC)
201
+ self.is_glyph = bool(flags & _GLYPH_MASK)
202
+
203
+ # Eagerly compute punct and sym (avoids property dispatch overhead
204
+ # on 300K+ accesses in the hot loop).
205
+ self.punct = is_punctuation(character) if self.printable else False
206
+ self.sym = is_symbol(character) if self.printable else False
207
+
208
+ self.range = unicode_range(character)
209
+ self.sep = is_separator(character)
210
+ self.emoticon = is_emoticon(character)
211
+ self.safe = character in COMMON_SAFE_ASCII_CHARACTERS
212
+ self.common_cjk = character in COMMON_CJK_CHARACTERS
213
+
214
+
215
+ # Per-codepoint cache of CharInfo instances
216
+ # At most UTF-8 size allocated.
217
+ @lru_cache(maxsize=None)
218
+ def _char_info(character: str) -> CharInfo:
219
+ """Build (once per codepoint) and cache the CharInfo for *character*."""
220
+ return CharInfo(character)
221
+
222
+
223
+ # ASCII table indexed by codepoint.
224
+ _ASCII_CHAR_INFO: list[CharInfo] = [
225
+ CharInfo(chr(_codepoint)) for _codepoint in range(128)
226
+ ]
227
+
228
+
229
+ class MessDetectorPlugin:
230
+ """
231
+ Base abstract class used for mess detection plugins.
232
+ All detectors MUST extend and implement given methods.
233
+ """
234
+
235
+ __slots__ = ()
236
+
237
+ def feed_info(self, character: str, info: CharInfo) -> None:
238
+ """
239
+ The main routine to be executed upon character.
240
+ Insert the logic in witch the text would be considered chaotic.
241
+ """
242
+ raise NotImplementedError # Defensive:
243
+
244
+ def reset(self) -> None: # Defensive:
245
+ """
246
+ Permit to reset the plugin to the initial state.
247
+ """
248
+ raise NotImplementedError
249
+
250
+ @property
251
+ def ratio(self) -> float:
252
+ """
253
+ Compute the chaos ratio based on what your feed() has seen.
254
+ Must NOT be lower than 0.; No restriction gt 0.
255
+ """
256
+ raise NotImplementedError # Defensive:
257
+
258
+
259
+ @final
260
+ class TooManySymbolOrPunctuationPlugin(MessDetectorPlugin):
261
+ __slots__ = (
262
+ "_punctuation_count",
263
+ "_symbol_count",
264
+ "_character_count",
265
+ "_last_printable_char",
266
+ "_frenzy_symbol_in_word",
267
+ )
268
+
269
+ def __init__(self) -> None:
270
+ self._punctuation_count: int = 0
271
+ self._symbol_count: int = 0
272
+ self._character_count: int = 0
273
+
274
+ self._last_printable_char: str | None = None
275
+ self._frenzy_symbol_in_word: bool = False
276
+
277
+ def feed_info(self, character: str, info: CharInfo) -> None:
278
+ """Optimized feed using pre-computed character info."""
279
+ self._character_count += 1
280
+
281
+ if character != self._last_printable_char and not info.safe:
282
+ if info.punct:
283
+ self._punctuation_count += 1
284
+ elif not info.digit and info.sym and not info.emoticon:
285
+ self._symbol_count += 2
286
+
287
+ self._last_printable_char = character
288
+
289
+ def reset(self) -> None: # Abstract
290
+ self._punctuation_count = 0
291
+ self._character_count = 0
292
+ self._symbol_count = 0
293
+
294
+ @property
295
+ def ratio(self) -> float:
296
+ if self._character_count == 0:
297
+ return 0.0
298
+
299
+ ratio_of_punctuation: float = (
300
+ self._punctuation_count + self._symbol_count
301
+ ) / self._character_count
302
+
303
+ return ratio_of_punctuation if ratio_of_punctuation >= 0.3 else 0.0
304
+
305
+
306
+ @final
307
+ class TooManyAccentuatedPlugin(MessDetectorPlugin):
308
+ __slots__ = ("_character_count", "_accentuated_count")
309
+
310
+ def __init__(self) -> None:
311
+ self._character_count: int = 0
312
+ self._accentuated_count: int = 0
313
+
314
+ def feed_info(self, character: str, info: CharInfo) -> None:
315
+ """Optimized feed using pre-computed character info."""
316
+ self._character_count += 1
317
+
318
+ if info.accentuated:
319
+ self._accentuated_count += 1
320
+
321
+ def reset(self) -> None: # Abstract
322
+ self._character_count = 0
323
+ self._accentuated_count = 0
324
+
325
+ @property
326
+ def ratio(self) -> float:
327
+ if self._character_count < 8:
328
+ return 0.0
329
+
330
+ ratio_of_accentuation: float = self._accentuated_count / self._character_count
331
+ return ratio_of_accentuation if ratio_of_accentuation >= 0.35 else 0.0
332
+
333
+
334
+ @final
335
+ class UnprintablePlugin(MessDetectorPlugin):
336
+ __slots__ = ("_unprintable_count", "_character_count")
337
+
338
+ def __init__(self) -> None:
339
+ self._unprintable_count: int = 0
340
+ self._character_count: int = 0
341
+
342
+ def feed_info(self, character: str, info: CharInfo) -> None:
343
+ """Optimized feed using pre-computed character info."""
344
+ if (
345
+ not info.space
346
+ and not info.printable
347
+ and character != "\x1a"
348
+ and character != "\ufeff"
349
+ ):
350
+ self._unprintable_count += 1
351
+ self._character_count += 1
352
+
353
+ def reset(self) -> None: # Abstract
354
+ self._unprintable_count = 0
355
+
356
+ @property
357
+ def ratio(self) -> float:
358
+ if self._character_count == 0: # Defensive:
359
+ return 0.0
360
+
361
+ return (self._unprintable_count * 8) / self._character_count
362
+
363
+
364
+ @final
365
+ class SuspiciousDuplicateAccentPlugin(MessDetectorPlugin):
366
+ __slots__ = (
367
+ "_successive_count",
368
+ "_character_count",
369
+ "_last_latin_character",
370
+ "_last_was_accentuated",
371
+ )
372
+
373
+ def __init__(self) -> None:
374
+ self._successive_count: int = 0
375
+ self._character_count: int = 0
376
+
377
+ self._last_latin_character: str | None = None
378
+ self._last_was_accentuated: bool = False
379
+
380
+ def feed_info(self, character: str, info: CharInfo) -> None:
381
+ """Optimized feed using pre-computed character info."""
382
+ self._character_count += 1
383
+ if (
384
+ self._last_latin_character is not None
385
+ and info.accentuated
386
+ and self._last_was_accentuated
387
+ ):
388
+ if info.upper and self._last_latin_character.isupper():
389
+ self._successive_count += 1
390
+ if remove_accent(character) == remove_accent(self._last_latin_character):
391
+ self._successive_count += 1
392
+ self._last_latin_character = character
393
+ self._last_was_accentuated = info.accentuated
394
+
395
+ def reset(self) -> None: # Abstract
396
+ self._successive_count = 0
397
+ self._character_count = 0
398
+ self._last_latin_character = None
399
+ self._last_was_accentuated = False
400
+
401
+ @property
402
+ def ratio(self) -> float:
403
+ if self._character_count == 0:
404
+ return 0.0
405
+
406
+ return (self._successive_count * 2) / self._character_count
407
+
408
+
409
+ @final
410
+ class SuspiciousRange(MessDetectorPlugin):
411
+ __slots__ = (
412
+ "_suspicious_successive_range_count",
413
+ "_character_count",
414
+ "_last_printable_seen",
415
+ "_last_printable_range",
416
+ )
417
+
418
+ def __init__(self) -> None:
419
+ self._suspicious_successive_range_count: int = 0
420
+ self._character_count: int = 0
421
+ self._last_printable_seen: str | None = None
422
+ self._last_printable_range: str | None = None
423
+
424
+ def feed_info(self, character: str, info: CharInfo) -> None:
425
+ """Optimized feed using pre-computed character info."""
426
+ self._character_count += 1
427
+
428
+ if info.space or info.punct or info.safe:
429
+ self._last_printable_seen = None
430
+ self._last_printable_range = None
431
+ return
432
+
433
+ if self._last_printable_seen is None:
434
+ self._last_printable_seen = character
435
+ self._last_printable_range = info.range
436
+ return
437
+
438
+ unicode_range_a: str | None = self._last_printable_range
439
+ unicode_range_b: str | None = info.range
440
+
441
+ # Identical non-None ranges can never be suspicious.
442
+ if unicode_range_a != unicode_range_b or unicode_range_a is None:
443
+ if is_suspiciously_successive_range(unicode_range_a, unicode_range_b):
444
+ self._suspicious_successive_range_count += 1
445
+
446
+ self._last_printable_seen = character
447
+ self._last_printable_range = unicode_range_b
448
+
449
+ def reset(self) -> None: # Abstract
450
+ self._character_count = 0
451
+ self._suspicious_successive_range_count = 0
452
+ self._last_printable_seen = None
453
+ self._last_printable_range = None
454
+
455
+ @property
456
+ def ratio(self) -> float:
457
+ if self._character_count <= 13:
458
+ return 0.0
459
+
460
+ ratio_of_suspicious_range_usage: float = (
461
+ self._suspicious_successive_range_count * 2
462
+ ) / self._character_count
463
+
464
+ return ratio_of_suspicious_range_usage
465
+
466
+
467
+ @final
468
+ class SuperWeirdWordPlugin(MessDetectorPlugin):
469
+ __slots__ = (
470
+ "_word_count",
471
+ "_bad_word_count",
472
+ "_foreign_long_count",
473
+ "_is_current_word_bad",
474
+ "_foreign_long_watch",
475
+ "_character_count",
476
+ "_bad_character_count",
477
+ "_buffer_length",
478
+ "_buffer_last_char",
479
+ "_buffer_last_char_accentuated",
480
+ "_buffer_accent_count",
481
+ "_buffer_glyph_count",
482
+ "_buffer_upper_count",
483
+ "_buffer_first_lower",
484
+ "_buffer_has_non_ascii",
485
+ )
486
+
487
+ def __init__(self) -> None:
488
+ self._word_count: int = 0
489
+ self._bad_word_count: int = 0
490
+ self._foreign_long_count: int = 0
491
+
492
+ self._is_current_word_bad: bool = False
493
+ self._foreign_long_watch: bool = False
494
+
495
+ self._character_count: int = 0
496
+ self._bad_character_count: int = 0
497
+
498
+ self._buffer_length: int = 0
499
+ self._buffer_last_char: str | None = None
500
+ self._buffer_last_char_accentuated: bool = False
501
+ self._buffer_accent_count: int = 0
502
+ self._buffer_glyph_count: int = 0
503
+ self._buffer_upper_count: int = 0
504
+ self._buffer_first_lower: bool = False
505
+ self._buffer_has_non_ascii: bool = False
506
+
507
+ def feed_info(self, character: str, info: CharInfo) -> None:
508
+ """Optimized feed using pre-computed character info."""
509
+ if info.alpha:
510
+ if self._buffer_length == 0:
511
+ self._buffer_first_lower = info.lower
512
+ self._buffer_length += 1
513
+ self._buffer_last_char = character
514
+
515
+ if info.upper:
516
+ self._buffer_upper_count += 1
517
+ if not info.is_ascii:
518
+ self._buffer_has_non_ascii = True
519
+
520
+ self._buffer_last_char_accentuated = info.accentuated
521
+
522
+ if info.accentuated:
523
+ self._buffer_accent_count += 1
524
+ if (
525
+ not self._foreign_long_watch
526
+ and (not info.latin or info.accentuated)
527
+ and not info.is_glyph
528
+ ):
529
+ self._foreign_long_watch = True
530
+ if info.is_glyph:
531
+ self._buffer_glyph_count += 1
532
+ return
533
+ if not self._buffer_length:
534
+ return
535
+ if info.space or info.punct or info.sep:
536
+ self._word_count += 1
537
+ buffer_length: int = self._buffer_length
538
+
539
+ self._character_count += buffer_length
540
+
541
+ if buffer_length >= 4:
542
+ if self._buffer_accent_count / buffer_length >= 0.5:
543
+ self._is_current_word_bad = True
544
+ elif (
545
+ self._buffer_last_char_accentuated
546
+ and self._buffer_last_char.isupper() # type: ignore[union-attr]
547
+ and self._buffer_upper_count != buffer_length
548
+ ):
549
+ self._foreign_long_count += 1
550
+ self._is_current_word_bad = True
551
+ elif self._buffer_glyph_count == 1:
552
+ self._is_current_word_bad = True
553
+ self._foreign_long_count += 1
554
+ elif (
555
+ self._buffer_has_non_ascii
556
+ and self._buffer_first_lower
557
+ and self._buffer_upper_count == buffer_length - 1
558
+ ):
559
+ # Inverse capitalization detector.
560
+ # No natural writing produces such words.
561
+ # see https://github.com/jawah/charset_normalizer/issues/731
562
+ self._foreign_long_count += 1
563
+ self._is_current_word_bad = True
564
+ if buffer_length >= 24 and self._foreign_long_watch:
565
+ probable_camel_cased: bool = (
566
+ self._buffer_upper_count > 0
567
+ and self._buffer_upper_count / buffer_length <= 0.3
568
+ )
569
+
570
+ if not probable_camel_cased:
571
+ self._foreign_long_count += 1
572
+ self._is_current_word_bad = True
573
+
574
+ if self._is_current_word_bad:
575
+ self._bad_word_count += 1
576
+ self._bad_character_count += buffer_length
577
+ self._is_current_word_bad = False
578
+
579
+ self._foreign_long_watch = False
580
+ self._buffer_length = 0
581
+ self._buffer_last_char = None
582
+ self._buffer_last_char_accentuated = False
583
+ self._buffer_accent_count = 0
584
+ self._buffer_glyph_count = 0
585
+ self._buffer_upper_count = 0
586
+ self._buffer_first_lower = False
587
+ self._buffer_has_non_ascii = False
588
+ elif (
589
+ character not in {"<", ">", "-", "=", "~", "|", "_"}
590
+ and not info.digit
591
+ and info.sym
592
+ ):
593
+ self._is_current_word_bad = True
594
+ self._buffer_length += 1
595
+ self._buffer_last_char = character
596
+ self._buffer_last_char_accentuated = False
597
+
598
+ def reset(self) -> None: # Abstract
599
+ self._buffer_length = 0
600
+ self._buffer_last_char = None
601
+ self._buffer_last_char_accentuated = False
602
+ self._is_current_word_bad = False
603
+ self._foreign_long_watch = False
604
+ self._bad_word_count = 0
605
+ self._word_count = 0
606
+ self._character_count = 0
607
+ self._bad_character_count = 0
608
+ self._foreign_long_count = 0
609
+ self._buffer_accent_count = 0
610
+ self._buffer_glyph_count = 0
611
+ self._buffer_upper_count = 0
612
+ self._buffer_first_lower = False
613
+ self._buffer_has_non_ascii = False
614
+
615
+ @property
616
+ def ratio(self) -> float:
617
+ if self._word_count <= 10 and self._foreign_long_count == 0:
618
+ return 0.0
619
+
620
+ return self._bad_character_count / self._character_count
621
+
622
+
623
+ @final
624
+ class CjkUncommonPlugin(MessDetectorPlugin):
625
+ """
626
+ Detect messy CJK text that probably means nothing.
627
+ """
628
+
629
+ __slots__ = ("_character_count", "_uncommon_count")
630
+
631
+ def __init__(self) -> None:
632
+ self._character_count: int = 0
633
+ self._uncommon_count: int = 0
634
+
635
+ def feed_info(self, character: str, info: CharInfo) -> None:
636
+ """Optimized feed using pre-computed character info."""
637
+ self._character_count += 1
638
+
639
+ if not info.common_cjk:
640
+ self._uncommon_count += 1
641
+
642
+ def reset(self) -> None: # Abstract
643
+ self._character_count = 0
644
+ self._uncommon_count = 0
645
+
646
+ @property
647
+ def ratio(self) -> float:
648
+ if self._character_count < 8:
649
+ return 0.0
650
+
651
+ uncommon_form_usage: float = self._uncommon_count / self._character_count
652
+
653
+ # we can be pretty sure it's garbage when uncommon characters are widely
654
+ # used. otherwise it could just be traditional chinese for example.
655
+ return uncommon_form_usage / 10 if uncommon_form_usage > 0.5 else 0.0
656
+
657
+
658
+ @final
659
+ class ArchaicUpperLowerPlugin(MessDetectorPlugin):
660
+ __slots__ = (
661
+ "_buf",
662
+ "_character_count_since_last_sep",
663
+ "_successive_upper_lower_count",
664
+ "_successive_upper_lower_count_final",
665
+ "_character_count",
666
+ "_last_alpha_seen",
667
+ "_last_alpha_seen_upper",
668
+ "_last_alpha_seen_lower",
669
+ "_current_ascii_only",
670
+ )
671
+
672
+ def __init__(self) -> None:
673
+ self._buf: bool = False
674
+
675
+ self._character_count_since_last_sep: int = 0
676
+
677
+ self._successive_upper_lower_count: int = 0
678
+ self._successive_upper_lower_count_final: int = 0
679
+
680
+ self._character_count: int = 0
681
+
682
+ self._last_alpha_seen: str | None = None
683
+ self._last_alpha_seen_upper: bool = False
684
+ self._last_alpha_seen_lower: bool = False
685
+ self._current_ascii_only: bool = True
686
+
687
+ def feed_info(self, character: str, info: CharInfo) -> None:
688
+ """Optimized feed using pre-computed character info."""
689
+ is_concerned: bool = info.alpha and info.case_variable
690
+ chunk_sep: bool = not is_concerned
691
+
692
+ if chunk_sep and self._character_count_since_last_sep > 0:
693
+ if (
694
+ self._character_count_since_last_sep <= 64
695
+ and not info.digit
696
+ and not self._current_ascii_only
697
+ ):
698
+ self._successive_upper_lower_count_final += (
699
+ self._successive_upper_lower_count
700
+ )
701
+
702
+ self._successive_upper_lower_count = 0
703
+ self._character_count_since_last_sep = 0
704
+ self._last_alpha_seen = None
705
+ self._buf = False
706
+ self._character_count += 1
707
+ self._current_ascii_only = True
708
+
709
+ return
710
+
711
+ if self._current_ascii_only and not info.is_ascii:
712
+ self._current_ascii_only = False
713
+
714
+ if self._last_alpha_seen is not None:
715
+ if (info.upper and self._last_alpha_seen_lower) or (
716
+ info.lower and self._last_alpha_seen_upper
717
+ ):
718
+ if self._buf:
719
+ self._successive_upper_lower_count += 2
720
+ self._buf = False
721
+ else:
722
+ self._buf = True
723
+ else:
724
+ self._buf = False
725
+
726
+ self._character_count += 1
727
+ self._character_count_since_last_sep += 1
728
+ self._last_alpha_seen = character
729
+ self._last_alpha_seen_upper = info.upper
730
+ self._last_alpha_seen_lower = info.lower
731
+
732
+ def reset(self) -> None: # Abstract
733
+ self._character_count = 0
734
+ self._character_count_since_last_sep = 0
735
+ self._successive_upper_lower_count = 0
736
+ self._successive_upper_lower_count_final = 0
737
+ self._last_alpha_seen = None
738
+ self._last_alpha_seen_upper = False
739
+ self._last_alpha_seen_lower = False
740
+ self._buf = False
741
+ self._current_ascii_only = True
742
+
743
+ @property
744
+ def ratio(self) -> float:
745
+ if self._character_count == 0: # Defensive:
746
+ return 0.0
747
+
748
+ return self._successive_upper_lower_count_final / self._character_count
749
+
750
+
751
+ @final
752
+ class ArabicIsolatedFormPlugin(MessDetectorPlugin):
753
+ __slots__ = ("_character_count", "_isolated_form_count")
754
+
755
+ def __init__(self) -> None:
756
+ self._character_count: int = 0
757
+ self._isolated_form_count: int = 0
758
+
759
+ def reset(self) -> None: # Abstract
760
+ self._character_count = 0
761
+ self._isolated_form_count = 0
762
+
763
+ def feed_info(self, character: str, info: CharInfo) -> None:
764
+ """Optimized feed using pre-computed character info."""
765
+ self._character_count += 1
766
+
767
+ if info.flags & _ARABIC_ISOLATED_FORM:
768
+ self._isolated_form_count += 1
769
+
770
+ @property
771
+ def ratio(self) -> float:
772
+ if self._character_count < 8:
773
+ return 0.0
774
+
775
+ isolated_form_usage: float = self._isolated_form_count / self._character_count
776
+
777
+ return isolated_form_usage
778
+
779
+
780
+ @lru_cache(maxsize=1024)
781
+ def is_suspiciously_successive_range(
782
+ unicode_range_a: str | None, unicode_range_b: str | None
783
+ ) -> bool:
784
+ """
785
+ Determine if two Unicode range seen next to each other can be considered as suspicious.
786
+ """
787
+ if unicode_range_a is None or unicode_range_b is None:
788
+ return True
789
+
790
+ if unicode_range_a == unicode_range_b:
791
+ return False
792
+
793
+ if "Latin" in unicode_range_a and "Latin" in unicode_range_b:
794
+ return False
795
+
796
+ if "Emoticons" in unicode_range_a or "Emoticons" in unicode_range_b:
797
+ return False
798
+
799
+ # Latin characters can be accompanied with a combining diacritical mark
800
+ # eg. Vietnamese.
801
+ if ("Latin" in unicode_range_a or "Latin" in unicode_range_b) and (
802
+ "Combining" in unicode_range_a or "Combining" in unicode_range_b
803
+ ):
804
+ return False
805
+
806
+ keywords_range_a, keywords_range_b = (
807
+ unicode_range_a.split(" "),
808
+ unicode_range_b.split(" "),
809
+ )
810
+
811
+ for el in keywords_range_a:
812
+ if el in UNICODE_SECONDARY_RANGE_KEYWORD:
813
+ continue
814
+ if el in keywords_range_b:
815
+ return False
816
+
817
+ # Japanese Exception
818
+ range_a_jp_chars, range_b_jp_chars = (
819
+ unicode_range_a
820
+ in (
821
+ "Hiragana",
822
+ "Katakana",
823
+ ),
824
+ unicode_range_b in ("Hiragana", "Katakana"),
825
+ )
826
+ if (range_a_jp_chars or range_b_jp_chars) and (
827
+ "CJK" in unicode_range_a or "CJK" in unicode_range_b
828
+ ):
829
+ return False
830
+ if range_a_jp_chars and range_b_jp_chars:
831
+ return False
832
+
833
+ if "Hangul" in unicode_range_a or "Hangul" in unicode_range_b:
834
+ if "CJK" in unicode_range_a or "CJK" in unicode_range_b:
835
+ return False
836
+ if unicode_range_a == "Basic Latin" or unicode_range_b == "Basic Latin":
837
+ return False
838
+
839
+ # Chinese/Japanese use dedicated range for punctuation and/or separators.
840
+ if ("CJK" in unicode_range_a or "CJK" in unicode_range_b) or (
841
+ unicode_range_a in ["Katakana", "Hiragana"]
842
+ and unicode_range_b in ["Katakana", "Hiragana"]
843
+ ):
844
+ if "Punctuation" in unicode_range_a or "Punctuation" in unicode_range_b:
845
+ return False
846
+ if "Forms" in unicode_range_a or "Forms" in unicode_range_b:
847
+ return False
848
+ if unicode_range_a == "Basic Latin" or unicode_range_b == "Basic Latin":
849
+ return False
850
+
851
+ return True
852
+
853
+
854
+ def mess_ratio(
855
+ decoded_sequence: str, maximum_threshold: float = 0.2, debug: bool = False
856
+ ) -> float:
857
+ """
858
+ Compute a mess ratio given a decoded bytes sequence. The maximum threshold does stop the computation earlier.
859
+ """
860
+
861
+ seq_len: int = len(decoded_sequence)
862
+
863
+ if seq_len < 511:
864
+ step: int = 32
865
+ elif seq_len < 1024:
866
+ step = 64
867
+ else:
868
+ step = 128
869
+
870
+ # str.isascii() is O(1) (the flag lives in the str header). Six of the
871
+ # nine detectors provably keep a 0.0 ratio on ASCII-only input and are
872
+ # therefore not fed at all.
873
+ is_pure_ascii: bool = decoded_sequence.isascii()
874
+
875
+ # Cached per-codepoint character properties (see CharInfo). ASCII
876
+ # characters resolve through the immutable import-time table; anything
877
+ # else goes through the lru_cache-backed slow path.
878
+ ascii_info = _ASCII_CHAR_INFO
879
+ char_info = _char_info
880
+
881
+ mean_mess_ratio: float
882
+ info: CharInfo
883
+
884
+ # Create each detector as a named local variable (unrolled from the generic loop).
885
+ # This eliminates per-character iteration over the detector list and
886
+ # per-character eligible() virtual dispatch, while keeping every plugin class
887
+ # intact and fully readable.
888
+ d_sp: TooManySymbolOrPunctuationPlugin = TooManySymbolOrPunctuationPlugin()
889
+ d_ta: TooManyAccentuatedPlugin = TooManyAccentuatedPlugin()
890
+ d_up: UnprintablePlugin = UnprintablePlugin()
891
+ d_sda: SuspiciousDuplicateAccentPlugin = SuspiciousDuplicateAccentPlugin()
892
+ d_sr: SuspiciousRange = SuspiciousRange()
893
+ d_sw: SuperWeirdWordPlugin = SuperWeirdWordPlugin()
894
+ d_cu: CjkUncommonPlugin = CjkUncommonPlugin()
895
+ d_au: ArchaicUpperLowerPlugin = ArchaicUpperLowerPlugin()
896
+ d_ai: ArabicIsolatedFormPlugin = ArabicIsolatedFormPlugin()
897
+
898
+ # Local references for feed_info methods called in the hot loop.
899
+ d_sp_feed = d_sp.feed_info
900
+ d_ta_feed = d_ta.feed_info
901
+ d_up_feed = d_up.feed_info
902
+ d_sda_feed = d_sda.feed_info
903
+ d_sr_feed = d_sr.feed_info
904
+ d_sw_feed = d_sw.feed_info
905
+ d_cu_feed = d_cu.feed_info
906
+ d_au_feed = d_au.feed_info
907
+ d_ai_feed = d_ai.feed_info
908
+
909
+ for block_start in range(0, seq_len, step):
910
+ for character in decoded_sequence[block_start : block_start + step]:
911
+ # Character properties computed once per distinct codepoint
912
+ # (shared across all plugins and all mess_ratio calls).
913
+ # ord() doubles as the ASCII table index and, unlike
914
+ # str.isascii(), lowers to a mypyc primitive.
915
+ codepoint: int = ord(character)
916
+ if codepoint < 128:
917
+ info = ascii_info[codepoint]
918
+ else:
919
+ info = char_info(character)
920
+
921
+ # Detectors with eligible() == always True
922
+ d_up_feed(character, info)
923
+ d_sw_feed(character, info)
924
+
925
+ if is_pure_ascii:
926
+ # The six remaining detectors provably stay at 0.0 (see above).
927
+ if info.printable:
928
+ d_sp_feed(character, info)
929
+ continue
930
+
931
+ d_au_feed(character, info)
932
+
933
+ # Detectors with eligible() == isprintable
934
+ if info.printable:
935
+ d_sp_feed(character, info)
936
+ d_sr_feed(character, info)
937
+
938
+ # Detectors with eligible() == isalpha
939
+ if info.alpha:
940
+ d_ta_feed(character, info)
941
+ # SuspiciousDuplicateAccent: isalpha() and is_latin()
942
+ if info.latin:
943
+ d_sda_feed(character, info)
944
+ # CjkUncommon: is_cjk()
945
+ if info.is_cjk:
946
+ d_cu_feed(character, info)
947
+ # ArabicIsolatedForm: is_arabic()
948
+ if info.is_arabic:
949
+ d_ai_feed(character, info)
950
+
951
+ mean_mess_ratio = (
952
+ d_sp.ratio
953
+ + d_ta.ratio
954
+ + d_up.ratio
955
+ + d_sda.ratio
956
+ + d_sr.ratio
957
+ + d_sw.ratio
958
+ + d_cu.ratio
959
+ + d_au.ratio
960
+ + d_ai.ratio
961
+ )
962
+
963
+ if mean_mess_ratio >= maximum_threshold:
964
+ break
965
+ else:
966
+ # Flush last word buffer in SuperWeirdWordPlugin via trailing newline.
967
+ nl_info = ascii_info[10] # "\n"
968
+ d_sw_feed("\n", nl_info)
969
+ if not is_pure_ascii:
970
+ d_au_feed("\n", nl_info)
971
+ d_up_feed("\n", nl_info)
972
+
973
+ mean_mess_ratio = (
974
+ d_sp.ratio
975
+ + d_ta.ratio
976
+ + d_up.ratio
977
+ + d_sda.ratio
978
+ + d_sr.ratio
979
+ + d_sw.ratio
980
+ + d_cu.ratio
981
+ + d_au.ratio
982
+ + d_ai.ratio
983
+ )
984
+
985
+ if debug: # Defensive:
986
+ logger = getLogger("charset_normalizer")
987
+
988
+ logger.log(
989
+ TRACE,
990
+ "Mess-detector extended-analysis start. "
991
+ f"intermediary_mean_mess_ratio_calc={step} mean_mess_ratio={mean_mess_ratio} "
992
+ f"maximum_threshold={maximum_threshold}",
993
+ )
994
+
995
+ if seq_len > 16:
996
+ logger.log(TRACE, f"Starting with: {decoded_sequence[:16]}")
997
+ logger.log(TRACE, f"Ending with: {decoded_sequence[-16::]}")
998
+
999
+ for dt in [d_sp, d_ta, d_up, d_sda, d_sr, d_sw, d_cu, d_au, d_ai]:
1000
+ logger.log(TRACE, f"{dt.__class__}: {dt.ratio}")
1001
+
1002
+ return round(mean_mess_ratio, 3)
data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer/models.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from encodings.aliases import aliases
4
+ from re import sub
5
+ from typing import Any, Iterator, List, Tuple
6
+
7
+ from .constant import RE_POSSIBLE_ENCODING_INDICATION, TOO_BIG_SEQUENCE
8
+ from .utils import iana_name, is_multi_byte_encoding, unicode_range
9
+
10
+
11
+ class CharsetMatch:
12
+ def __init__(
13
+ self,
14
+ payload: bytes | bytearray,
15
+ guessed_encoding: str,
16
+ mean_mess_ratio: float,
17
+ has_sig_or_bom: bool,
18
+ languages: CoherenceMatches,
19
+ decoded_payload: str | None = None,
20
+ preemptive_declaration: str | None = None,
21
+ ):
22
+ self._payload: bytes | bytearray = payload
23
+
24
+ self._encoding: str = guessed_encoding
25
+ self._mean_mess_ratio: float = mean_mess_ratio
26
+ self._languages: CoherenceMatches = languages
27
+ self._has_sig_or_bom: bool = has_sig_or_bom
28
+ self._unicode_ranges: list[str] | None = None
29
+
30
+ self._leaves: list[CharsetMatch] = []
31
+ self._mean_coherence_ratio: float = 0.0
32
+
33
+ self._output_payload: bytes | None = None
34
+ self._output_encoding: str | None = None
35
+
36
+ self._string: str | None = decoded_payload
37
+
38
+ self._preemptive_declaration: str | None = preemptive_declaration
39
+
40
+ def __eq__(self, other: object) -> bool:
41
+ if not isinstance(other, CharsetMatch):
42
+ if isinstance(other, str):
43
+ return iana_name(other) == self.encoding
44
+ return False
45
+ return self.encoding == other.encoding and self.fingerprint == other.fingerprint
46
+
47
+ def __lt__(self, other: object) -> bool:
48
+ """
49
+ Implemented to make sorted available upon CharsetMatches items.
50
+ """
51
+ if not isinstance(other, CharsetMatch):
52
+ raise ValueError
53
+
54
+ chaos_difference: float = abs(self.chaos - other.chaos)
55
+ coherence_difference: float = abs(self.coherence - other.coherence)
56
+
57
+ # Below 0.5% difference --> Use Coherence
58
+ if chaos_difference < 0.005 and coherence_difference > 0.02:
59
+ return self.coherence > other.coherence
60
+ elif chaos_difference < 0.005 and coherence_difference <= 0.02:
61
+ # When having a difficult decision, use the result that decoded as many multi-byte as possible.
62
+ # preserve RAM usage!
63
+ if len(self._payload) >= TOO_BIG_SEQUENCE:
64
+ return self.chaos < other.chaos
65
+ return self.multi_byte_usage > other.multi_byte_usage
66
+
67
+ return self.chaos < other.chaos
68
+
69
+ @property
70
+ def multi_byte_usage(self) -> float:
71
+ return 1.0 - (len(str(self)) / len(self.raw))
72
+
73
+ def __str__(self) -> str:
74
+ # Lazy Str Loading
75
+ if self._string is None:
76
+ self._string = str(self._payload, self._encoding, "strict")
77
+ # UTF-7 BOM is encoded in modified Base64 whose byte boundary
78
+ # can overlap with the next character, so raw-byte stripping
79
+ # is unreliable. Strip the decoded BOM character instead.
80
+ if (
81
+ self._has_sig_or_bom
82
+ and self._encoding == "utf_7"
83
+ and self._string
84
+ and self._string[0] == "\ufeff"
85
+ ):
86
+ self._string = self._string[1:]
87
+ return self._string
88
+
89
+ def __repr__(self) -> str:
90
+ return f"<CharsetMatch '{self.encoding}' fp({self.fingerprint})>"
91
+
92
+ def add_submatch(self, other: CharsetMatch) -> None:
93
+ if not isinstance(other, CharsetMatch) or other == self:
94
+ raise ValueError(
95
+ "Unable to add instance <{}> as a submatch of a CharsetMatch".format(
96
+ other.__class__
97
+ )
98
+ )
99
+
100
+ other._string = None # Unload RAM usage; dirty trick.
101
+ self._leaves.append(other)
102
+
103
+ @property
104
+ def encoding(self) -> str:
105
+ return self._encoding
106
+
107
+ @property
108
+ def encoding_aliases(self) -> list[str]:
109
+ """
110
+ Encoding name are known by many name, using this could help when searching for IBM855 when it's listed as CP855.
111
+ """
112
+ also_known_as: list[str] = []
113
+ for u, p in aliases.items():
114
+ if self.encoding == u:
115
+ also_known_as.append(p)
116
+ elif self.encoding == p:
117
+ also_known_as.append(u)
118
+ return also_known_as
119
+
120
+ @property
121
+ def bom(self) -> bool:
122
+ return self._has_sig_or_bom
123
+
124
+ @property
125
+ def byte_order_mark(self) -> bool:
126
+ return self._has_sig_or_bom
127
+
128
+ @property
129
+ def languages(self) -> list[str]:
130
+ """
131
+ Return the complete list of possible languages found in decoded sequence.
132
+ Usually not really useful. Returned list may be empty even if 'language' property return something != 'Unknown'.
133
+ """
134
+ return [e[0] for e in self._languages]
135
+
136
+ @property
137
+ def language(self) -> str:
138
+ """
139
+ Most probable language found in decoded sequence. If none were detected or inferred, the property will return
140
+ "Unknown".
141
+ """
142
+ if not self._languages:
143
+ # Trying to infer the language based on the given encoding
144
+ # Its either English or we should not pronounce ourselves in certain cases.
145
+ if "ascii" in self.could_be_from_charset:
146
+ return "English"
147
+
148
+ # doing it there to avoid circular import
149
+ from charset_normalizer.cd import encoding_languages, mb_encoding_languages
150
+
151
+ languages = (
152
+ mb_encoding_languages(self.encoding)
153
+ if is_multi_byte_encoding(self.encoding)
154
+ else encoding_languages(self.encoding)
155
+ )
156
+
157
+ if len(languages) == 0 or "Latin Based" in languages:
158
+ return "Unknown"
159
+
160
+ return languages[0]
161
+
162
+ return self._languages[0][0]
163
+
164
+ @property
165
+ def chaos(self) -> float:
166
+ return self._mean_mess_ratio
167
+
168
+ @property
169
+ def coherence(self) -> float:
170
+ if not self._languages:
171
+ return 0.0
172
+ return self._languages[0][1]
173
+
174
+ @property
175
+ def percent_chaos(self) -> float:
176
+ return round(self.chaos * 100, ndigits=3)
177
+
178
+ @property
179
+ def percent_coherence(self) -> float:
180
+ return round(self.coherence * 100, ndigits=3)
181
+
182
+ @property
183
+ def raw(self) -> bytes | bytearray:
184
+ """
185
+ Original untouched bytes.
186
+ """
187
+ return self._payload
188
+
189
+ @property
190
+ def submatch(self) -> list[CharsetMatch]:
191
+ return self._leaves
192
+
193
+ @property
194
+ def has_submatch(self) -> bool:
195
+ return len(self._leaves) > 0
196
+
197
+ @property
198
+ def alphabets(self) -> list[str]:
199
+ if self._unicode_ranges is not None:
200
+ return self._unicode_ranges
201
+ # list detected ranges
202
+ detected_ranges: list[str | None] = [unicode_range(char) for char in str(self)]
203
+ # filter and sort
204
+ self._unicode_ranges = sorted(list({r for r in detected_ranges if r}))
205
+ return self._unicode_ranges
206
+
207
+ @property
208
+ def could_be_from_charset(self) -> list[str]:
209
+ """
210
+ The complete list of encoding that output the exact SAME str result and therefore could be the originating
211
+ encoding.
212
+ This list does include the encoding available in property 'encoding'.
213
+ """
214
+ return [self._encoding] + [m.encoding for m in self._leaves]
215
+
216
+ def output(self, encoding: str = "utf_8") -> bytes:
217
+ """
218
+ Method to get re-encoded bytes payload using given target encoding. Default to UTF-8.
219
+ Any errors will be simply ignored by the encoder NOT replaced.
220
+ """
221
+ if self._output_encoding is None or self._output_encoding != encoding:
222
+ self._output_encoding = encoding
223
+ decoded_string = str(self)
224
+ if (
225
+ self._preemptive_declaration is not None
226
+ and self._preemptive_declaration.lower()
227
+ not in ["utf-8", "utf8", "utf_8"]
228
+ ):
229
+ patched_header = sub(
230
+ RE_POSSIBLE_ENCODING_INDICATION,
231
+ lambda m: m.string[m.span()[0] : m.span()[1]].replace(
232
+ m.groups()[0],
233
+ iana_name(self._output_encoding).replace("_", "-"), # type: ignore[arg-type]
234
+ ),
235
+ decoded_string[:8192],
236
+ count=1,
237
+ )
238
+
239
+ decoded_string = patched_header + decoded_string[8192:]
240
+
241
+ self._output_payload = decoded_string.encode(encoding, "replace")
242
+
243
+ return self._output_payload # type: ignore
244
+
245
+ @property
246
+ def fingerprint(self) -> int:
247
+ """
248
+ Retrieve a hash fingerprint of the decoded payload, used for deduplication.
249
+ """
250
+ return hash(str(self))
251
+
252
+
253
+ class CharsetMatches:
254
+ """
255
+ Container with every CharsetMatch items ordered by default from most probable to the less one.
256
+ Act like a list(iterable) but does not implements all related methods.
257
+ """
258
+
259
+ def __init__(self, results: list[CharsetMatch] | None = None):
260
+ self._results: list[CharsetMatch] = sorted(results) if results else []
261
+
262
+ def __iter__(self) -> Iterator[CharsetMatch]:
263
+ yield from self._results
264
+
265
+ def __getitem__(self, item: int | str) -> CharsetMatch:
266
+ """
267
+ Retrieve a single item either by its position or encoding name (alias may be used here).
268
+ Raise KeyError upon invalid index or encoding not present in results.
269
+ """
270
+ if isinstance(item, int):
271
+ return self._results[item]
272
+ if isinstance(item, str):
273
+ item = iana_name(item, False)
274
+ for result in self._results:
275
+ if item in result.could_be_from_charset:
276
+ return result
277
+ raise KeyError
278
+
279
+ def __len__(self) -> int:
280
+ return len(self._results)
281
+
282
+ def __bool__(self) -> bool:
283
+ return len(self._results) > 0
284
+
285
+ def append(self, item: CharsetMatch) -> None:
286
+ """
287
+ Insert a single match. Will be inserted accordingly to preserve sort.
288
+ Can be inserted as a submatch.
289
+ """
290
+ if not isinstance(item, CharsetMatch):
291
+ raise ValueError(
292
+ "Cannot append instance '{}' to CharsetMatches".format(
293
+ str(item.__class__)
294
+ )
295
+ )
296
+ # We should disable the submatch factoring when the input file is too heavy (conserve RAM usage)
297
+ if len(item.raw) < TOO_BIG_SEQUENCE:
298
+ for match in self._results:
299
+ if match.fingerprint == item.fingerprint and match.chaos == item.chaos:
300
+ match.add_submatch(item)
301
+ return
302
+ self._results.append(item)
303
+ self._results = sorted(self._results)
304
+
305
+ def best(self) -> CharsetMatch | None:
306
+ """
307
+ Simply return the first match. Strict equivalent to matches[0].
308
+ """
309
+ if not self._results:
310
+ return None
311
+ return self._results[0]
312
+
313
+ def first(self) -> CharsetMatch | None:
314
+ """
315
+ Redundant method, call the method best(). Kept for BC reasons.
316
+ """
317
+ return self.best()
318
+
319
+
320
+ CoherenceMatch = Tuple[str, float]
321
+ CoherenceMatches = List[CoherenceMatch]
322
+
323
+
324
+ class CliDetectionResult:
325
+ def __init__(
326
+ self,
327
+ path: str,
328
+ encoding: str | None,
329
+ encoding_aliases: list[str],
330
+ alternative_encodings: list[str],
331
+ language: str,
332
+ alphabets: list[str],
333
+ has_sig_or_bom: bool,
334
+ chaos: float,
335
+ coherence: float,
336
+ unicode_path: str | None,
337
+ is_preferred: bool,
338
+ ):
339
+ self.path: str = path
340
+ self.unicode_path: str | None = unicode_path
341
+ self.encoding: str | None = encoding
342
+ self.encoding_aliases: list[str] = encoding_aliases
343
+ self.alternative_encodings: list[str] = alternative_encodings
344
+ self.language: str = language
345
+ self.alphabets: list[str] = alphabets
346
+ self.has_sig_or_bom: bool = has_sig_or_bom
347
+ self.chaos: float = chaos
348
+ self.coherence: float = coherence
349
+ self.is_preferred: bool = is_preferred
350
+
351
+ @property
352
+ def __dict__(self) -> dict[str, Any]: # type: ignore
353
+ return {
354
+ "path": self.path,
355
+ "encoding": self.encoding,
356
+ "encoding_aliases": self.encoding_aliases,
357
+ "alternative_encodings": self.alternative_encodings,
358
+ "language": self.language,
359
+ "alphabets": self.alphabets,
360
+ "has_sig_or_bom": self.has_sig_or_bom,
361
+ "chaos": self.chaos,
362
+ "coherence": self.coherence,
363
+ "unicode_path": self.unicode_path,
364
+ "is_preferred": self.is_preferred,
365
+ }
366
+
367
+ def to_json(self) -> str:
368
+ from json import dumps
369
+
370
+ return dumps(self.__dict__, ensure_ascii=True, indent=4)
data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer/utils.py ADDED
@@ -0,0 +1,455 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import importlib
4
+ import logging
5
+ import unicodedata
6
+ from bisect import bisect_right
7
+ from codecs import IncrementalDecoder
8
+ from encodings.aliases import aliases
9
+ from functools import lru_cache
10
+ from re import findall
11
+ from typing import Generator
12
+
13
+ from .constant import (
14
+ ENCODING_MARKS,
15
+ IANA_SUPPORTED_SIMILAR,
16
+ RE_POSSIBLE_ENCODING_INDICATION,
17
+ UNICODE_RANGES_COMBINED,
18
+ _SECONDARY_RANGE_NAMES,
19
+ UTF8_MAXIMAL_ALLOCATION,
20
+ COMMON_CJK_CHARACTERS,
21
+ _LATIN,
22
+ _CJK,
23
+ _HANGUL,
24
+ _KATAKANA,
25
+ _HIRAGANA,
26
+ _THAI,
27
+ _ARABIC,
28
+ _ARABIC_ISOLATED_FORM,
29
+ _ACCENT_KEYWORDS,
30
+ _ACCENTUATED,
31
+ )
32
+
33
+
34
+ def _character_flags(character: str) -> int:
35
+ """Compute all name-based classification flags with a single unicodedata.name() call."""
36
+ try:
37
+ desc: str = unicodedata.name(character)
38
+ except ValueError:
39
+ return 0
40
+
41
+ flags: int = 0
42
+
43
+ if "LATIN" in desc:
44
+ flags |= _LATIN
45
+ if "CJK" in desc:
46
+ flags |= _CJK
47
+ if "HANGUL" in desc:
48
+ flags |= _HANGUL
49
+ if "KATAKANA" in desc:
50
+ flags |= _KATAKANA
51
+ if "HIRAGANA" in desc:
52
+ flags |= _HIRAGANA
53
+ if "THAI" in desc:
54
+ flags |= _THAI
55
+ if "ARABIC" in desc:
56
+ flags |= _ARABIC
57
+ if "ISOLATED FORM" in desc:
58
+ flags |= _ARABIC_ISOLATED_FORM
59
+
60
+ for kw in _ACCENT_KEYWORDS:
61
+ if kw in desc:
62
+ flags |= _ACCENTUATED
63
+ break
64
+
65
+ return flags
66
+
67
+
68
+ def is_accentuated(character: str) -> bool:
69
+ return bool(_character_flags(character) & _ACCENTUATED)
70
+
71
+
72
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
73
+ def remove_accent(character: str) -> str:
74
+ decomposed: str = unicodedata.decomposition(character)
75
+ if not decomposed:
76
+ return character
77
+
78
+ codes: list[str] = decomposed.split(" ")
79
+
80
+ return chr(int(codes[0], 16))
81
+
82
+
83
+ # Pre-built sorted lookup table for O(log n) binary search in unicode_range().
84
+ # Each entry is (range_start, range_end_exclusive, range_name).
85
+ _UNICODE_RANGES_SORTED: list[tuple[int, int, str]] = sorted(
86
+ (ord_range.start, ord_range.stop, name)
87
+ for name, ord_range in UNICODE_RANGES_COMBINED.items()
88
+ )
89
+ _UNICODE_RANGE_STARTS: list[int] = [e[0] for e in _UNICODE_RANGES_SORTED]
90
+
91
+
92
+ def unicode_range(character: str) -> str | None:
93
+ """
94
+ Retrieve the Unicode range official name from a single character.
95
+ """
96
+ character_ord: int = ord(character)
97
+
98
+ # Binary search: find the rightmost range whose start <= character_ord
99
+ idx = bisect_right(_UNICODE_RANGE_STARTS, character_ord) - 1
100
+ if idx >= 0:
101
+ start, stop, name = _UNICODE_RANGES_SORTED[idx]
102
+ if character_ord < stop:
103
+ return name
104
+
105
+ return None
106
+
107
+
108
+ def is_latin(character: str) -> bool:
109
+ return bool(_character_flags(character) & _LATIN)
110
+
111
+
112
+ def is_punctuation(character: str) -> bool:
113
+ character_category: str = unicodedata.category(character)
114
+
115
+ if "P" in character_category:
116
+ return True
117
+
118
+ character_range: str | None = unicode_range(character)
119
+
120
+ if character_range is None:
121
+ return False
122
+
123
+ return "Punctuation" in character_range
124
+
125
+
126
+ def is_symbol(character: str) -> bool:
127
+ character_category: str = unicodedata.category(character)
128
+
129
+ if "S" in character_category or "N" in character_category:
130
+ return True
131
+
132
+ character_range: str | None = unicode_range(character)
133
+
134
+ if character_range is None:
135
+ return False
136
+
137
+ return "Forms" in character_range and character_category != "Lo"
138
+
139
+
140
+ def is_emoticon(character: str) -> bool:
141
+ character_range: str | None = unicode_range(character)
142
+
143
+ if character_range is None:
144
+ return False
145
+
146
+ return "Emoticons" in character_range or "Pictographs" in character_range
147
+
148
+
149
+ def is_separator(character: str) -> bool:
150
+ if character.isspace() or character in {"|", "+", "<", ">"}:
151
+ return True
152
+
153
+ character_category: str = unicodedata.category(character)
154
+
155
+ return "Z" in character_category or character_category in {"Po", "Pd", "Pc"}
156
+
157
+
158
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
159
+ def is_case_variable(character: str) -> bool:
160
+ return character.islower() != character.isupper()
161
+
162
+
163
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
164
+ def is_cjk(character: str) -> bool:
165
+ return bool(_character_flags(character) & _CJK)
166
+
167
+
168
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
169
+ def is_hiragana(character: str) -> bool:
170
+ return bool(_character_flags(character) & _HIRAGANA)
171
+
172
+
173
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
174
+ def is_katakana(character: str) -> bool:
175
+ return bool(_character_flags(character) & _KATAKANA)
176
+
177
+
178
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
179
+ def is_hangul(character: str) -> bool:
180
+ return bool(_character_flags(character) & _HANGUL)
181
+
182
+
183
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
184
+ def is_thai(character: str) -> bool:
185
+ return bool(_character_flags(character) & _THAI)
186
+
187
+
188
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
189
+ def is_arabic(character: str) -> bool:
190
+ return bool(_character_flags(character) & _ARABIC)
191
+
192
+
193
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
194
+ def is_arabic_isolated_form(character: str) -> bool:
195
+ return bool(_character_flags(character) & _ARABIC_ISOLATED_FORM)
196
+
197
+
198
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
199
+ def is_cjk_uncommon(character: str) -> bool:
200
+ return character not in COMMON_CJK_CHARACTERS
201
+
202
+
203
+ def is_unicode_range_secondary(range_name: str) -> bool:
204
+ return range_name in _SECONDARY_RANGE_NAMES
205
+
206
+
207
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
208
+ def is_unprintable(character: str) -> bool:
209
+ return (
210
+ not character.isspace() # includes \n \t \r \v
211
+ and not character.isprintable()
212
+ and character != "\x1a" # Why? Its the ASCII substitute character.
213
+ and character != "\ufeff" # bug discovered in Python,
214
+ # Zero Width No-Break Space located in Arabic Presentation Forms-B, Unicode 1.1 not acknowledged as space.
215
+ )
216
+
217
+
218
+ def any_specified_encoding(
219
+ sequence: bytes | bytearray, search_zone: int = 8192
220
+ ) -> str | None:
221
+ """
222
+ Extract using ASCII-only decoder any specified encoding in the first n-bytes.
223
+ """
224
+ if not isinstance(sequence, (bytes, bytearray)):
225
+ raise TypeError
226
+
227
+ seq_len: int = len(sequence)
228
+
229
+ decoded_zone: str = sequence[: min(seq_len, search_zone)].decode(
230
+ "ascii", errors="ignore"
231
+ )
232
+
233
+ # Cheap literal pre-filter.
234
+ lowered_zone: str = decoded_zone.lower()
235
+ if "coding" not in lowered_zone and "charset" not in lowered_zone:
236
+ return None
237
+
238
+ results: list[str] = findall(
239
+ RE_POSSIBLE_ENCODING_INDICATION,
240
+ decoded_zone,
241
+ )
242
+
243
+ if len(results) == 0:
244
+ return None
245
+
246
+ for specified_encoding in results:
247
+ specified_encoding = specified_encoding.lower().replace("-", "_")
248
+
249
+ encoding_alias: str
250
+ encoding_iana: str
251
+
252
+ for encoding_alias, encoding_iana in aliases.items():
253
+ if encoding_alias == specified_encoding:
254
+ return encoding_iana
255
+ if encoding_iana == specified_encoding:
256
+ return encoding_iana
257
+
258
+ return None
259
+
260
+
261
+ @lru_cache(maxsize=128)
262
+ def is_multi_byte_encoding(name: str) -> bool:
263
+ """
264
+ Verify is a specific encoding is a multi byte one based on it IANA name
265
+ """
266
+ if name in {
267
+ "utf_8",
268
+ "utf_8_sig",
269
+ "utf_16",
270
+ "utf_16_be",
271
+ "utf_16_le",
272
+ "utf_32",
273
+ "utf_32_le",
274
+ "utf_32_be",
275
+ "utf_7",
276
+ }:
277
+ return True
278
+
279
+ # Besides the Unicode family above, every multibyte codec shipped with
280
+ # Python is implemented by _multibytecodec through exactly one of the six
281
+ # cjkcodecs providers below. Probing those providers directly (getcodec)
282
+ # classifies a name without importing its "encodings.<name>" module:
283
+ # classifying the whole IANA_SUPPORTED list would otherwise import many
284
+ # modules and dominate "import charset_normalizer" wall time.
285
+ # see https://github.com/jawah/charset_normalizer/issues/742
286
+ for provider in (
287
+ "_codecs_cn",
288
+ "_codecs_hk",
289
+ "_codecs_iso2022",
290
+ "_codecs_jp",
291
+ "_codecs_kr",
292
+ "_codecs_tw",
293
+ ):
294
+ try:
295
+ importlib.import_module(provider).getcodec(name) # type: ignore[attr-defined]
296
+ except (ImportError, AttributeError, LookupError): # Defensive: edge cases
297
+ continue
298
+ return True
299
+
300
+ return False
301
+
302
+
303
+ def identify_sig_or_bom(sequence: bytes | bytearray) -> tuple[str | None, bytes]:
304
+ """
305
+ Identify and extract SIG/BOM in given sequence.
306
+ """
307
+
308
+ for iana_encoding in ENCODING_MARKS:
309
+ marks: bytes | list[bytes] = ENCODING_MARKS[iana_encoding]
310
+
311
+ if isinstance(marks, bytes):
312
+ marks = [marks]
313
+
314
+ for mark in marks:
315
+ if sequence.startswith(mark):
316
+ return iana_encoding, mark
317
+
318
+ return None, b""
319
+
320
+
321
+ def should_strip_sig_or_bom(iana_encoding: str) -> bool:
322
+ return iana_encoding not in {"utf_16", "utf_32"}
323
+
324
+
325
+ def iana_name(cp_name: str, strict: bool = True) -> str:
326
+ """Returns the Python normalized encoding name (Not the IANA official name)."""
327
+ cp_name = cp_name.lower().replace("-", "_")
328
+
329
+ encoding_alias: str
330
+ encoding_iana: str
331
+
332
+ for encoding_alias, encoding_iana in aliases.items():
333
+ if cp_name in [encoding_alias, encoding_iana]:
334
+ return encoding_iana
335
+
336
+ if strict:
337
+ raise ValueError(f"Unable to retrieve IANA for '{cp_name}'")
338
+
339
+ return cp_name
340
+
341
+
342
+ def cp_similarity(iana_name_a: str, iana_name_b: str) -> float:
343
+ if is_multi_byte_encoding(iana_name_a) or is_multi_byte_encoding(iana_name_b):
344
+ return 0.0
345
+
346
+ decoder_a = importlib.import_module(f"encodings.{iana_name_a}").IncrementalDecoder
347
+ decoder_b = importlib.import_module(f"encodings.{iana_name_b}").IncrementalDecoder
348
+
349
+ id_a: IncrementalDecoder = decoder_a(errors="ignore")
350
+ id_b: IncrementalDecoder = decoder_b(errors="ignore")
351
+
352
+ character_match_count: int = 0
353
+
354
+ for i in range(256):
355
+ to_be_decoded: bytes = bytes([i])
356
+ if id_a.decode(to_be_decoded) == id_b.decode(to_be_decoded):
357
+ character_match_count += 1
358
+
359
+ return character_match_count / 256
360
+
361
+
362
+ def is_cp_similar(iana_name_a: str, iana_name_b: str) -> bool:
363
+ """
364
+ Determine if two code page are at least 80% similar. IANA_SUPPORTED_SIMILAR dict was generated using
365
+ the function cp_similarity.
366
+ """
367
+ return (
368
+ iana_name_a in IANA_SUPPORTED_SIMILAR
369
+ and iana_name_b in IANA_SUPPORTED_SIMILAR[iana_name_a]
370
+ )
371
+
372
+
373
+ def set_logging_handler(
374
+ name: str = "charset_normalizer",
375
+ level: int = logging.INFO,
376
+ format_string: str = "%(asctime)s | %(levelname)s | %(message)s",
377
+ ) -> None:
378
+ logger = logging.getLogger(name)
379
+ logger.setLevel(level)
380
+
381
+ handler = logging.StreamHandler()
382
+ handler.setFormatter(logging.Formatter(format_string))
383
+ logger.addHandler(handler)
384
+
385
+
386
+ def cut_sequence_chunks(
387
+ sequences: bytes | bytearray,
388
+ encoding_iana: str,
389
+ offsets: range,
390
+ chunk_size: int,
391
+ bom_or_sig_available: bool,
392
+ strip_sig_or_bom: bool,
393
+ sig_payload: bytes,
394
+ is_multi_byte_decoder: bool,
395
+ decoded_payload: str | None = None,
396
+ deferred_decoding: bool = False,
397
+ ) -> Generator[str, None, None]:
398
+ if decoded_payload and not is_multi_byte_decoder:
399
+ for i in offsets:
400
+ chunk = decoded_payload[i : i + chunk_size]
401
+ if not chunk:
402
+ break
403
+ yield chunk
404
+ elif deferred_decoding:
405
+ # Deferred single-byte probing: the whole payload is not decoded
406
+ # yet. Single-byte codecs are stateless (1 byte == 1 char), hence
407
+ # decode(base)[i:j] == decode(base[i:j]): slicing the raw bytes
408
+ # yields exactly the chunks the branch above would have produced,
409
+ # short trailing chunks included, and raises UnicodeDecodeError on
410
+ # invalid bytes just like the whole-payload decode would.
411
+ base_bytes = (
412
+ sequences if not strip_sig_or_bom else sequences[len(sig_payload) :]
413
+ )
414
+ for i in offsets:
415
+ cut_sequence = base_bytes[i : i + chunk_size]
416
+ if not cut_sequence:
417
+ break
418
+ yield str(cut_sequence, encoding_iana)
419
+ else:
420
+ for i in offsets:
421
+ chunk_end = i + chunk_size
422
+ if chunk_end > len(sequences) + 8:
423
+ continue
424
+
425
+ cut_sequence = sequences[i : i + chunk_size]
426
+
427
+ if bom_or_sig_available and not strip_sig_or_bom:
428
+ cut_sequence = sig_payload + cut_sequence
429
+
430
+ chunk = cut_sequence.decode(
431
+ encoding_iana,
432
+ errors="ignore" if is_multi_byte_decoder else "strict",
433
+ )
434
+
435
+ # multi-byte bad cutting detector and adjustment
436
+ # not the cleanest way to perform that fix but clever enough for now.
437
+ if is_multi_byte_decoder and i > 0:
438
+ chunk_partial_size_chk: int = min(chunk_size, 16)
439
+
440
+ if (
441
+ decoded_payload
442
+ and chunk[:chunk_partial_size_chk] not in decoded_payload
443
+ ):
444
+ for j in range(i, i - 4, -1):
445
+ cut_sequence = sequences[j:chunk_end]
446
+
447
+ if bom_or_sig_available and not strip_sig_or_bom:
448
+ cut_sequence = sig_payload + cut_sequence
449
+
450
+ chunk = cut_sequence.decode(encoding_iana, errors="ignore")
451
+
452
+ if chunk[:chunk_partial_size_chk] in decoded_payload:
453
+ break
454
+
455
+ yield chunk
data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer/version.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Expose version
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ __version__ = "3.4.9"
8
+ VERSION = __version__.split(".")
data/diffusion/.venv/lib/python3.11/site-packages/packaging-26.2.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ uv
data/diffusion/.venv/lib/python3.11/site-packages/packaging-26.2.dist-info/METADATA ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: packaging
3
+ Version: 26.2
4
+ Summary: Core utilities for Python packages
5
+ Author-email: Donald Stufft <donald@stufft.io>
6
+ Requires-Python: >=3.8
7
+ Description-Content-Type: text/x-rst
8
+ License-Expression: Apache-2.0 OR BSD-2-Clause
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Classifier: Programming Language :: Python :: 3.8
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Programming Language :: Python :: Implementation :: CPython
22
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
23
+ Classifier: Programming Language :: Python :: Free Threading :: 4 - Resilient
24
+ Classifier: Typing :: Typed
25
+ License-File: LICENSE
26
+ License-File: LICENSE.APACHE
27
+ License-File: LICENSE.BSD
28
+ Project-URL: Documentation, https://packaging.pypa.io/
29
+ Project-URL: Source, https://github.com/pypa/packaging
30
+
31
+ packaging
32
+ =========
33
+
34
+ .. start-intro
35
+
36
+ Reusable core utilities for various Python Packaging
37
+ `interoperability specifications <https://packaging.python.org/specifications/>`_.
38
+
39
+ This library provides utilities that implement the interoperability
40
+ specifications which have clearly one correct behaviour (eg: :pep:`440`)
41
+ or benefit greatly from having a single shared implementation (eg: :pep:`425`).
42
+
43
+ .. end-intro
44
+
45
+ The ``packaging`` project includes the following: version handling, specifiers,
46
+ markers, requirements, tags, metadata, lockfiles, utilities.
47
+
48
+ Documentation
49
+ -------------
50
+
51
+ The `documentation`_ provides information and the API for the following:
52
+
53
+ - Version Handling
54
+ - Specifiers
55
+ - Markers
56
+ - Licenses
57
+ - Requirements
58
+ - Metadata
59
+ - Tags
60
+ - Lockfiles (pylock)
61
+ - Direct URL helpers
62
+ - Dependency groups
63
+ - Errors
64
+ - Utilities
65
+
66
+ Installation
67
+ ------------
68
+
69
+ Use ``pip`` to install these utilities::
70
+
71
+ pip install packaging
72
+
73
+ The ``packaging`` library uses calendar-based versioning (``YY.N``).
74
+
75
+ Discussion
76
+ ----------
77
+
78
+ If you run into bugs, you can file them in our `issue tracker`_.
79
+
80
+ You can also join discussions on `GitHub Discussions`_ to ask questions or get involved.
81
+
82
+ .. _`documentation`: https://packaging.pypa.io/
83
+ .. _`issue tracker`: https://github.com/pypa/packaging/issues
84
+ .. _`GitHub Discussions`: https://github.com/pypa/packaging/discussions
85
+
86
+
87
+ Code of Conduct
88
+ ---------------
89
+
90
+ Everyone interacting in the packaging project's codebases, issue trackers, chat
91
+ rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_.
92
+
93
+ .. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md
94
+
95
+ Contributing
96
+ ------------
97
+
98
+ The ``CONTRIBUTING.rst`` file outlines how to contribute to this project as
99
+ well as how to report a potential security issue. The documentation for this
100
+ project also covers information about `project development`_ and `security`_.
101
+
102
+ .. _`project development`: https://packaging.pypa.io/en/latest/development/
103
+ .. _`security`: https://packaging.pypa.io/en/latest/security/
104
+
105
+ Project History
106
+ ---------------
107
+
108
+ Please review the ``CHANGELOG.rst`` file or the `Changelog documentation`_ for
109
+ recent changes and project history.
110
+
111
+ .. _`Changelog documentation`: https://packaging.pypa.io/en/latest/changelog/
112
+
data/diffusion/.venv/lib/python3.11/site-packages/packaging-26.2.dist-info/RECORD ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ packaging-26.2.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
2
+ packaging-26.2.dist-info/METADATA,sha256=T5y815M0FaR5P3dnyYoralEsgj_IHIczeBVwXyMOyr8,3543
3
+ packaging-26.2.dist-info/RECORD,,
4
+ packaging-26.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ packaging-26.2.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
6
+ packaging-26.2.dist-info/licenses/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197
7
+ packaging-26.2.dist-info/licenses/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174
8
+ packaging-26.2.dist-info/licenses/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344
9
+ packaging/__init__.py,sha256=QhMEdPu2XogrJzV3S0KWS6t7l0I9k8EeDRJl4fnw87s,494
10
+ packaging/_elffile.py,sha256=-sKkptYqzYw2-x3QByJa5mB4rfPWu1pxkZHRx1WAFCY,3211
11
+ packaging/_manylinux.py,sha256=Hf6nB0cOrayEs96-p3oIXAgGnFquv20DO5l-o2_Xnv0,9559
12
+ packaging/_musllinux.py,sha256=Z6swjH3MA7XS3qXnmMN7QPhqP3fnoYI0eQ18e9-HgAE,2707
13
+ packaging/_parser.py,sha256=Kf2nsDw4c54X82pY8ba4F02Bve6OygGMAjL-Begqcew,11698
14
+ packaging/_structures.py,sha256=60jRbF78p8z5MKnNd6cAprgOadCJHV0DlmUmRBqFZcs,1109
15
+ packaging/_tokenizer.py,sha256=tFU2Wr-ZZJdAbkXLEJo7qUQDJaIkfft9DqaifiEND7A,5391
16
+ packaging/dependency_groups.py,sha256=XZIAVFK9uHG4RCGprmJn3VInUWMesxha_kytJuMO9eY,10218
17
+ packaging/direct_url.py,sha256=eKmbDiPP1sLV4Mj_kCSZqqknrIyVO9Sr7JpF8KCjp4U,10917
18
+ packaging/errors.py,sha256=6hfEYXAf8v_IF65-lFadJOMIieBP2xIKtyEXjG1nGIs,2680
19
+ packaging/licenses/__init__.py,sha256=_Jx0XRiD_58palsWnyLrLuh59ZpGCPIPXLKdZo9OJvQ,7293
20
+ packaging/licenses/_spdx.py,sha256=WW7DXiyg68up_YND_wpRYlr1SHhiV4FfJLQffghhMxQ,51122
21
+ packaging/markers.py,sha256=8fDIUhAF6YMnCNB5FSiwh9pEIusiFzAF73J-0OB8bTk,17055
22
+ packaging/metadata.py,sha256=crAh0E3GVGVqPlu6EdRFsaG-Y6UYznTUqjuGKRGPv6c,38770
23
+ packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
24
+ packaging/pylock.py,sha256=G_1gncTmDbRLY1jo4VDI9Uw-b5IErh_Q9V_BbVJTmD8,33890
25
+ packaging/requirements.py,sha256=dd1c9aa1gp5NI6btF6UFRQjPn1nxQXnE_T34yDDTEpc,4383
26
+ packaging/specifiers.py,sha256=Mfp8avQg0lVot17to9lVKBtZD1FsWBTItoGwFUZ3wtg,71514
27
+ packaging/tags.py,sha256=NQ1weo69_Sjte3xBZ1I_G63CIgCmaN0C24mz-z3hGYo,34224
28
+ packaging/utils.py,sha256=M7-JMKic2sP1YtV_8aW7eVGB-x3ADuKCiSrsVeCd2Uo,9848
29
+ packaging/version.py,sha256=Y1aTtxe3sn2xOMa5BdI85-AcHuybbanOVkEvvSRRC8I,38369
data/diffusion/.venv/lib/python3.11/site-packages/packaging-26.2.dist-info/REQUESTED ADDED
File without changes
data/diffusion/.venv/lib/python3.11/site-packages/packaging-26.2.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: flit 3.12.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
data/diffusion/.venv/lib/python3.11/site-packages/requests/__init__.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # __
2
+ # /__) _ _ _ _ _/ _
3
+ # / ( (- (/ (/ (- _) / _)
4
+ # /
5
+
6
+ """
7
+ Requests HTTP Library
8
+ ~~~~~~~~~~~~~~~~~~~~~
9
+
10
+ Requests is an HTTP library, written in Python, for human beings.
11
+ Basic GET usage:
12
+
13
+ >>> import requests
14
+ >>> r = requests.get('https://www.python.org')
15
+ >>> r.status_code
16
+ 200
17
+ >>> b'Python is a programming language' in r.content
18
+ True
19
+
20
+ ... or POST:
21
+
22
+ >>> payload = dict(key1='value1', key2='value2')
23
+ >>> r = requests.post('https://httpbin.org/post', data=payload)
24
+ >>> print(r.text)
25
+ {
26
+ ...
27
+ "form": {
28
+ "key1": "value1",
29
+ "key2": "value2"
30
+ },
31
+ ...
32
+ }
33
+
34
+ The other HTTP methods are supported - see `requests.api`. Full documentation
35
+ is at <https://requests.readthedocs.io>.
36
+
37
+ :copyright: (c) 2017 by Kenneth Reitz.
38
+ :license: Apache 2.0, see LICENSE for more details.
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import warnings
44
+
45
+ import urllib3
46
+
47
+ from .exceptions import RequestsDependencyWarning
48
+
49
+ try:
50
+ from charset_normalizer import __version__ as charset_normalizer_version
51
+ except ImportError:
52
+ charset_normalizer_version = None
53
+
54
+ try:
55
+ from chardet import __version__ as chardet_version # type: ignore[import-not-found]
56
+ except ImportError:
57
+ chardet_version = None
58
+
59
+
60
+ def check_compatibility(
61
+ urllib3_version: str,
62
+ chardet_version: str | None,
63
+ charset_normalizer_version: str | None,
64
+ ) -> None:
65
+ urllib3_version_list = urllib3_version.split(".")[:3]
66
+ assert urllib3_version_list != ["dev"] # Verify urllib3 isn't installed from git.
67
+
68
+ # Sometimes, urllib3 only reports its version as 16.1.
69
+ if len(urllib3_version_list) == 2:
70
+ urllib3_version_list.append("0")
71
+
72
+ # Check urllib3 for compatibility.
73
+ major, minor, patch = urllib3_version_list # noqa: F811
74
+ major, minor, patch = int(major), int(minor), int(patch)
75
+ # urllib3 >= 1.21.1
76
+ assert major >= 1
77
+ if major == 1:
78
+ assert minor >= 21
79
+
80
+ # Check charset_normalizer for compatibility.
81
+ if chardet_version:
82
+ major, minor, patch = chardet_version.split(".")[:3]
83
+ major, minor, patch = int(major), int(minor), int(patch)
84
+ # chardet_version >= 3.0.2, < 8.0.0
85
+ assert (3, 0, 2) <= (major, minor, patch) < (8, 0, 0)
86
+ elif charset_normalizer_version:
87
+ major, minor, patch = charset_normalizer_version.split(".")[:3]
88
+ major, minor, patch = int(major), int(minor), int(patch)
89
+ # charset_normalizer >= 2.0.0 < 4.0.0
90
+ assert (2, 0, 0) <= (major, minor, patch) < (4, 0, 0)
91
+ else:
92
+ warnings.warn(
93
+ "Unable to find acceptable character detection dependency "
94
+ "(chardet or charset_normalizer).",
95
+ RequestsDependencyWarning,
96
+ )
97
+
98
+
99
+ def _check_cryptography(cryptography_version: str) -> None:
100
+ # cryptography < 1.3.4
101
+ try:
102
+ cryptography_version_list = list(map(int, cryptography_version.split(".")))
103
+ except ValueError:
104
+ return
105
+
106
+ if cryptography_version_list < [1, 3, 4]:
107
+ warning = f"Old version of cryptography ({cryptography_version_list}) may cause slowdown."
108
+ warnings.warn(warning, RequestsDependencyWarning)
109
+
110
+
111
+ # Check imported dependencies for compatibility.
112
+ try:
113
+ check_compatibility(
114
+ urllib3.__version__, # type: ignore[reportPrivateImportUsage]
115
+ chardet_version, # type: ignore[reportUnknownArgumentType]
116
+ charset_normalizer_version,
117
+ )
118
+ except (AssertionError, ValueError):
119
+ warnings.warn(
120
+ f"urllib3 ({urllib3.__version__}) or chardet " # type: ignore[reportPrivateImportUsage]
121
+ f"({chardet_version})/charset_normalizer ({charset_normalizer_version}) "
122
+ "doesn't match a supported version!",
123
+ RequestsDependencyWarning,
124
+ )
125
+
126
+ # Attempt to enable urllib3's fallback for SNI support
127
+ # if the standard library doesn't support SNI or the
128
+ # 'ssl' library isn't available.
129
+ try:
130
+ try:
131
+ import ssl
132
+ except ImportError:
133
+ ssl = None
134
+
135
+ if not getattr(ssl, "HAS_SNI", False):
136
+ from urllib3.contrib import pyopenssl
137
+
138
+ pyopenssl.inject_into_urllib3()
139
+
140
+ # Check cryptography version
141
+ from cryptography import ( # type: ignore[reportMissingImports]
142
+ __version__ as cryptography_version, # type: ignore[reportUnknownVariableType]
143
+ )
144
+
145
+ _check_cryptography(cryptography_version) # type: ignore[reportUnknownArgumentType]
146
+ except ImportError:
147
+ pass
148
+
149
+ # urllib3's DependencyWarnings should be silenced.
150
+ from urllib3.exceptions import DependencyWarning
151
+
152
+ warnings.simplefilter("ignore", DependencyWarning)
153
+
154
+ # Set default logging handler to avoid "No handler found" warnings.
155
+ import logging
156
+ from logging import NullHandler
157
+
158
+ from . import packages, utils
159
+ from .__version__ import (
160
+ __author__,
161
+ __author_email__,
162
+ __build__,
163
+ __cake__,
164
+ __copyright__,
165
+ __description__,
166
+ __license__,
167
+ __title__,
168
+ __url__,
169
+ __version__,
170
+ )
171
+ from .api import delete, get, head, options, patch, post, put, request
172
+ from .exceptions import (
173
+ ConnectionError,
174
+ ConnectTimeout,
175
+ FileModeWarning,
176
+ HTTPError,
177
+ JSONDecodeError,
178
+ ReadTimeout,
179
+ RequestException,
180
+ Timeout,
181
+ TooManyRedirects,
182
+ URLRequired,
183
+ )
184
+ from .models import PreparedRequest, Request, Response
185
+ from .sessions import Session, session
186
+ from .status_codes import codes
187
+
188
+ __all__ = (
189
+ "ConnectionError",
190
+ "ConnectTimeout",
191
+ "HTTPError",
192
+ "JSONDecodeError",
193
+ "PreparedRequest",
194
+ "ReadTimeout",
195
+ "Request",
196
+ "RequestException",
197
+ "Response",
198
+ "Session",
199
+ "Timeout",
200
+ "TooManyRedirects",
201
+ "URLRequired",
202
+ "codes",
203
+ "delete",
204
+ "get",
205
+ "head",
206
+ "options",
207
+ "packages",
208
+ "patch",
209
+ "post",
210
+ "put",
211
+ "request",
212
+ "session",
213
+ "utils",
214
+ )
215
+
216
+ logging.getLogger(__name__).addHandler(NullHandler())
217
+
218
+ # FileModeWarnings go off per the default.
219
+ warnings.simplefilter("default", FileModeWarning, append=True)
data/diffusion/.venv/lib/python3.11/site-packages/requests/__version__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # .-. .-. .-. . . .-. .-. .-. .-.
2
+ # |( |- |.| | | |- `-. | `-.
3
+ # ' ' `-' `-`.`-' `-' `-' ' `-'
4
+
5
+ __title__ = "requests"
6
+ __description__ = "Python HTTP for Humans."
7
+ __url__ = "https://requests.readthedocs.io"
8
+ __version__ = "2.34.2"
9
+ __build__ = 0x023402
10
+ __author__ = "Kenneth Reitz"
11
+ __author_email__ = "me@kennethreitz.org"
12
+ __license__ = "Apache-2.0"
13
+ __copyright__ = "Copyright Kenneth Reitz"
14
+ __cake__ = "\u2728 \U0001f370 \u2728"
data/diffusion/.venv/lib/python3.11/site-packages/requests/_internal_utils.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests._internal_utils
3
+ ~~~~~~~~~~~~~~
4
+
5
+ Provides utility functions that are consumed internally by Requests
6
+ which depend on extremely few external helpers (such as compat)
7
+ """
8
+
9
+ import re
10
+
11
+ from .compat import builtin_str
12
+
13
+ _VALID_HEADER_NAME_RE_BYTE = re.compile(rb"^[^:\s][^:\r\n]*\Z")
14
+ _VALID_HEADER_NAME_RE_STR = re.compile(r"^[^:\s][^:\r\n]*\Z")
15
+ _VALID_HEADER_VALUE_RE_BYTE = re.compile(rb"^\S[^\r\n]*\Z|^\Z")
16
+ _VALID_HEADER_VALUE_RE_STR = re.compile(r"^\S[^\r\n]*\Z|^\Z")
17
+
18
+ _HEADER_VALIDATORS_STR = (_VALID_HEADER_NAME_RE_STR, _VALID_HEADER_VALUE_RE_STR)
19
+ _HEADER_VALIDATORS_BYTE = (_VALID_HEADER_NAME_RE_BYTE, _VALID_HEADER_VALUE_RE_BYTE)
20
+ HEADER_VALIDATORS = {
21
+ bytes: _HEADER_VALIDATORS_BYTE,
22
+ str: _HEADER_VALIDATORS_STR,
23
+ }
24
+
25
+
26
+ def to_native_string(string: str | bytes, encoding: str = "ascii") -> str:
27
+ """Given a string object, regardless of type, returns a representation of
28
+ that string in the native string type, encoding and decoding where
29
+ necessary. This assumes ASCII unless told otherwise.
30
+ """
31
+ if isinstance(string, builtin_str):
32
+ out = string
33
+ else:
34
+ out = string.decode(encoding)
35
+
36
+ return out
37
+
38
+
39
+ def unicode_is_ascii(u_string: str) -> bool:
40
+ """Determine if unicode string only contains ASCII characters.
41
+
42
+ :param str u_string: unicode string to check. Must be unicode
43
+ and not Python 2 `str`.
44
+ :rtype: bool
45
+ """
46
+ assert isinstance(u_string, str)
47
+ try:
48
+ u_string.encode("ascii")
49
+ return True
50
+ except UnicodeEncodeError:
51
+ return False
data/diffusion/.venv/lib/python3.11/site-packages/requests/_types.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests._types
3
+ ~~~~~~~~~~~~~~~
4
+
5
+ This module contains type aliases used internally by the Requests library.
6
+ These types are not part of the public API and must not be relied upon
7
+ by external code.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence
13
+ from typing import (
14
+ TYPE_CHECKING,
15
+ Any,
16
+ Protocol,
17
+ TypeAlias,
18
+ TypeVar,
19
+ runtime_checkable,
20
+ )
21
+
22
+ _T_co = TypeVar("_T_co", covariant=True)
23
+ _KT_co = TypeVar("_KT_co", covariant=True)
24
+ _VT_co = TypeVar("_VT_co", covariant=True)
25
+
26
+
27
+ @runtime_checkable
28
+ class SupportsRead(Protocol[_T_co]):
29
+ def read(self, length: int = ..., /) -> _T_co: ...
30
+
31
+
32
+ @runtime_checkable
33
+ class SupportsItems(Protocol[_KT_co, _VT_co]):
34
+ def items(self) -> Iterable[tuple[_KT_co, _VT_co]]: ...
35
+
36
+
37
+ # These are needed at runtime for default_hooks() return type
38
+ HookType: TypeAlias = Callable[["Response"], Any]
39
+ HooksInputType: TypeAlias = Mapping[str, Iterable[HookType] | HookType]
40
+
41
+
42
+ def is_prepared(request: PreparedRequest) -> TypeIs[_ValidatedRequest]:
43
+ """Verify a PreparedRequest has been fully prepared."""
44
+ if TYPE_CHECKING:
45
+ return request.url is not None and request.method is not None
46
+ # noop at runtime to avoid AssertionError
47
+ return True
48
+
49
+
50
+ if TYPE_CHECKING:
51
+ from http.cookiejar import CookieJar
52
+ from typing import TypeAlias, TypedDict
53
+
54
+ from typing_extensions import (
55
+ Buffer, # TODO: move to collections.abc when Python >= 3.12
56
+ TypeIs, # TODO: move to typing when Python >= 3.13
57
+ )
58
+
59
+ from .auth import AuthBase
60
+ from .cookies import RequestsCookieJar
61
+ from .models import PreparedRequest, Response
62
+ from .structures import CaseInsensitiveDict
63
+
64
+ class _ValidatedRequest(PreparedRequest):
65
+ """Subtype asserting a PreparedRequest has been fully prepared before calling.
66
+
67
+ The override suppression is required because mutable attribute types are
68
+ invariant (Liskov), but we only narrow after preparation is complete. This
69
+ is the explicit contract for Requests but Python's typing doesn't have a
70
+ better way to represent the requirement.
71
+ """
72
+
73
+ url: str # type: ignore[reportIncompatibleVariableOverride]
74
+ method: str # type: ignore[reportIncompatibleVariableOverride]
75
+
76
+ # Type aliases for core API concepts (ordered by request() signature)
77
+ UriType: TypeAlias = str | bytes
78
+
79
+ _ParamsMappingKeyType: TypeAlias = str | bytes | int | float
80
+ _ParamsMappingValueType: TypeAlias = (
81
+ str | bytes | int | float | Iterable[str | bytes | int | float] | None
82
+ )
83
+ ParamsType: TypeAlias = (
84
+ SupportsItems[_ParamsMappingKeyType, _ParamsMappingValueType]
85
+ | tuple[tuple[_ParamsMappingKeyType, _ParamsMappingValueType], ...]
86
+ | Iterable[tuple[_ParamsMappingKeyType, _ParamsMappingValueType]]
87
+ | str
88
+ | bytes
89
+ | None
90
+ )
91
+
92
+ KVDataType: TypeAlias = Iterable[tuple[Any, Any]] | SupportsItems[Any, Any]
93
+
94
+ RawDataType: TypeAlias = KVDataType | str | bytes
95
+ StreamDataType: TypeAlias = SupportsRead[str | bytes]
96
+ EncodableDataType: TypeAlias = RawDataType | StreamDataType
97
+
98
+ DataType: TypeAlias = (
99
+ KVDataType
100
+ | Iterable[bytes | str]
101
+ | str
102
+ | bytes
103
+ | Buffer
104
+ | SupportsRead[str | bytes]
105
+ | None
106
+ )
107
+
108
+ BodyType: TypeAlias = (
109
+ bytes | str | Iterable[bytes | str] | SupportsRead[bytes | str] | None
110
+ )
111
+
112
+ HeadersType: TypeAlias = Mapping[str, str | bytes] | None
113
+
114
+ CookiesType: TypeAlias = RequestsCookieJar | Mapping[str, str]
115
+
116
+ # Building blocks for FilesType
117
+ _FileName: TypeAlias = str | None
118
+ _FileContent: TypeAlias = SupportsRead[str | bytes] | str | bytes
119
+ _FileSpecBasic: TypeAlias = tuple[_FileName, _FileContent]
120
+ _FileSpecWithContentType: TypeAlias = tuple[_FileName, _FileContent, str]
121
+ _FileSpecWithHeaders: TypeAlias = tuple[
122
+ _FileName, _FileContent, str, CaseInsensitiveDict[str] | Mapping[str, str]
123
+ ]
124
+ _FileSpec: TypeAlias = (
125
+ _FileContent | _FileSpecBasic | _FileSpecWithContentType | _FileSpecWithHeaders
126
+ )
127
+ FilesType: TypeAlias = (
128
+ Mapping[str, _FileSpec] | Iterable[tuple[str, _FileSpec]] | None
129
+ )
130
+
131
+ AuthType: TypeAlias = (
132
+ tuple[str, str] | AuthBase | Callable[[PreparedRequest], PreparedRequest] | None
133
+ )
134
+
135
+ TimeoutType: TypeAlias = float | tuple[float | None, float | None] | None
136
+ ProxiesType: TypeAlias = MutableMapping[str, str]
137
+ HooksType: TypeAlias = dict[str, list[HookType]] | None
138
+ VerifyType: TypeAlias = bool | str
139
+ CertType: TypeAlias = str | tuple[str, str] | None
140
+ JsonType: TypeAlias = (
141
+ None
142
+ | bool
143
+ | int
144
+ | float
145
+ | str
146
+ | Sequence["JsonType"]
147
+ | Mapping[str, "JsonType"]
148
+ )
149
+
150
+ # TypedDicts for Unpack kwargs (PEP 692)
151
+
152
+ class BaseRequestKwargs(TypedDict, total=False):
153
+ headers: HeadersType
154
+ cookies: RequestsCookieJar | CookieJar | dict[str, str] | None
155
+ files: FilesType
156
+ auth: AuthType
157
+ timeout: TimeoutType
158
+ allow_redirects: bool
159
+ proxies: dict[str, str] | None
160
+ hooks: HooksInputType | None
161
+ stream: bool | None
162
+ verify: VerifyType | None
163
+ cert: CertType
164
+
165
+ class RequestKwargs(BaseRequestKwargs, total=False):
166
+ """kwargs for request(), options(), head(), delete()."""
167
+
168
+ params: ParamsType
169
+ data: DataType
170
+ json: JsonType
171
+
172
+ class GetKwargs(BaseRequestKwargs, total=False):
173
+ data: DataType
174
+ json: JsonType
175
+
176
+ class PostKwargs(BaseRequestKwargs, total=False):
177
+ params: ParamsType
178
+
179
+ class DataKwargs(BaseRequestKwargs, total=False):
180
+ """kwargs for put(), patch()."""
181
+
182
+ params: ParamsType
183
+ json: JsonType
data/diffusion/.venv/lib/python3.11/site-packages/requests/adapters.py ADDED
@@ -0,0 +1,748 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.adapters
3
+ ~~~~~~~~~~~~~~~~~
4
+
5
+ This module contains the transport adapters that Requests uses to define
6
+ and maintain connections.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os.path
12
+ import socket # noqa: F401 # type: ignore[reportUnusedImport]
13
+ import typing
14
+ import warnings
15
+ from typing import Any
16
+
17
+ from urllib3.exceptions import (
18
+ ClosedPoolError,
19
+ ConnectTimeoutError,
20
+ LocationValueError,
21
+ MaxRetryError,
22
+ NewConnectionError,
23
+ ProtocolError,
24
+ ReadTimeoutError,
25
+ ResponseError,
26
+ )
27
+ from urllib3.exceptions import HTTPError as _HTTPError
28
+ from urllib3.exceptions import InvalidHeader as _InvalidHeader
29
+ from urllib3.exceptions import ProxyError as _ProxyError
30
+ from urllib3.exceptions import SSLError as _SSLError
31
+ from urllib3.poolmanager import PoolManager, proxy_from_url
32
+ from urllib3.util import Timeout as TimeoutSauce
33
+ from urllib3.util import parse_url
34
+ from urllib3.util.retry import Retry
35
+
36
+ from .auth import _basic_auth_str # type: ignore[reportPrivateUsage]
37
+ from .compat import basestring, urlparse
38
+ from .cookies import extract_cookies_to_jar
39
+ from .exceptions import (
40
+ ConnectionError,
41
+ ConnectTimeout,
42
+ InvalidHeader,
43
+ InvalidProxyURL,
44
+ InvalidSchema,
45
+ InvalidURL,
46
+ ProxyError,
47
+ ReadTimeout,
48
+ RetryError,
49
+ SSLError,
50
+ )
51
+ from .models import Response
52
+ from .structures import CaseInsensitiveDict
53
+ from .utils import (
54
+ DEFAULT_CA_BUNDLE_PATH,
55
+ get_auth_from_url,
56
+ get_encoding_from_headers,
57
+ prepend_scheme_if_needed,
58
+ select_proxy,
59
+ urldefragauth,
60
+ )
61
+
62
+ try:
63
+ from urllib3.contrib.socks import SOCKSProxyManager # type: ignore[assignment]
64
+ except ImportError:
65
+
66
+ def SOCKSProxyManager(*args: Any, **kwargs: Any) -> None:
67
+ raise InvalidSchema("Missing dependencies for SOCKS support.")
68
+
69
+
70
+ if typing.TYPE_CHECKING:
71
+ from urllib3.connectionpool import HTTPConnectionPool
72
+ from urllib3.poolmanager import PoolManager as _PoolManager
73
+
74
+ from . import _types as _t
75
+ from .models import PreparedRequest
76
+
77
+ from ._types import is_prepared as _is_prepared
78
+
79
+ DEFAULT_POOLBLOCK = False
80
+ DEFAULT_POOLSIZE = 10
81
+ DEFAULT_RETRIES = 0
82
+ DEFAULT_POOL_TIMEOUT = None
83
+
84
+
85
+ def _urllib3_request_context(
86
+ request: PreparedRequest,
87
+ verify: bool | str | None,
88
+ client_cert: tuple[str, str] | str | None,
89
+ poolmanager: PoolManager,
90
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
91
+ host_params: dict[str, Any] = {}
92
+ pool_kwargs: dict[str, Any] = {}
93
+ parsed_request_url = urlparse(request.url)
94
+ scheme = parsed_request_url.scheme.lower()
95
+ port = parsed_request_url.port
96
+
97
+ cert_reqs = "CERT_REQUIRED"
98
+ if verify is False:
99
+ cert_reqs = "CERT_NONE"
100
+ elif isinstance(verify, str):
101
+ if not os.path.isdir(verify):
102
+ pool_kwargs["ca_certs"] = verify
103
+ else:
104
+ pool_kwargs["ca_cert_dir"] = verify
105
+ pool_kwargs["cert_reqs"] = cert_reqs
106
+ if client_cert is not None:
107
+ if isinstance(client_cert, tuple) and len(client_cert) == 2:
108
+ pool_kwargs["cert_file"] = client_cert[0]
109
+ pool_kwargs["key_file"] = client_cert[1]
110
+ else:
111
+ # According to our docs, we allow users to specify just the client
112
+ # cert path
113
+ pool_kwargs["cert_file"] = client_cert
114
+ host_params = {
115
+ "scheme": scheme,
116
+ "host": parsed_request_url.hostname,
117
+ "port": port,
118
+ }
119
+ return host_params, pool_kwargs
120
+
121
+
122
+ class BaseAdapter:
123
+ """The Base Transport Adapter"""
124
+
125
+ def __init__(self) -> None:
126
+ super().__init__()
127
+
128
+ def send(
129
+ self,
130
+ request: PreparedRequest,
131
+ stream: bool = False,
132
+ timeout: _t.TimeoutType = None,
133
+ verify: _t.VerifyType = True,
134
+ cert: _t.CertType = None,
135
+ proxies: dict[str, str] | None = None,
136
+ ) -> Response:
137
+ """Sends PreparedRequest object. Returns Response object.
138
+
139
+ :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
140
+ :param stream: (optional) Whether to stream the request content.
141
+ :param timeout: (optional) How long to wait for the server to send
142
+ data before giving up, as a float, or a :ref:`(connect timeout,
143
+ read timeout) <timeouts>` tuple.
144
+ :type timeout: float or tuple
145
+ :param verify: (optional) Either a boolean, in which case it controls whether we verify
146
+ the server's TLS certificate, or a string, in which case it must be a path
147
+ to a CA bundle to use
148
+ :param cert: (optional) Any user-provided SSL certificate to be trusted.
149
+ :param proxies: (optional) The proxies dictionary to apply to the request.
150
+ """
151
+ raise NotImplementedError
152
+
153
+ def close(self) -> None:
154
+ """Cleans up adapter specific items."""
155
+ raise NotImplementedError
156
+
157
+
158
+ class HTTPAdapter(BaseAdapter):
159
+ """The built-in HTTP Adapter for urllib3.
160
+
161
+ Provides a general-case interface for Requests sessions to contact HTTP and
162
+ HTTPS urls by implementing the Transport Adapter interface. This class will
163
+ usually be created by the :class:`Session <Session>` class under the
164
+ covers.
165
+
166
+ :param pool_connections: The number of urllib3 connection pools to cache.
167
+ :param pool_maxsize: The maximum number of connections to save in the pool.
168
+ :param max_retries: The maximum number of retries each connection
169
+ should attempt. Note, this applies only to failed DNS lookups, socket
170
+ connections and connection timeouts, never to requests where data has
171
+ made it to the server. By default, Requests does not retry failed
172
+ connections. If you need granular control over the conditions under
173
+ which we retry a request, import urllib3's ``Retry`` class and pass
174
+ that instead.
175
+ :param pool_block: Whether the connection pool should block for connections.
176
+
177
+ Usage::
178
+
179
+ >>> import requests
180
+ >>> s = requests.Session()
181
+ >>> a = requests.adapters.HTTPAdapter(max_retries=3)
182
+ >>> s.mount('http://', a)
183
+ """
184
+
185
+ __attrs__: list[str] = [
186
+ "max_retries",
187
+ "config",
188
+ "_pool_connections",
189
+ "_pool_maxsize",
190
+ "_pool_block",
191
+ ]
192
+
193
+ max_retries: Retry
194
+ config: dict[str, Any]
195
+ proxy_manager: dict[str, Any]
196
+ _pool_connections: int
197
+ _pool_maxsize: int
198
+ _pool_block: bool
199
+ poolmanager: _PoolManager
200
+
201
+ def __init__(
202
+ self,
203
+ pool_connections: int = DEFAULT_POOLSIZE,
204
+ pool_maxsize: int = DEFAULT_POOLSIZE,
205
+ max_retries: int | Retry = DEFAULT_RETRIES,
206
+ pool_block: bool = DEFAULT_POOLBLOCK,
207
+ ) -> None:
208
+ if max_retries == DEFAULT_RETRIES:
209
+ self.max_retries = Retry(0, read=False)
210
+ else:
211
+ self.max_retries = Retry.from_int(max_retries)
212
+ self.config = {}
213
+ self.proxy_manager = {}
214
+
215
+ super().__init__()
216
+
217
+ self._pool_connections = pool_connections
218
+ self._pool_maxsize = pool_maxsize
219
+ self._pool_block = pool_block
220
+
221
+ self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)
222
+
223
+ def __getstate__(self) -> dict[str, Any]:
224
+ return {attr: getattr(self, attr, None) for attr in self.__attrs__}
225
+
226
+ def __setstate__(self, state: dict[str, Any]) -> None:
227
+ # Can't handle by adding 'proxy_manager' to self.__attrs__ because
228
+ # self.poolmanager uses a lambda function, which isn't pickleable.
229
+ self.proxy_manager = {}
230
+ self.config = {}
231
+
232
+ for attr, value in state.items():
233
+ setattr(self, attr, value)
234
+
235
+ self.init_poolmanager(
236
+ self._pool_connections, self._pool_maxsize, block=self._pool_block
237
+ )
238
+
239
+ def init_poolmanager(
240
+ self,
241
+ connections: int,
242
+ maxsize: int,
243
+ block: bool = DEFAULT_POOLBLOCK,
244
+ **pool_kwargs: Any,
245
+ ) -> None:
246
+ """Initializes a urllib3 PoolManager.
247
+
248
+ This method should not be called from user code, and is only
249
+ exposed for use when subclassing the
250
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
251
+
252
+ :param connections: The number of urllib3 connection pools to cache.
253
+ :param maxsize: The maximum number of connections to save in the pool.
254
+ :param block: Block when no free connections are available.
255
+ :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.
256
+ """
257
+ # save these values for pickling
258
+ self._pool_connections = connections
259
+ self._pool_maxsize = maxsize
260
+ self._pool_block = block
261
+
262
+ self.poolmanager = PoolManager(
263
+ num_pools=connections,
264
+ maxsize=maxsize,
265
+ block=block,
266
+ **pool_kwargs,
267
+ )
268
+
269
+ def proxy_manager_for(self, proxy: str, **proxy_kwargs: Any) -> Any:
270
+ """Return urllib3 ProxyManager for the given proxy.
271
+
272
+ This method should not be called from user code, and is only
273
+ exposed for use when subclassing the
274
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
275
+
276
+ :param proxy: The proxy to return a urllib3 ProxyManager for.
277
+ :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.
278
+ :returns: ProxyManager
279
+ :rtype: urllib3.ProxyManager
280
+ """
281
+ if proxy in self.proxy_manager:
282
+ manager = self.proxy_manager[proxy]
283
+ elif proxy.lower().startswith("socks"):
284
+ username, password = get_auth_from_url(proxy)
285
+ manager = self.proxy_manager[proxy] = SOCKSProxyManager(
286
+ proxy,
287
+ username=username,
288
+ password=password,
289
+ num_pools=self._pool_connections,
290
+ maxsize=self._pool_maxsize,
291
+ block=self._pool_block,
292
+ **proxy_kwargs,
293
+ )
294
+ else:
295
+ proxy_headers = self.proxy_headers(proxy)
296
+ manager = self.proxy_manager[proxy] = proxy_from_url(
297
+ proxy,
298
+ proxy_headers=proxy_headers,
299
+ num_pools=self._pool_connections,
300
+ maxsize=self._pool_maxsize,
301
+ block=self._pool_block,
302
+ **proxy_kwargs,
303
+ )
304
+
305
+ return manager
306
+
307
+ def cert_verify(
308
+ self, conn: Any, url: str, verify: _t.VerifyType, cert: _t.CertType
309
+ ) -> None:
310
+ """Verify a SSL certificate. This method should not be called from user
311
+ code, and is only exposed for use when subclassing the
312
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
313
+
314
+ :param conn: The urllib3 connection object associated with the cert.
315
+ :param url: The requested URL.
316
+ :param verify: Either a boolean, in which case it controls whether we verify
317
+ the server's TLS certificate, or a string, in which case it must be a path
318
+ to a CA bundle to use
319
+ :param cert: The SSL certificate to verify.
320
+ """
321
+ if url.lower().startswith("https") and verify:
322
+ cert_loc = None
323
+
324
+ # Allow self-specified cert location.
325
+ if verify is not True:
326
+ cert_loc = verify
327
+
328
+ if not cert_loc:
329
+ cert_loc = DEFAULT_CA_BUNDLE_PATH
330
+
331
+ if not cert_loc or not os.path.exists(cert_loc):
332
+ raise OSError(
333
+ f"Could not find a suitable TLS CA certificate bundle, "
334
+ f"invalid path: {cert_loc}"
335
+ )
336
+
337
+ conn.cert_reqs = "CERT_REQUIRED"
338
+
339
+ if not os.path.isdir(cert_loc):
340
+ conn.ca_certs = cert_loc
341
+ else:
342
+ conn.ca_cert_dir = cert_loc
343
+ else:
344
+ conn.cert_reqs = "CERT_NONE"
345
+ conn.ca_certs = None
346
+ conn.ca_cert_dir = None
347
+
348
+ if cert:
349
+ if not isinstance(cert, basestring):
350
+ conn.cert_file = cert[0]
351
+ conn.key_file = cert[1]
352
+ else:
353
+ conn.cert_file = cert
354
+ conn.key_file = None
355
+ if conn.cert_file and not os.path.exists(conn.cert_file):
356
+ raise OSError(
357
+ f"Could not find the TLS certificate file, "
358
+ f"invalid path: {conn.cert_file}"
359
+ )
360
+ if conn.key_file and not os.path.exists(conn.key_file):
361
+ raise OSError(
362
+ f"Could not find the TLS key file, invalid path: {conn.key_file}"
363
+ )
364
+
365
+ def build_response(self, req: PreparedRequest, resp: Any) -> Response:
366
+ """Builds a :class:`Response <requests.Response>` object from a urllib3
367
+ response. This should not be called from user code, and is only exposed
368
+ for use when subclassing the
369
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`
370
+
371
+ :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.
372
+ :param resp: The urllib3 response object.
373
+ :rtype: requests.Response
374
+ """
375
+ assert _is_prepared(req)
376
+ response = Response()
377
+
378
+ # Fallback to None if there's no status_code, for whatever reason.
379
+ response.status_code = getattr(resp, "status", None) # type: ignore[assignment]
380
+
381
+ # Make headers case-insensitive.
382
+ response.headers = CaseInsensitiveDict(getattr(resp, "headers", {}))
383
+
384
+ # Set encoding.
385
+ response.encoding = get_encoding_from_headers(response.headers)
386
+ response.raw = resp
387
+ response.reason = response.raw.reason
388
+
389
+ if isinstance(req.url, bytes):
390
+ response.url = req.url.decode("utf-8")
391
+ else:
392
+ response.url = req.url
393
+
394
+ # Add new cookies from the server.
395
+ extract_cookies_to_jar(response.cookies, req, resp)
396
+
397
+ # Give the Response some context.
398
+ response.request = req
399
+ response.connection = self
400
+
401
+ return response
402
+
403
+ def build_connection_pool_key_attributes(
404
+ self, request: PreparedRequest, verify: _t.VerifyType, cert: _t.CertType = None
405
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
406
+ """Build the PoolKey attributes used by urllib3 to return a connection.
407
+
408
+ This looks at the PreparedRequest, the user-specified verify value,
409
+ and the value of the cert parameter to determine what PoolKey values
410
+ to use to select a connection from a given urllib3 Connection Pool.
411
+
412
+ The SSL related pool key arguments are not consistently set. As of
413
+ this writing, use the following to determine what keys may be in that
414
+ dictionary:
415
+
416
+ * If ``verify`` is ``True``, ``"ssl_context"`` will be set and will be the
417
+ default Requests SSL Context
418
+ * If ``verify`` is ``False``, ``"ssl_context"`` will not be set but
419
+ ``"cert_reqs"`` will be set
420
+ * If ``verify`` is a string, (i.e., it is a user-specified trust bundle)
421
+ ``"ca_certs"`` will be set if the string is not a directory recognized
422
+ by :py:func:`os.path.isdir`, otherwise ``"ca_cert_dir"`` will be
423
+ set.
424
+ * If ``"cert"`` is specified, ``"cert_file"`` will always be set. If
425
+ ``"cert"`` is a tuple with a second item, ``"key_file"`` will also
426
+ be present
427
+
428
+ To override these settings, one may subclass this class, call this
429
+ method and use the above logic to change parameters as desired. For
430
+ example, if one wishes to use a custom :py:class:`ssl.SSLContext` one
431
+ must both set ``"ssl_context"`` and based on what else they require,
432
+ alter the other keys to ensure the desired behaviour.
433
+
434
+ :param request:
435
+ The PreparedRequest being sent over the connection.
436
+ :type request:
437
+ :class:`~requests.models.PreparedRequest`
438
+ :param verify:
439
+ Either a boolean, in which case it controls whether
440
+ we verify the server's TLS certificate, or a string, in which case it
441
+ must be a path to a CA bundle to use.
442
+ :param cert:
443
+ (optional) Any user-provided SSL certificate for client
444
+ authentication (a.k.a., mTLS). This may be a string (i.e., just
445
+ the path to a file which holds both certificate and key) or a
446
+ tuple of length 2 with the certificate file path and key file
447
+ path.
448
+ :returns:
449
+ A tuple of two dictionaries. The first is the "host parameters"
450
+ portion of the Pool Key including scheme, hostname, and port. The
451
+ second is a dictionary of SSLContext related parameters.
452
+ """
453
+ return _urllib3_request_context(request, verify, cert, self.poolmanager)
454
+
455
+ def get_connection_with_tls_context(
456
+ self,
457
+ request: PreparedRequest,
458
+ verify: _t.VerifyType,
459
+ proxies: dict[str, str] | None = None,
460
+ cert: _t.CertType = None,
461
+ ) -> HTTPConnectionPool:
462
+ """Returns a urllib3 connection for the given request and TLS settings.
463
+ This should not be called from user code, and is only exposed for use
464
+ when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
465
+
466
+ :param request:
467
+ The :class:`PreparedRequest <PreparedRequest>` object to be sent
468
+ over the connection.
469
+ :param verify:
470
+ Either a boolean, in which case it controls whether we verify the
471
+ server's TLS certificate, or a string, in which case it must be a
472
+ path to a CA bundle to use.
473
+ :param proxies:
474
+ (optional) The proxies dictionary to apply to the request.
475
+ :param cert:
476
+ (optional) Any user-provided SSL certificate to be used for client
477
+ authentication (a.k.a., mTLS).
478
+ :rtype:
479
+ urllib3.HTTPConnectionPool
480
+ """
481
+ assert _is_prepared(request)
482
+
483
+ proxy = select_proxy(request.url, proxies)
484
+ try:
485
+ host_params, pool_kwargs = self.build_connection_pool_key_attributes(
486
+ request,
487
+ verify,
488
+ cert,
489
+ )
490
+ except ValueError as e:
491
+ raise InvalidURL(e, request=request)
492
+ if proxy:
493
+ proxy = prepend_scheme_if_needed(proxy, "http")
494
+ proxy_url = parse_url(proxy)
495
+ if not proxy_url.host:
496
+ raise InvalidProxyURL(
497
+ "Please check proxy URL. It is malformed "
498
+ "and could be missing the host."
499
+ )
500
+ proxy_manager = self.proxy_manager_for(proxy)
501
+ conn = proxy_manager.connection_from_host(
502
+ **host_params, pool_kwargs=pool_kwargs
503
+ )
504
+ else:
505
+ # Only scheme should be lower case
506
+ conn = self.poolmanager.connection_from_host(
507
+ **host_params, pool_kwargs=pool_kwargs
508
+ )
509
+
510
+ return conn
511
+
512
+ def get_connection(
513
+ self, url: str, proxies: dict[str, str] | None = None
514
+ ) -> HTTPConnectionPool:
515
+ """DEPRECATED: Users should move to `get_connection_with_tls_context`
516
+ for all subclasses of HTTPAdapter using Requests>=2.32.2.
517
+
518
+ Returns a urllib3 connection for the given URL. This should not be
519
+ called from user code, and is only exposed for use when subclassing the
520
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
521
+
522
+ :param url: The URL to connect to.
523
+ :param proxies: (optional) A Requests-style dictionary of proxies used on this request.
524
+ :rtype: urllib3.HTTPConnectionPool
525
+ """
526
+ warnings.warn(
527
+ (
528
+ "`get_connection` has been deprecated in favor of "
529
+ "`get_connection_with_tls_context`. Custom HTTPAdapter subclasses "
530
+ "will need to migrate for Requests>=2.32.2. Please see "
531
+ "https://github.com/psf/requests/pull/6710 for more details."
532
+ ),
533
+ DeprecationWarning,
534
+ )
535
+ proxy = select_proxy(url, proxies)
536
+
537
+ if proxy:
538
+ proxy = prepend_scheme_if_needed(proxy, "http")
539
+ proxy_url = parse_url(proxy)
540
+ if not proxy_url.host:
541
+ raise InvalidProxyURL(
542
+ "Please check proxy URL. It is malformed "
543
+ "and could be missing the host."
544
+ )
545
+ proxy_manager = self.proxy_manager_for(proxy)
546
+ conn = proxy_manager.connection_from_url(url)
547
+ else:
548
+ # Only scheme should be lower case
549
+ parsed = urlparse(url)
550
+ url = parsed.geturl()
551
+ conn = self.poolmanager.connection_from_url(url)
552
+
553
+ return conn
554
+
555
+ def close(self) -> None:
556
+ """Disposes of any internal state.
557
+
558
+ Currently, this closes the PoolManager and any active ProxyManager,
559
+ which closes any pooled connections.
560
+ """
561
+ self.poolmanager.clear()
562
+ for proxy in self.proxy_manager.values():
563
+ proxy.clear()
564
+
565
+ def request_url(
566
+ self, request: PreparedRequest, proxies: dict[str, str] | None
567
+ ) -> str:
568
+ """Obtain the url to use when making the final request.
569
+
570
+ If the message is being sent through a HTTP proxy, the full URL has to
571
+ be used. Otherwise, we should only use the path portion of the URL.
572
+
573
+ This should not be called from user code, and is only exposed for use
574
+ when subclassing the
575
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
576
+
577
+ :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
578
+ :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.
579
+ :rtype: str
580
+ """
581
+ assert _is_prepared(request)
582
+
583
+ proxy = select_proxy(request.url, proxies)
584
+ scheme = urlparse(request.url).scheme
585
+
586
+ is_proxied_http_request = proxy and scheme != "https"
587
+ using_socks_proxy = False
588
+ if proxy:
589
+ proxy_scheme = urlparse(proxy).scheme.lower()
590
+ using_socks_proxy = proxy_scheme.startswith("socks")
591
+
592
+ url = request.path_url
593
+
594
+ if is_proxied_http_request and not using_socks_proxy:
595
+ url = urldefragauth(request.url)
596
+
597
+ return url
598
+
599
+ def add_headers(self, request: PreparedRequest, **kwargs: Any) -> None:
600
+ """Add any headers needed by the connection. As of v2.0 this does
601
+ nothing by default, but is left for overriding by users that subclass
602
+ the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
603
+
604
+ This should not be called from user code, and is only exposed for use
605
+ when subclassing the
606
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
607
+
608
+ :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.
609
+ :param kwargs: The keyword arguments from the call to send().
610
+ """
611
+ pass
612
+
613
+ def proxy_headers(self, proxy: str) -> dict[str, str]:
614
+ """Returns a dictionary of the headers to add to any request sent
615
+ through a proxy. This works with urllib3 magic to ensure that they are
616
+ correctly sent to the proxy, rather than in a tunnelled request if
617
+ CONNECT is being used.
618
+
619
+ This should not be called from user code, and is only exposed for use
620
+ when subclassing the
621
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
622
+
623
+ :param proxy: The url of the proxy being used for this request.
624
+ :rtype: dict
625
+ """
626
+ headers: dict[str, str] = {}
627
+ username, password = get_auth_from_url(proxy)
628
+
629
+ if username:
630
+ headers["Proxy-Authorization"] = _basic_auth_str(username, password)
631
+
632
+ return headers
633
+
634
+ def send(
635
+ self,
636
+ request: PreparedRequest,
637
+ stream: bool = False,
638
+ timeout: _t.TimeoutType = None,
639
+ verify: _t.VerifyType = True,
640
+ cert: _t.CertType = None,
641
+ proxies: dict[str, str] | None = None,
642
+ ) -> Response:
643
+ """Sends PreparedRequest object. Returns Response object.
644
+
645
+ :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
646
+ :param stream: (optional) Whether to stream the request content.
647
+ :param timeout: (optional) How long to wait for the server to send
648
+ data before giving up, as a float, or a :ref:`(connect timeout,
649
+ read timeout) <timeouts>` tuple.
650
+ :type timeout: float or tuple or urllib3 Timeout object
651
+ :param verify: (optional) Either a boolean, in which case it controls whether
652
+ we verify the server's TLS certificate, or a string, in which case it
653
+ must be a path to a CA bundle to use
654
+ :param cert: (optional) Any user-provided SSL certificate to be trusted.
655
+ :param proxies: (optional) The proxies dictionary to apply to the request.
656
+ :rtype: requests.Response
657
+ """
658
+
659
+ assert _is_prepared(request)
660
+
661
+ try:
662
+ conn = self.get_connection_with_tls_context(
663
+ request, verify, proxies=proxies, cert=cert
664
+ )
665
+ except LocationValueError as e:
666
+ raise InvalidURL(e, request=request)
667
+
668
+ self.cert_verify(conn, request.url, verify, cert)
669
+ url = self.request_url(request, proxies)
670
+ self.add_headers(
671
+ request,
672
+ stream=stream,
673
+ timeout=timeout,
674
+ verify=verify,
675
+ cert=cert,
676
+ proxies=proxies,
677
+ )
678
+
679
+ chunked = not (request.body is None or "Content-Length" in request.headers)
680
+
681
+ if isinstance(timeout, tuple):
682
+ try:
683
+ connect, read = timeout
684
+ resolved_timeout = TimeoutSauce(connect=connect, read=read)
685
+ except ValueError:
686
+ raise ValueError(
687
+ f"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, "
688
+ f"or a single float to set both timeouts to the same value."
689
+ )
690
+ elif isinstance(timeout, TimeoutSauce):
691
+ resolved_timeout = timeout
692
+ else:
693
+ resolved_timeout = TimeoutSauce(connect=timeout, read=timeout)
694
+
695
+ try:
696
+ resp = conn.urlopen(
697
+ method=request.method,
698
+ url=url,
699
+ body=request.body, # type: ignore[arg-type] # urllib3 stubs don't accept Iterable[bytes | str]
700
+ headers=request.headers, # type: ignore[arg-type] # urllib3#3072
701
+ redirect=False,
702
+ assert_same_host=False,
703
+ preload_content=False,
704
+ decode_content=False,
705
+ retries=self.max_retries,
706
+ timeout=resolved_timeout,
707
+ chunked=chunked,
708
+ )
709
+
710
+ except (ProtocolError, OSError) as err:
711
+ raise ConnectionError(err, request=request)
712
+
713
+ except MaxRetryError as e:
714
+ if isinstance(e.reason, ConnectTimeoutError):
715
+ # TODO: Remove this in 3.0.0: see #2811
716
+ if not isinstance(e.reason, NewConnectionError):
717
+ raise ConnectTimeout(e, request=request)
718
+
719
+ if isinstance(e.reason, ResponseError):
720
+ raise RetryError(e, request=request)
721
+
722
+ if isinstance(e.reason, _ProxyError):
723
+ raise ProxyError(e, request=request)
724
+
725
+ if isinstance(e.reason, _SSLError):
726
+ # This branch is for urllib3 v1.22 and later.
727
+ raise SSLError(e, request=request)
728
+
729
+ raise ConnectionError(e, request=request)
730
+
731
+ except ClosedPoolError as e:
732
+ raise ConnectionError(e, request=request)
733
+
734
+ except _ProxyError as e:
735
+ raise ProxyError(e)
736
+
737
+ except (_SSLError, _HTTPError) as e:
738
+ if isinstance(e, _SSLError):
739
+ # This branch is for urllib3 versions earlier than v1.22
740
+ raise SSLError(e, request=request)
741
+ elif isinstance(e, ReadTimeoutError):
742
+ raise ReadTimeout(e, request=request)
743
+ elif isinstance(e, _InvalidHeader):
744
+ raise InvalidHeader(e, request=request)
745
+ else:
746
+ raise
747
+
748
+ return self.build_response(request, resp)
data/diffusion/.venv/lib/python3.11/site-packages/requests/api.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.api
3
+ ~~~~~~~~~~~~
4
+
5
+ This module implements the Requests API.
6
+
7
+ :copyright: (c) 2012 by Kenneth Reitz.
8
+ :license: Apache2, see LICENSE for more details.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import TYPE_CHECKING
14
+
15
+ from . import sessions
16
+ from .models import Response
17
+
18
+ if TYPE_CHECKING:
19
+ from typing_extensions import Unpack
20
+
21
+ from . import _types as _t
22
+
23
+
24
+ def request(
25
+ method: str, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]
26
+ ) -> Response:
27
+ """Constructs and sends a :class:`Request <Request>`.
28
+
29
+ :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.
30
+ :param url: URL for the new :class:`Request` object.
31
+ :param params: (optional) Dictionary, list of tuples or bytes to send
32
+ in the query string for the :class:`Request`.
33
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
34
+ object to send in the body of the :class:`Request`.
35
+ :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
36
+ :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
37
+ :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
38
+ :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
39
+ ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
40
+ or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content_type'`` is a string
41
+ defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
42
+ to add for the file.
43
+ :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
44
+ :param timeout: (optional) How many seconds to wait for the server to send data
45
+ before giving up, as a float, or a :ref:`(connect timeout, read
46
+ timeout) <timeouts>` tuple.
47
+ :type timeout: float or tuple
48
+ :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.
49
+ :type allow_redirects: bool
50
+ :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
51
+ :param verify: (optional) Either a boolean, in which case it controls whether we verify
52
+ the server's TLS certificate, or a string, in which case it must be a path
53
+ to a CA bundle to use. Defaults to ``True``.
54
+ :param stream: (optional) if ``False``, the response content will be immediately downloaded.
55
+ :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
56
+ :return: :class:`Response <Response>` object
57
+ :rtype: requests.Response
58
+
59
+ Usage::
60
+
61
+ >>> import requests
62
+ >>> req = requests.request('GET', 'https://httpbin.org/get')
63
+ >>> req
64
+ <Response [200]>
65
+ """
66
+
67
+ # By using the 'with' statement we are sure the session is closed, thus we
68
+ # avoid leaving sockets open which can trigger a ResourceWarning in some
69
+ # cases, and look like a memory leak in others.
70
+ with sessions.Session() as session:
71
+ return session.request(method=method, url=url, **kwargs)
72
+
73
+
74
+ def get(
75
+ url: _t.UriType, params: _t.ParamsType = None, **kwargs: Unpack[_t.GetKwargs]
76
+ ) -> Response:
77
+ r"""Sends a GET request.
78
+
79
+ :param url: URL for the new :class:`Request` object.
80
+ :param params: (optional) Dictionary, list of tuples or bytes to send
81
+ in the query string for the :class:`Request`.
82
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
83
+ :return: :class:`Response <Response>` object
84
+ :rtype: requests.Response
85
+ """
86
+
87
+ return request("get", url, params=params, **kwargs)
88
+
89
+
90
+ def options(url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:
91
+ r"""Sends an OPTIONS request.
92
+
93
+ :param url: URL for the new :class:`Request` object.
94
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
95
+ :return: :class:`Response <Response>` object
96
+ :rtype: requests.Response
97
+ """
98
+
99
+ return request("options", url, **kwargs)
100
+
101
+
102
+ def head(url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:
103
+ r"""Sends a HEAD request.
104
+
105
+ :param url: URL for the new :class:`Request` object.
106
+ :param \*\*kwargs: Optional arguments that ``request`` takes. If
107
+ `allow_redirects` is not provided, it will be set to `False` (as
108
+ opposed to the default :meth:`request` behavior).
109
+ :return: :class:`Response <Response>` object
110
+ :rtype: requests.Response
111
+ """
112
+
113
+ kwargs.setdefault("allow_redirects", False)
114
+ return request("head", url, **kwargs)
115
+
116
+
117
+ def post(
118
+ url: _t.UriType,
119
+ data: _t.DataType = None,
120
+ json: _t.JsonType = None,
121
+ **kwargs: Unpack[_t.PostKwargs],
122
+ ) -> Response:
123
+ r"""Sends a POST request.
124
+
125
+ :param url: URL for the new :class:`Request` object.
126
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
127
+ object to send in the body of the :class:`Request`.
128
+ :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
129
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
130
+ :return: :class:`Response <Response>` object
131
+ :rtype: requests.Response
132
+ """
133
+
134
+ return request("post", url, data=data, json=json, **kwargs)
135
+
136
+
137
+ def put(
138
+ url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]
139
+ ) -> Response:
140
+ r"""Sends a PUT request.
141
+
142
+ :param url: URL for the new :class:`Request` object.
143
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
144
+ object to send in the body of the :class:`Request`.
145
+ :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
146
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
147
+ :return: :class:`Response <Response>` object
148
+ :rtype: requests.Response
149
+ """
150
+
151
+ return request("put", url, data=data, **kwargs)
152
+
153
+
154
+ def patch(
155
+ url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]
156
+ ) -> Response:
157
+ r"""Sends a PATCH request.
158
+
159
+ :param url: URL for the new :class:`Request` object.
160
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
161
+ object to send in the body of the :class:`Request`.
162
+ :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
163
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
164
+ :return: :class:`Response <Response>` object
165
+ :rtype: requests.Response
166
+ """
167
+
168
+ return request("patch", url, data=data, **kwargs)
169
+
170
+
171
+ def delete(url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:
172
+ r"""Sends a DELETE request.
173
+
174
+ :param url: URL for the new :class:`Request` object.
175
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
176
+ :return: :class:`Response <Response>` object
177
+ :rtype: requests.Response
178
+ """
179
+
180
+ return request("delete", url, **kwargs)
data/diffusion/.venv/lib/python3.11/site-packages/requests/auth.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.auth
3
+ ~~~~~~~~~~~~~
4
+
5
+ This module contains the authentication handlers for Requests.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import os
12
+ import re
13
+ import threading
14
+ import time
15
+ import warnings
16
+ from base64 import b64encode
17
+ from typing import TYPE_CHECKING, Any, Final, cast, overload
18
+
19
+ from ._internal_utils import to_native_string
20
+ from .compat import basestring, str, urlparse
21
+ from .cookies import extract_cookies_to_jar
22
+ from .utils import parse_dict_header
23
+
24
+ if TYPE_CHECKING:
25
+ from http.cookiejar import CookieJar
26
+ from typing import Any
27
+
28
+ from .models import PreparedRequest, Response
29
+
30
+ CONTENT_TYPE_FORM_URLENCODED: Final = "application/x-www-form-urlencoded"
31
+ CONTENT_TYPE_MULTI_PART: Final = "multipart/form-data"
32
+
33
+
34
+ def _basic_auth_str(username: bytes | str, password: bytes | str) -> str:
35
+ """Returns a Basic Auth string."""
36
+
37
+ # "I want us to put a big-ol' comment on top of it that
38
+ # says that this behaviour is dumb but we need to preserve
39
+ # it because people are relying on it."
40
+ # - Lukasa
41
+ #
42
+ # These are here solely to maintain backwards compatibility
43
+ # for things like ints. This will be removed in 3.0.0.
44
+ if not isinstance(username, basestring): # type: ignore[reportUnnecessaryIsInstance] # runtime guard for non-str/bytes
45
+ warnings.warn(
46
+ "Non-string usernames will no longer be supported in Requests "
47
+ f"3.0.0. Please convert the object you've passed in ({username!r}) to "
48
+ "a string or bytes object in the near future to avoid "
49
+ "problems.",
50
+ category=DeprecationWarning,
51
+ )
52
+ username = str(username)
53
+
54
+ if not isinstance(password, basestring): # type: ignore[reportUnnecessaryIsInstance] # runtime guard for non-str/bytes
55
+ warnings.warn(
56
+ "Non-string passwords will no longer be supported in Requests "
57
+ f"3.0.0. Please convert the object you've passed in ({type(password)!r}) to "
58
+ "a string or bytes object in the near future to avoid "
59
+ "problems.",
60
+ category=DeprecationWarning,
61
+ )
62
+ password = str(password)
63
+ # -- End Removal --
64
+
65
+ if isinstance(username, str):
66
+ username = username.encode("latin1")
67
+
68
+ if isinstance(password, str):
69
+ password = password.encode("latin1")
70
+
71
+ authstr = "Basic " + to_native_string(
72
+ b64encode(b":".join((username, password))).strip()
73
+ )
74
+
75
+ return authstr
76
+
77
+
78
+ class AuthBase:
79
+ """Base class that all auth implementations derive from"""
80
+
81
+ def __call__(self, r: PreparedRequest) -> PreparedRequest:
82
+ raise NotImplementedError("Auth hooks must be callable.")
83
+
84
+
85
+ class HTTPBasicAuth(AuthBase):
86
+ """Attaches HTTP Basic Authentication to the given Request object."""
87
+
88
+ username: bytes | str
89
+ password: bytes | str
90
+
91
+ @overload
92
+ def __init__(self, username: str, password: str) -> None: ...
93
+ @overload
94
+ def __init__(self, username: bytes, password: bytes) -> None: ...
95
+
96
+ def __init__(self, username: bytes | str, password: bytes | str) -> None:
97
+ self.username = username
98
+ self.password = password
99
+
100
+ def __eq__(self, other: object) -> bool:
101
+ return all(
102
+ [
103
+ self.username == getattr(other, "username", None),
104
+ self.password == getattr(other, "password", None),
105
+ ]
106
+ )
107
+
108
+ def __ne__(self, other: Any) -> bool:
109
+ return not self == other
110
+
111
+ def __call__(self, r: PreparedRequest) -> PreparedRequest:
112
+ r.headers["Authorization"] = _basic_auth_str(self.username, self.password)
113
+ return r
114
+
115
+
116
+ class HTTPProxyAuth(HTTPBasicAuth):
117
+ """Attaches HTTP Proxy Authentication to a given Request object."""
118
+
119
+ def __call__(self, r: PreparedRequest) -> PreparedRequest:
120
+ r.headers["Proxy-Authorization"] = _basic_auth_str(self.username, self.password)
121
+ return r
122
+
123
+
124
+ class HTTPDigestAuth(AuthBase):
125
+ """Attaches HTTP Digest Authentication to the given Request object."""
126
+
127
+ username: bytes | str
128
+ password: bytes | str
129
+ _thread_local: threading.local
130
+ last_nonce: str
131
+ nonce_count: int
132
+ chal: dict[str, str]
133
+ pos: int | None
134
+ num_401_calls: int | None
135
+
136
+ @overload
137
+ def __init__(self, username: str, password: str) -> None: ...
138
+ @overload
139
+ def __init__(self, username: bytes, password: bytes) -> None: ...
140
+
141
+ def __init__(self, username: bytes | str, password: bytes | str) -> None:
142
+ self.username = username
143
+ self.password = password
144
+ # Keep state in per-thread local storage
145
+ self._thread_local = threading.local()
146
+
147
+ def init_per_thread_state(self) -> None:
148
+ # Ensure state is initialized just once per-thread
149
+ if not hasattr(self._thread_local, "init"):
150
+ self._thread_local.init = True
151
+ self._thread_local.last_nonce = ""
152
+ self._thread_local.nonce_count = 0
153
+ self._thread_local.chal = {}
154
+ self._thread_local.pos = None
155
+ self._thread_local.num_401_calls = None
156
+
157
+ def build_digest_header(self, method: str, url: str) -> str | None:
158
+ """
159
+ :rtype: str
160
+ """
161
+
162
+ realm = self._thread_local.chal["realm"]
163
+ nonce = self._thread_local.chal["nonce"]
164
+ qop = self._thread_local.chal.get("qop")
165
+ algorithm = self._thread_local.chal.get("algorithm")
166
+ opaque = self._thread_local.chal.get("opaque")
167
+ hash_utf8 = None
168
+
169
+ if algorithm is None:
170
+ _algorithm = "MD5"
171
+ else:
172
+ _algorithm = algorithm.upper()
173
+ # lambdas assume digest modules are imported at the top level
174
+ if _algorithm == "MD5" or _algorithm == "MD5-SESS":
175
+
176
+ def md5_utf8(x: str | bytes) -> str:
177
+ if isinstance(x, str):
178
+ x = x.encode("utf-8")
179
+ return hashlib.md5(x, usedforsecurity=False).hexdigest()
180
+
181
+ hash_utf8 = md5_utf8
182
+ elif _algorithm == "SHA":
183
+
184
+ def sha_utf8(x: str | bytes) -> str:
185
+ if isinstance(x, str):
186
+ x = x.encode("utf-8")
187
+ return hashlib.sha1(x, usedforsecurity=False).hexdigest()
188
+
189
+ hash_utf8 = sha_utf8
190
+ elif _algorithm == "SHA-256":
191
+
192
+ def sha256_utf8(x: str | bytes) -> str:
193
+ if isinstance(x, str):
194
+ x = x.encode("utf-8")
195
+ return hashlib.sha256(x, usedforsecurity=False).hexdigest()
196
+
197
+ hash_utf8 = sha256_utf8
198
+ elif _algorithm == "SHA-512":
199
+
200
+ def sha512_utf8(x: str | bytes) -> str:
201
+ if isinstance(x, str):
202
+ x = x.encode("utf-8")
203
+ return hashlib.sha512(x, usedforsecurity=False).hexdigest()
204
+
205
+ hash_utf8 = sha512_utf8
206
+
207
+ if hash_utf8 is None:
208
+ return None
209
+
210
+ def KD(s: str, d: str) -> str:
211
+ return hash_utf8(f"{s}:{d}")
212
+
213
+ # XXX not implemented yet
214
+ entdig = None
215
+ p_parsed = urlparse(url)
216
+ #: path is request-uri defined in RFC 2616 which should not be empty
217
+ path = p_parsed.path or "/"
218
+ if p_parsed.query:
219
+ path += f"?{p_parsed.query}"
220
+
221
+ A1 = f"{self.username}:{realm}:{self.password}"
222
+ A2 = f"{method}:{path}"
223
+
224
+ HA1 = hash_utf8(A1)
225
+ HA2 = hash_utf8(A2)
226
+
227
+ if nonce == self._thread_local.last_nonce:
228
+ self._thread_local.nonce_count += 1
229
+ else:
230
+ self._thread_local.nonce_count = 1
231
+ ncvalue = f"{self._thread_local.nonce_count:08x}"
232
+ s = str(self._thread_local.nonce_count).encode("utf-8")
233
+ s += nonce.encode("utf-8")
234
+ s += time.ctime().encode("utf-8")
235
+ s += os.urandom(8)
236
+
237
+ cnonce = hashlib.sha1(s, usedforsecurity=False).hexdigest()[:16]
238
+ if _algorithm == "MD5-SESS":
239
+ HA1 = hash_utf8(f"{HA1}:{nonce}:{cnonce}") # type: ignore[reportConstantRedefinition] # RFC 2617 terminology
240
+
241
+ if not qop:
242
+ respdig = KD(HA1, f"{nonce}:{HA2}")
243
+ elif qop == "auth" or "auth" in qop.split(","):
244
+ noncebit = f"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}"
245
+ respdig = KD(HA1, noncebit)
246
+ else:
247
+ # XXX handle auth-int.
248
+ return None
249
+
250
+ self._thread_local.last_nonce = nonce
251
+
252
+ # XXX should the partial digests be encoded too?
253
+ base = (
254
+ f'username="{self.username}", realm="{realm}", nonce="{nonce}", '
255
+ f'uri="{path}", response="{respdig}"'
256
+ )
257
+ if opaque:
258
+ base += f', opaque="{opaque}"'
259
+ if algorithm:
260
+ base += f', algorithm="{algorithm}"'
261
+ if entdig:
262
+ base += f', digest="{entdig}"'
263
+ if qop:
264
+ base += f', qop="auth", nc={ncvalue}, cnonce="{cnonce}"'
265
+
266
+ return f"Digest {base}"
267
+
268
+ def handle_redirect(self, r: Response, **kwargs: Any) -> None:
269
+ """Reset num_401_calls counter on redirects."""
270
+ if r.is_redirect:
271
+ self._thread_local.num_401_calls = 1
272
+
273
+ def handle_401(self, r: Response, **kwargs: Any) -> Response:
274
+ """
275
+ Takes the given response and tries digest-auth, if needed.
276
+
277
+ :rtype: requests.Response
278
+ """
279
+
280
+ # If response is not 4xx, do not auth
281
+ # See https://github.com/psf/requests/issues/3772
282
+ if not 400 <= r.status_code < 500:
283
+ self._thread_local.num_401_calls = 1
284
+ return r
285
+
286
+ if self._thread_local.pos is not None:
287
+ # Rewind the file position indicator of the body to where
288
+ # it was to resend the request.
289
+ if (seek := getattr(r.request.body, "seek", None)) is not None:
290
+ seek(self._thread_local.pos)
291
+ s_auth = r.headers.get("www-authenticate", "")
292
+
293
+ if "digest" in s_auth.lower() and self._thread_local.num_401_calls < 2:
294
+ self._thread_local.num_401_calls += 1
295
+ pat = re.compile(r"digest ", flags=re.IGNORECASE)
296
+ self._thread_local.chal = parse_dict_header(pat.sub("", s_auth, count=1))
297
+
298
+ # Consume content and release the original connection
299
+ # to allow our new request to reuse the same one.
300
+ r.content
301
+ r.close()
302
+ prep = r.request.copy()
303
+ cookie_jar = cast("CookieJar", prep._cookies) # type: ignore[reportPrivateUsage]
304
+ extract_cookies_to_jar(cookie_jar, r.request, r.raw)
305
+ prep.prepare_cookies(cookie_jar)
306
+
307
+ _digest_auth = self.build_digest_header(
308
+ cast(str, prep.method), cast(str, prep.url)
309
+ )
310
+ if _digest_auth:
311
+ prep.headers["Authorization"] = _digest_auth
312
+ _r = r.connection.send(prep, **kwargs)
313
+ _r.history.append(r)
314
+ _r.request = prep
315
+
316
+ return _r
317
+
318
+ self._thread_local.num_401_calls = 1
319
+ return r
320
+
321
+ def __call__(self, r: PreparedRequest) -> PreparedRequest:
322
+ # Initialize per-thread state, if needed
323
+ self.init_per_thread_state()
324
+ # If we have a saved nonce, skip the 401
325
+ if self._thread_local.last_nonce:
326
+ _digest_auth = self.build_digest_header(
327
+ cast(str, r.method), cast(str, r.url)
328
+ )
329
+ if _digest_auth:
330
+ r.headers["Authorization"] = _digest_auth
331
+ if (tell := getattr(r.body, "tell", None)) is not None:
332
+ self._thread_local.pos = tell()
333
+ else:
334
+ # In the case of HTTPDigestAuth being reused and the body of
335
+ # the previous request was a file-like object, pos has the
336
+ # file position of the previous body. Ensure it's set to
337
+ # None.
338
+ self._thread_local.pos = None
339
+ r.register_hook("response", self.handle_401)
340
+ r.register_hook("response", self.handle_redirect)
341
+ self._thread_local.num_401_calls = 1
342
+
343
+ return r
344
+
345
+ def __eq__(self, other: object) -> bool:
346
+ return all(
347
+ [
348
+ self.username == getattr(other, "username", None),
349
+ self.password == getattr(other, "password", None),
350
+ ]
351
+ )
352
+
353
+ def __ne__(self, other: Any) -> bool:
354
+ return not self == other
data/diffusion/.venv/lib/python3.11/site-packages/requests/certs.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ """
4
+ requests.certs
5
+ ~~~~~~~~~~~~~~
6
+
7
+ This module returns the preferred default CA certificate bundle. There is
8
+ only one — the one from the certifi package.
9
+
10
+ If you are packaging Requests, e.g., for a Linux distribution or a managed
11
+ environment, you can change the definition of where() to return a separately
12
+ packaged CA bundle.
13
+ """
14
+
15
+ from certifi import where
16
+
17
+ if __name__ == "__main__":
18
+ print(where())
data/diffusion/.venv/lib/python3.11/site-packages/requests/compat.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.compat
3
+ ~~~~~~~~~~~~~~~
4
+
5
+ This module previously handled import compatibility issues
6
+ between Python 2 and Python 3. It remains for backwards
7
+ compatibility until the next major version.
8
+ """
9
+
10
+ # pyright: reportUnusedImport=false
11
+
12
+ from __future__ import annotations
13
+
14
+ import importlib
15
+ import sys
16
+ from types import ModuleType
17
+
18
+ # -------
19
+ # urllib3
20
+ # -------
21
+ from urllib3 import (
22
+ __version__ as urllib3_version, # type: ignore[reportPrivateImportUsage]
23
+ )
24
+
25
+ # Detect which major version of urllib3 is being used.
26
+ try:
27
+ is_urllib3_1 = int(urllib3_version.split(".")[0]) == 1
28
+ except (TypeError, AttributeError):
29
+ # If we can't discern a version, prefer old functionality.
30
+ is_urllib3_1 = True
31
+
32
+ # -------------------
33
+ # Character Detection
34
+ # -------------------
35
+
36
+
37
+ def _resolve_char_detection() -> ModuleType | None:
38
+ """Find supported character detection libraries."""
39
+ chardet = None
40
+ for lib in ("chardet", "charset_normalizer"):
41
+ if chardet is None:
42
+ try:
43
+ chardet = importlib.import_module(lib)
44
+ except ImportError:
45
+ pass
46
+ return chardet
47
+
48
+
49
+ chardet = _resolve_char_detection()
50
+
51
+ # -------
52
+ # Pythons
53
+ # -------
54
+
55
+ # Syntax sugar.
56
+ _ver = sys.version_info
57
+
58
+ #: Python 2.x?
59
+ is_py2 = _ver[0] == 2
60
+
61
+ #: Python 3.x?
62
+ is_py3 = _ver[0] == 3
63
+
64
+ # json/simplejson module import resolution
65
+ has_simplejson = False
66
+ try:
67
+ import simplejson as json # type: ignore[import-not-found]
68
+
69
+ has_simplejson = True
70
+ except ImportError:
71
+ import json
72
+
73
+ if has_simplejson:
74
+ from simplejson import JSONDecodeError # type: ignore[import-not-found]
75
+ else:
76
+ from json import JSONDecodeError
77
+
78
+ # Keep OrderedDict for backwards compatibility.
79
+ from collections import OrderedDict
80
+ from collections.abc import Callable, Mapping, MutableMapping
81
+ from http import cookiejar as cookielib
82
+ from http.cookies import Morsel
83
+ from io import StringIO
84
+
85
+ # --------------
86
+ # Legacy Imports
87
+ # --------------
88
+ from urllib.parse import (
89
+ quote,
90
+ quote_plus,
91
+ unquote,
92
+ unquote_plus,
93
+ urldefrag,
94
+ urlencode,
95
+ urljoin,
96
+ urlparse,
97
+ urlsplit,
98
+ urlunparse,
99
+ )
100
+ from urllib.request import (
101
+ getproxies,
102
+ getproxies_environment,
103
+ parse_http_list,
104
+ proxy_bypass,
105
+ proxy_bypass_environment, # type: ignore[attr-defined] # https://github.com/python/cpython/issues/145331
106
+ )
107
+
108
+ builtin_str = str
109
+ str = str
110
+ bytes = bytes
111
+ basestring = (str, bytes)
112
+ numeric_types = (int, float)
113
+ integer_types = (int,)
data/diffusion/.venv/lib/python3.11/site-packages/requests/cookies.py ADDED
@@ -0,0 +1,625 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.cookies
3
+ ~~~~~~~~~~~~~~~~
4
+
5
+ Compatibility code to be able to use `http.cookiejar.CookieJar` with requests.
6
+
7
+ requests.utils imports from here, so be careful with imports.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import calendar
13
+ import copy
14
+ import time
15
+ from collections.abc import Iterator, MutableMapping
16
+ from http.cookiejar import Cookie, CookieJar, CookiePolicy
17
+ from typing import TYPE_CHECKING, Any, TypeVar, overload
18
+
19
+ from ._internal_utils import to_native_string
20
+ from ._types import is_prepared as _is_prepared
21
+ from .compat import Morsel, cookielib, urlparse, urlunparse
22
+
23
+ if TYPE_CHECKING:
24
+ from _typeshed import SupportsKeysAndGetItem
25
+
26
+ from .models import PreparedRequest
27
+
28
+ import threading
29
+
30
+
31
+ class MockRequest:
32
+ """Wraps a `requests.PreparedRequest` to mimic a `urllib2.Request`.
33
+
34
+ The code in `http.cookiejar.CookieJar` expects this interface in order to correctly
35
+ manage cookie policies, i.e., determine whether a cookie can be set, given the
36
+ domains of the request and the cookie.
37
+
38
+ The original request object is read-only. The client is responsible for collecting
39
+ the new headers via `get_new_headers()` and interpreting them appropriately. You
40
+ probably want `get_cookie_header`, defined below.
41
+ """
42
+
43
+ type: str
44
+
45
+ def __init__(self, request: PreparedRequest) -> None:
46
+ assert _is_prepared(request)
47
+ self._r = request
48
+ self._new_headers: dict[str, str] = {}
49
+ self.type = urlparse(self._r.url).scheme
50
+
51
+ def get_type(self) -> str:
52
+ return self.type
53
+
54
+ def get_host(self) -> str:
55
+ return urlparse(self._r.url).netloc
56
+
57
+ def get_origin_req_host(self) -> str:
58
+ return self.get_host()
59
+
60
+ def get_full_url(self) -> str:
61
+ # Only return the response's URL if the user hadn't set the Host
62
+ # header
63
+ if not self._r.headers.get("Host"):
64
+ return self._r.url
65
+ # If they did set it, retrieve it and reconstruct the expected domain
66
+ host = to_native_string(self._r.headers["Host"], encoding="utf-8")
67
+ parsed = urlparse(self._r.url)
68
+ # Reconstruct the URL as we expect it
69
+ return urlunparse(
70
+ [
71
+ parsed.scheme,
72
+ host,
73
+ parsed.path,
74
+ parsed.params,
75
+ parsed.query,
76
+ parsed.fragment,
77
+ ]
78
+ )
79
+
80
+ def is_unverifiable(self) -> bool:
81
+ return True
82
+
83
+ def has_header(self, name: str) -> bool:
84
+ return name in self._r.headers or name in self._new_headers
85
+
86
+ def get_header(self, name: str, default: str | None = None) -> str | None:
87
+ return self._r.headers.get(name, self._new_headers.get(name, default)) # type: ignore[return-value]
88
+
89
+ def add_header(self, key: str, val: str) -> None:
90
+ """cookiejar has no legitimate use for this method; add it back if you find one."""
91
+ raise NotImplementedError(
92
+ "Cookie headers should be added with add_unredirected_header()"
93
+ )
94
+
95
+ def add_unredirected_header(self, name: str, value: str) -> None:
96
+ self._new_headers[name] = value
97
+
98
+ def get_new_headers(self) -> dict[str, str]:
99
+ return self._new_headers
100
+
101
+ @property
102
+ def unverifiable(self) -> bool:
103
+ return self.is_unverifiable()
104
+
105
+ @property
106
+ def origin_req_host(self) -> str:
107
+ return self.get_origin_req_host()
108
+
109
+ @property
110
+ def host(self) -> str:
111
+ return self.get_host()
112
+
113
+
114
+ class MockResponse:
115
+ """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.
116
+
117
+ ...what? Basically, expose the parsed HTTP headers from the server response
118
+ the way `http.cookiejar` expects to see them.
119
+ """
120
+
121
+ def __init__(self, headers: Any) -> None:
122
+ """Make a MockResponse for `cookiejar` to read.
123
+
124
+ :param headers: a httplib.HTTPMessage or analogous carrying the headers
125
+ """
126
+ self._headers = headers
127
+
128
+ def info(self) -> Any:
129
+ return self._headers
130
+
131
+ def getheaders(self, name: str) -> Any:
132
+ self._headers.getheaders(name)
133
+
134
+
135
+ def extract_cookies_to_jar(
136
+ jar: CookieJar, request: PreparedRequest, response: Any
137
+ ) -> None:
138
+ """Extract the cookies from the response into a CookieJar.
139
+
140
+ :param jar: http.cookiejar.CookieJar (not necessarily a RequestsCookieJar)
141
+ :param request: our own requests.Request object
142
+ :param response: urllib3.HTTPResponse object
143
+ """
144
+ if not (hasattr(response, "_original_response") and response._original_response):
145
+ return
146
+ # the _original_response field is the wrapped httplib.HTTPResponse object,
147
+ req = MockRequest(request)
148
+ # pull out the HTTPMessage with the headers and put it in the mock:
149
+ res = MockResponse(response._original_response.msg)
150
+ jar.extract_cookies(res, req) # type: ignore[arg-type]
151
+
152
+
153
+ def get_cookie_header(jar: CookieJar, request: PreparedRequest) -> str | None:
154
+ """
155
+ Produce an appropriate Cookie header string to be sent with `request`, or None.
156
+
157
+ :rtype: str
158
+ """
159
+ r = MockRequest(request)
160
+ jar.add_cookie_header(r) # type: ignore[arg-type]
161
+ return r.get_new_headers().get("Cookie")
162
+
163
+
164
+ def remove_cookie_by_name(
165
+ cookiejar: CookieJar, name: str, domain: str | None = None, path: str | None = None
166
+ ) -> None:
167
+ """Unsets a cookie by name, by default over all domains and paths.
168
+
169
+ Wraps CookieJar.clear(), is O(n).
170
+ """
171
+ clearables: list[tuple[str, str, str]] = []
172
+ for cookie in cookiejar:
173
+ if cookie.name != name:
174
+ continue
175
+ if domain is not None and domain != cookie.domain:
176
+ continue
177
+ if path is not None and path != cookie.path:
178
+ continue
179
+ clearables.append((cookie.domain, cookie.path, cookie.name))
180
+
181
+ for domain, path, name in clearables:
182
+ cookiejar.clear(domain, path, name)
183
+
184
+
185
+ class CookieConflictError(RuntimeError):
186
+ """There are two cookies that meet the criteria specified in the cookie jar.
187
+ Use .get and .set and include domain and path args in order to be more specific.
188
+ """
189
+
190
+
191
+ class RequestsCookieJar(CookieJar, MutableMapping[str, str | None]): # type: ignore[misc]
192
+ """Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict
193
+ interface.
194
+
195
+ This is the CookieJar we create by default for requests and sessions that
196
+ don't specify one, since some clients may expect response.cookies and
197
+ session.cookies to support dict operations.
198
+
199
+ Requests does not use the dict interface internally; it's just for
200
+ compatibility with external client code. All requests code should work
201
+ out of the box with externally provided instances of ``CookieJar``, e.g.
202
+ ``LWPCookieJar`` and ``FileCookieJar``.
203
+
204
+ Unlike a regular CookieJar, this class is pickleable.
205
+
206
+ .. warning:: dictionary operations that are normally O(1) may be O(n).
207
+ """
208
+
209
+ _policy: CookiePolicy
210
+
211
+ def get( # type: ignore[override]
212
+ self,
213
+ name: str,
214
+ default: str | None = None,
215
+ domain: str | None = None,
216
+ path: str | None = None,
217
+ ) -> str | None:
218
+ """Dict-like get() that also supports optional domain and path args in
219
+ order to resolve naming collisions from using one cookie jar over
220
+ multiple domains.
221
+
222
+ .. warning:: operation is O(n), not O(1).
223
+ """
224
+ try:
225
+ return self._find_no_duplicates(name, domain, path)
226
+ except KeyError:
227
+ return default
228
+
229
+ def set(
230
+ self, name: str, value: str | Morsel[dict[str, str]] | None, **kwargs: Any
231
+ ) -> Cookie | None:
232
+ """Dict-like set() that also supports optional domain and path args in
233
+ order to resolve naming collisions from using one cookie jar over
234
+ multiple domains.
235
+ """
236
+ # support client code that unsets cookies by assignment of a None value:
237
+ if value is None:
238
+ remove_cookie_by_name(
239
+ self, name, domain=kwargs.get("domain"), path=kwargs.get("path")
240
+ )
241
+ return
242
+
243
+ if isinstance(value, Morsel):
244
+ c = morsel_to_cookie(value)
245
+ else:
246
+ c = create_cookie(name, value, **kwargs)
247
+ self.set_cookie(c)
248
+ return c
249
+
250
+ def iterkeys(self) -> Iterator[str]:
251
+ """Dict-like iterkeys() that returns an iterator of names of cookies
252
+ from the jar.
253
+
254
+ .. seealso:: itervalues() and iteritems().
255
+ """
256
+ for cookie in iter(self):
257
+ yield cookie.name
258
+
259
+ def keys(self) -> list[str]: # type: ignore[override]
260
+ """Dict-like keys() that returns a list of names of cookies from the
261
+ jar.
262
+
263
+ .. seealso:: values() and items().
264
+ """
265
+ return list(self.iterkeys())
266
+
267
+ def itervalues(self) -> Iterator[str | None]:
268
+ """Dict-like itervalues() that returns an iterator of values of cookies
269
+ from the jar.
270
+
271
+ .. seealso:: iterkeys() and iteritems().
272
+ """
273
+ for cookie in iter(self):
274
+ yield cookie.value
275
+
276
+ def values(self) -> list[str | None]: # type: ignore[override]
277
+ """Dict-like values() that returns a list of values of cookies from the
278
+ jar.
279
+
280
+ .. seealso:: keys() and items().
281
+ """
282
+ return list(self.itervalues())
283
+
284
+ def iteritems(self) -> Iterator[tuple[str, str | None]]:
285
+ """Dict-like iteritems() that returns an iterator of name-value tuples
286
+ from the jar.
287
+
288
+ .. seealso:: iterkeys() and itervalues().
289
+ """
290
+ for cookie in iter(self):
291
+ yield cookie.name, cookie.value
292
+
293
+ def items(self) -> list[tuple[str, str | None]]: # type: ignore[override]
294
+ """Dict-like items() that returns a list of name-value tuples from the
295
+ jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a
296
+ vanilla python dict of key value pairs.
297
+
298
+ .. seealso:: keys() and values().
299
+ """
300
+ return list(self.iteritems())
301
+
302
+ def list_domains(self) -> list[str]:
303
+ """Utility method to list all the domains in the jar."""
304
+ domains: list[str] = []
305
+ for cookie in iter(self):
306
+ if cookie.domain not in domains:
307
+ domains.append(cookie.domain)
308
+ return domains
309
+
310
+ def list_paths(self) -> list[str]:
311
+ """Utility method to list all the paths in the jar."""
312
+ paths: list[str] = []
313
+ for cookie in iter(self):
314
+ if cookie.path not in paths:
315
+ paths.append(cookie.path)
316
+ return paths
317
+
318
+ def multiple_domains(self) -> bool:
319
+ """Returns True if there are multiple domains in the jar.
320
+ Returns False otherwise.
321
+
322
+ :rtype: bool
323
+ """
324
+ domains: list[str] = []
325
+ for cookie in iter(self):
326
+ if cookie.domain is not None and cookie.domain in domains: # type: ignore[reportUnnecessaryComparison] # defensive check
327
+ return True
328
+ domains.append(cookie.domain)
329
+ return False # there is only one domain in jar
330
+
331
+ def get_dict(
332
+ self, domain: str | None = None, path: str | None = None
333
+ ) -> dict[str, str | None]:
334
+ """Takes as an argument an optional domain and path and returns a plain
335
+ old Python dict of name-value pairs of cookies that meet the
336
+ requirements.
337
+
338
+ :rtype: dict
339
+ """
340
+ dictionary: dict[str, str | None] = {}
341
+ for cookie in iter(self):
342
+ if (domain is None or cookie.domain == domain) and (
343
+ path is None or cookie.path == path
344
+ ):
345
+ dictionary[cookie.name] = cookie.value
346
+ return dictionary
347
+
348
+ def __iter__(self) -> Iterator[Cookie]: # type: ignore[override]
349
+ """RequestCookieJar's __iter__ comes from CookieJar not MutableMapping."""
350
+ return super().__iter__()
351
+
352
+ def __contains__(self, name: object) -> bool:
353
+ try:
354
+ return super().__contains__(name)
355
+ except CookieConflictError:
356
+ return True
357
+
358
+ def __getitem__(self, name: str) -> str | None:
359
+ """Dict-like __getitem__() for compatibility with client code. Throws
360
+ exception if there are more than one cookie with name. In that case,
361
+ use the more explicit get() method instead.
362
+
363
+ .. warning:: operation is O(n), not O(1).
364
+ """
365
+ return self._find_no_duplicates(name)
366
+
367
+ def __setitem__(
368
+ self, name: str, value: str | Morsel[dict[str, str]] | None
369
+ ) -> None:
370
+ """Dict-like __setitem__ for compatibility with client code. Throws
371
+ exception if there is already a cookie of that name in the jar. In that
372
+ case, use the more explicit set() method instead.
373
+ """
374
+ self.set(name, value)
375
+
376
+ def __delitem__(self, name: str) -> None:
377
+ """Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s
378
+ ``remove_cookie_by_name()``.
379
+ """
380
+ remove_cookie_by_name(self, name)
381
+
382
+ def set_cookie(self, cookie: Cookie, *args: Any, **kwargs: Any) -> None:
383
+ if (
384
+ (value := cookie.value) is not None
385
+ and value.startswith('"')
386
+ and value.endswith('"')
387
+ ):
388
+ cookie.value = value.replace('\\"', "")
389
+ return super().set_cookie(cookie, *args, **kwargs)
390
+
391
+ def update( # type: ignore[override]
392
+ self, other: CookieJar | SupportsKeysAndGetItem[str, str]
393
+ ) -> None:
394
+ """Updates this jar with cookies from another CookieJar or dict-like"""
395
+ if isinstance(other, cookielib.CookieJar):
396
+ for cookie in other:
397
+ self.set_cookie(copy.copy(cookie))
398
+ else:
399
+ super().update(other)
400
+
401
+ def _find(
402
+ self, name: str, domain: str | None = None, path: str | None = None
403
+ ) -> str | None:
404
+ """Requests uses this method internally to get cookie values.
405
+
406
+ If there are conflicting cookies, _find arbitrarily chooses one.
407
+ See _find_no_duplicates if you want an exception thrown if there are
408
+ conflicting cookies.
409
+
410
+ :param name: a string containing name of cookie
411
+ :param domain: (optional) string containing domain of cookie
412
+ :param path: (optional) string containing path of cookie
413
+ :return: cookie.value
414
+ """
415
+ for cookie in iter(self):
416
+ if cookie.name == name:
417
+ if domain is None or cookie.domain == domain:
418
+ if path is None or cookie.path == path:
419
+ return cookie.value
420
+
421
+ raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")
422
+
423
+ def _find_no_duplicates(
424
+ self, name: str, domain: str | None = None, path: str | None = None
425
+ ) -> str:
426
+ """Both ``__get_item__`` and ``get`` call this function: it's never
427
+ used elsewhere in Requests.
428
+
429
+ :param name: a string containing name of cookie
430
+ :param domain: (optional) string containing domain of cookie
431
+ :param path: (optional) string containing path of cookie
432
+ :raises KeyError: if cookie is not found
433
+ :raises CookieConflictError: if there are multiple cookies
434
+ that match name and optionally domain and path
435
+ :return: cookie.value
436
+ """
437
+ toReturn = None
438
+ for cookie in iter(self):
439
+ if cookie.name == name:
440
+ if domain is None or cookie.domain == domain:
441
+ if path is None or cookie.path == path:
442
+ if toReturn is not None:
443
+ # if there are multiple cookies that meet passed in criteria
444
+ raise CookieConflictError(
445
+ f"There are multiple cookies with name, {name!r}"
446
+ )
447
+ # we will eventually return this as long as no cookie conflict
448
+ toReturn = cookie.value
449
+
450
+ if toReturn is not None:
451
+ return toReturn
452
+ raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")
453
+
454
+ def __getstate__(self) -> dict[str, Any]:
455
+ """Unlike a normal CookieJar, this class is pickleable."""
456
+ state = self.__dict__.copy()
457
+ # remove the unpickleable RLock object
458
+ state.pop("_cookies_lock")
459
+ return state
460
+
461
+ def __setstate__(self, state: dict[str, Any]) -> None:
462
+ """Unlike a normal CookieJar, this class is pickleable."""
463
+ self.__dict__.update(state)
464
+ if "_cookies_lock" not in self.__dict__:
465
+ self._cookies_lock = threading.RLock()
466
+
467
+ def copy(self) -> RequestsCookieJar:
468
+ """Return a copy of this RequestsCookieJar."""
469
+ new_cj = RequestsCookieJar()
470
+ new_cj.set_policy(self.get_policy())
471
+ new_cj.update(self)
472
+ return new_cj
473
+
474
+ def get_policy(self) -> CookiePolicy:
475
+ """Return the CookiePolicy instance used."""
476
+ return self._policy
477
+
478
+
479
+ def _copy_cookie_jar(jar: CookieJar | None) -> CookieJar | None: # type: ignore[reportUnusedFunction] # cross-module usage in models.py
480
+ if jar is None:
481
+ return None
482
+
483
+ if copy_method := getattr(jar, "copy", None):
484
+ # We're dealing with an instance of RequestsCookieJar
485
+ return copy_method()
486
+ # We're dealing with a generic CookieJar instance
487
+ new_jar = copy.copy(jar)
488
+ new_jar.clear()
489
+ for cookie in jar:
490
+ new_jar.set_cookie(copy.copy(cookie))
491
+ return new_jar
492
+
493
+
494
+ def create_cookie(name: str, value: str, **kwargs: Any) -> Cookie:
495
+ """Make a cookie from underspecified parameters.
496
+
497
+ By default, the pair of `name` and `value` will be set for the domain ''
498
+ and sent on every request (this is sometimes called a "supercookie").
499
+ """
500
+ result: dict[str, Any] = {
501
+ "version": 0,
502
+ "name": name,
503
+ "value": value,
504
+ "port": None,
505
+ "domain": "",
506
+ "path": "/",
507
+ "secure": False,
508
+ "expires": None,
509
+ "discard": True,
510
+ "comment": None,
511
+ "comment_url": None,
512
+ "rest": {"HttpOnly": None},
513
+ "rfc2109": False,
514
+ }
515
+
516
+ badargs = set(kwargs) - set(result)
517
+ if badargs:
518
+ raise TypeError(
519
+ f"create_cookie() got unexpected keyword arguments: {list(badargs)}"
520
+ )
521
+
522
+ result.update(kwargs)
523
+ result["port_specified"] = bool(result["port"])
524
+ result["domain_specified"] = bool(result["domain"])
525
+ result["domain_initial_dot"] = result["domain"].startswith(".")
526
+ result["path_specified"] = bool(result["path"])
527
+
528
+ return cookielib.Cookie(**result)
529
+
530
+
531
+ def morsel_to_cookie(morsel: Morsel[Any]) -> Cookie:
532
+ """Convert a Morsel object into a Cookie containing the one k/v pair."""
533
+
534
+ expires: int | None = None
535
+ if morsel["max-age"]:
536
+ try:
537
+ expires = int(time.time() + int(morsel["max-age"]))
538
+ except ValueError:
539
+ raise TypeError(f"max-age: {morsel['max-age']} must be integer")
540
+ elif morsel["expires"]:
541
+ time_template = "%a, %d-%b-%Y %H:%M:%S GMT"
542
+ expires = calendar.timegm(time.strptime(morsel["expires"], time_template))
543
+ return create_cookie(
544
+ comment=morsel["comment"],
545
+ comment_url=bool(morsel["comment"]),
546
+ discard=False,
547
+ domain=morsel["domain"],
548
+ expires=expires,
549
+ name=morsel.key,
550
+ path=morsel["path"],
551
+ port=None,
552
+ rest={"HttpOnly": morsel["httponly"]},
553
+ rfc2109=False,
554
+ secure=bool(morsel["secure"]),
555
+ value=morsel.value,
556
+ version=morsel["version"] or 0,
557
+ )
558
+
559
+
560
+ _CookieJarT = TypeVar("_CookieJarT", bound=CookieJar)
561
+
562
+
563
+ @overload
564
+ def cookiejar_from_dict(
565
+ cookie_dict: dict[str, str] | None,
566
+ cookiejar: None = None,
567
+ overwrite: bool = True,
568
+ ) -> RequestsCookieJar: ...
569
+
570
+
571
+ @overload
572
+ def cookiejar_from_dict(
573
+ cookie_dict: dict[str, str] | None,
574
+ cookiejar: _CookieJarT,
575
+ overwrite: bool = True,
576
+ ) -> _CookieJarT: ...
577
+
578
+
579
+ def cookiejar_from_dict(
580
+ cookie_dict: dict[str, str] | None,
581
+ cookiejar: CookieJar | None = None,
582
+ overwrite: bool = True,
583
+ ) -> CookieJar:
584
+ """Returns a CookieJar from a key/value dictionary.
585
+
586
+ :param cookie_dict: Dict of key/values to insert into CookieJar.
587
+ :param cookiejar: (optional) A cookiejar to add the cookies to.
588
+ :param overwrite: (optional) If False, will not replace cookies
589
+ already in the jar with new ones.
590
+ :rtype: CookieJar
591
+ """
592
+ if cookiejar is None:
593
+ cookiejar = RequestsCookieJar()
594
+
595
+ if cookie_dict is not None:
596
+ names_from_jar = [cookie.name for cookie in cookiejar]
597
+ for name in cookie_dict:
598
+ if overwrite or (name not in names_from_jar):
599
+ cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))
600
+
601
+ return cookiejar
602
+
603
+
604
+ def merge_cookies(
605
+ cookiejar: CookieJar, cookies: dict[str, str] | CookieJar | None
606
+ ) -> CookieJar:
607
+ """Add cookies to cookiejar and returns a merged CookieJar.
608
+
609
+ :param cookiejar: CookieJar object to add the cookies to.
610
+ :param cookies: Dictionary or CookieJar object to be added.
611
+ :rtype: CookieJar
612
+ """
613
+ if not isinstance(cookiejar, cookielib.CookieJar): # type: ignore[reportUnnecessaryIsInstance] # runtime guard
614
+ raise ValueError("You can only merge into CookieJar")
615
+
616
+ if isinstance(cookies, dict):
617
+ cookiejar = cookiejar_from_dict(cookies, cookiejar=cookiejar, overwrite=False)
618
+ elif isinstance(cookies, cookielib.CookieJar):
619
+ if update_method := getattr(cookiejar, "update", None):
620
+ update_method(cookies)
621
+ else:
622
+ for cookie_in_jar in cookies:
623
+ cookiejar.set_cookie(cookie_in_jar)
624
+
625
+ return cookiejar
data/diffusion/.venv/lib/python3.11/site-packages/requests/exceptions.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.exceptions
3
+ ~~~~~~~~~~~~~~~~~~~
4
+
5
+ This module contains the set of Requests' exceptions.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import TYPE_CHECKING, Any
11
+
12
+ from urllib3.exceptions import HTTPError as BaseHTTPError
13
+
14
+ from .compat import JSONDecodeError as CompatJSONDecodeError
15
+
16
+ if TYPE_CHECKING:
17
+ from .models import PreparedRequest, Request, Response
18
+
19
+
20
+ class RequestException(IOError):
21
+ """There was an ambiguous exception that occurred while handling your
22
+ request.
23
+ """
24
+
25
+ response: Response | None
26
+ request: Request | PreparedRequest | None
27
+
28
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
29
+ """Initialize RequestException with `request` and `response` objects."""
30
+ response: Response | None = kwargs.pop("response", None)
31
+ self.response = response
32
+ self.request = kwargs.pop("request", None)
33
+ if response is not None and not self.request and hasattr(response, "request"):
34
+ self.request = response.request
35
+ super().__init__(*args, **kwargs)
36
+
37
+
38
+ class InvalidJSONError(RequestException):
39
+ """A JSON error occurred."""
40
+
41
+
42
+ class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):
43
+ """Couldn't decode the text into json"""
44
+
45
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
46
+ """
47
+ Construct the JSONDecodeError instance first with all
48
+ args. Then use it's args to construct the IOError so that
49
+ the json specific args aren't used as IOError specific args
50
+ and the error message from JSONDecodeError is preserved.
51
+ """
52
+ CompatJSONDecodeError.__init__(self, *args)
53
+ InvalidJSONError.__init__(self, *self.args, **kwargs)
54
+
55
+ def __reduce__(self) -> tuple[Any, ...] | str:
56
+ """
57
+ The __reduce__ method called when pickling the object must
58
+ be the one from the JSONDecodeError (be it json/simplejson)
59
+ as it expects all the arguments for instantiation, not just
60
+ one like the IOError, and the MRO would by default call the
61
+ __reduce__ method from the IOError due to the inheritance order.
62
+ """
63
+ return CompatJSONDecodeError.__reduce__(self)
64
+
65
+
66
+ class HTTPError(RequestException):
67
+ """An HTTP error occurred."""
68
+
69
+
70
+ class ConnectionError(RequestException):
71
+ """A Connection error occurred."""
72
+
73
+
74
+ class ProxyError(ConnectionError):
75
+ """A proxy error occurred."""
76
+
77
+
78
+ class SSLError(ConnectionError):
79
+ """An SSL error occurred."""
80
+
81
+
82
+ class Timeout(RequestException):
83
+ """The request timed out.
84
+
85
+ Catching this error will catch both
86
+ :exc:`~requests.exceptions.ConnectTimeout` and
87
+ :exc:`~requests.exceptions.ReadTimeout` errors.
88
+ """
89
+
90
+
91
+ class ConnectTimeout(ConnectionError, Timeout):
92
+ """The request timed out while trying to connect to the remote server.
93
+
94
+ Requests that produced this error are safe to retry.
95
+ """
96
+
97
+
98
+ class ReadTimeout(Timeout):
99
+ """The server did not send any data in the allotted amount of time."""
100
+
101
+
102
+ class URLRequired(RequestException):
103
+ """A valid URL is required to make a request."""
104
+
105
+
106
+ class TooManyRedirects(RequestException):
107
+ """Too many redirects."""
108
+
109
+
110
+ class MissingSchema(RequestException, ValueError):
111
+ """The URL scheme (e.g. http or https) is missing."""
112
+
113
+
114
+ class InvalidSchema(RequestException, ValueError):
115
+ """The URL scheme provided is either invalid or unsupported."""
116
+
117
+
118
+ class InvalidURL(RequestException, ValueError):
119
+ """The URL provided was somehow invalid."""
120
+
121
+
122
+ class InvalidHeader(RequestException, ValueError):
123
+ """The header value provided was somehow invalid."""
124
+
125
+
126
+ class InvalidProxyURL(InvalidURL):
127
+ """The proxy URL provided is invalid."""
128
+
129
+
130
+ class ChunkedEncodingError(RequestException):
131
+ """The server declared chunked encoding but sent an invalid chunk."""
132
+
133
+
134
+ class ContentDecodingError(RequestException, BaseHTTPError):
135
+ """Failed to decode response content."""
136
+
137
+
138
+ class StreamConsumedError(RequestException, TypeError):
139
+ """The content for this response was already consumed."""
140
+
141
+
142
+ class RetryError(RequestException):
143
+ """Custom retries logic failed"""
144
+
145
+
146
+ class UnrewindableBodyError(RequestException):
147
+ """Requests encountered an error when trying to rewind a body."""
148
+
149
+
150
+ # Warnings
151
+
152
+
153
+ class RequestsWarning(Warning):
154
+ """Base warning for Requests."""
155
+
156
+
157
+ class FileModeWarning(RequestsWarning, DeprecationWarning):
158
+ """A file was opened in text mode, but Requests determined its binary length."""
159
+
160
+
161
+ class RequestsDependencyWarning(RequestsWarning):
162
+ """An imported dependency doesn't match the expected version range."""
data/diffusion/.venv/lib/python3.11/site-packages/requests/help.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Module containing bug report helper(s)."""
2
+
3
+ # pyright: reportUnknownMemberType=false
4
+
5
+ import json
6
+ import platform
7
+ import ssl
8
+ import sys
9
+ from typing import Any
10
+
11
+ import idna
12
+ import urllib3
13
+
14
+ from . import __version__ as requests_version
15
+
16
+ try:
17
+ import charset_normalizer
18
+ except ImportError:
19
+ charset_normalizer = None
20
+
21
+ try:
22
+ import chardet # type: ignore[import-not-found]
23
+ except ImportError:
24
+ chardet = None
25
+
26
+ try:
27
+ from urllib3.contrib import pyopenssl
28
+ except ImportError:
29
+ pyopenssl = None
30
+ OpenSSL = None
31
+ cryptography = None
32
+ else:
33
+ import cryptography # type: ignore[import-not-found]
34
+ import OpenSSL # type: ignore[import-not-found]
35
+
36
+
37
+ def _implementation():
38
+ """Return a dict with the Python implementation and version.
39
+
40
+ Provide both the name and the version of the Python implementation
41
+ currently running. For example, on CPython 3.10.3 it will return
42
+ {'name': 'CPython', 'version': '3.10.3'}.
43
+
44
+ This function works best on CPython and PyPy: in particular, it probably
45
+ doesn't work for Jython or IronPython. Future investigation should be done
46
+ to work out the correct shape of the code for those platforms.
47
+ """
48
+ implementation = platform.python_implementation()
49
+
50
+ if implementation == "CPython":
51
+ implementation_version = platform.python_version()
52
+ elif implementation == "PyPy":
53
+ pypy = sys.pypy_version_info # type: ignore[attr-defined]
54
+ implementation_version = f"{pypy.major}.{pypy.minor}.{pypy.micro}"
55
+ if sys.pypy_version_info.releaselevel != "final": # type: ignore[attr-defined]
56
+ implementation_version = "".join(
57
+ [implementation_version, sys.pypy_version_info.releaselevel] # type: ignore[attr-defined]
58
+ )
59
+ elif implementation == "Jython":
60
+ implementation_version = platform.python_version() # Complete Guess
61
+ elif implementation == "IronPython":
62
+ implementation_version = platform.python_version() # Complete Guess
63
+ else:
64
+ implementation_version = "Unknown"
65
+
66
+ return {"name": implementation, "version": implementation_version}
67
+
68
+
69
+ def info() -> dict[str, Any]:
70
+ """Generate information for a bug report."""
71
+ try:
72
+ platform_info = {
73
+ "system": platform.system(),
74
+ "release": platform.release(),
75
+ }
76
+ except OSError:
77
+ platform_info = {
78
+ "system": "Unknown",
79
+ "release": "Unknown",
80
+ }
81
+
82
+ implementation_info = _implementation()
83
+ urllib3_info = {"version": urllib3.__version__} # type: ignore[reportPrivateImportUsage]
84
+ charset_normalizer_info = {"version": None}
85
+ chardet_info: dict[str, str | None] = {"version": None}
86
+ if charset_normalizer:
87
+ charset_normalizer_info = {"version": charset_normalizer.__version__}
88
+ if chardet:
89
+ chardet_info = {"version": chardet.__version__}
90
+
91
+ pyopenssl_info: dict[str, str | None] = {
92
+ "version": None,
93
+ "openssl_version": "",
94
+ }
95
+ if OpenSSL:
96
+ pyopenssl_info = {
97
+ "version": OpenSSL.__version__,
98
+ "openssl_version": f"{OpenSSL.SSL.OPENSSL_VERSION_NUMBER:x}",
99
+ }
100
+ cryptography_info = {
101
+ "version": getattr(cryptography, "__version__", ""),
102
+ }
103
+ idna_info = {
104
+ "version": getattr(idna, "__version__", ""),
105
+ }
106
+
107
+ system_ssl = ssl.OPENSSL_VERSION_NUMBER
108
+ system_ssl_info = {"version": f"{system_ssl:x}" if system_ssl is not None else ""} # type: ignore[reportUnnecessaryComparison]
109
+
110
+ return {
111
+ "platform": platform_info,
112
+ "implementation": implementation_info,
113
+ "system_ssl": system_ssl_info,
114
+ "using_pyopenssl": pyopenssl is not None,
115
+ "using_charset_normalizer": chardet is None,
116
+ "pyOpenSSL": pyopenssl_info,
117
+ "urllib3": urllib3_info,
118
+ "chardet": chardet_info,
119
+ "charset_normalizer": charset_normalizer_info,
120
+ "cryptography": cryptography_info,
121
+ "idna": idna_info,
122
+ "requests": {
123
+ "version": requests_version,
124
+ },
125
+ }
126
+
127
+
128
+ def main():
129
+ """Pretty-print the bug information as JSON."""
130
+ print(json.dumps(info(), sort_keys=True, indent=2))
131
+
132
+
133
+ if __name__ == "__main__":
134
+ main()
data/diffusion/.venv/lib/python3.11/site-packages/requests/hooks.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.hooks
3
+ ~~~~~~~~~~~~~~
4
+
5
+ This module provides the capabilities for the Requests hooks system.
6
+
7
+ Available hooks:
8
+
9
+ ``response``:
10
+ The response generated from a Request.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from collections.abc import Callable, Iterable
16
+ from typing import TYPE_CHECKING, Any
17
+
18
+ if TYPE_CHECKING:
19
+ from . import _types as _t
20
+ from .models import Response
21
+
22
+ HOOKS: list[str] = ["response"]
23
+
24
+
25
+ def default_hooks() -> dict[str, list[_t.HookType]]:
26
+ return {event: [] for event in HOOKS}
27
+
28
+
29
+ # TODO: response is the only one
30
+
31
+
32
+ def dispatch_hook(
33
+ key: str,
34
+ hooks: _t.HooksInputType | None,
35
+ hook_data: Response,
36
+ **kwargs: Any,
37
+ ) -> Response:
38
+ """Dispatches a hook dictionary on a given piece of data."""
39
+ hooks_dict = hooks or {}
40
+ hook_list: Iterable[_t.HookType] | _t.HookType | None = hooks_dict.get(key)
41
+ if hook_list:
42
+ if isinstance(hook_list, Callable):
43
+ hook_list = [hook_list]
44
+ for hook in hook_list:
45
+ _hook_data = hook(hook_data, **kwargs)
46
+ if _hook_data is not None:
47
+ hook_data = _hook_data
48
+ return hook_data
data/diffusion/.venv/lib/python3.11/site-packages/requests/models.py ADDED
@@ -0,0 +1,1180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.models
3
+ ~~~~~~~~~~~~~~~
4
+
5
+ This module contains the primary objects that power Requests.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import datetime
11
+
12
+ # Import encoding now, to avoid implicit import later.
13
+ # Implicit import within threads may cause LookupError when standard library is in a ZIP,
14
+ # such as in Embedded Python. See https://github.com/psf/requests/issues/3578.
15
+ import encodings.idna # noqa: F401 # type: ignore[reportUnusedImport]
16
+ from collections.abc import Callable, Generator, Iterable, Iterator, Mapping
17
+ from io import UnsupportedOperation
18
+ from typing import (
19
+ TYPE_CHECKING,
20
+ Any,
21
+ Final,
22
+ Literal,
23
+ cast,
24
+ overload,
25
+ )
26
+
27
+ from urllib3.exceptions import (
28
+ DecodeError,
29
+ LocationParseError,
30
+ ProtocolError,
31
+ ReadTimeoutError,
32
+ SSLError,
33
+ )
34
+ from urllib3.fields import RequestField
35
+ from urllib3.filepost import encode_multipart_formdata
36
+ from urllib3.util import parse_url
37
+
38
+ from ._internal_utils import to_native_string, unicode_is_ascii
39
+ from ._types import SupportsRead as _SupportsRead
40
+ from .auth import HTTPBasicAuth
41
+ from .compat import (
42
+ JSONDecodeError,
43
+ basestring,
44
+ builtin_str,
45
+ chardet,
46
+ cookielib,
47
+ urlencode,
48
+ urlsplit,
49
+ urlunparse,
50
+ )
51
+ from .compat import json as complexjson
52
+ from .cookies import (
53
+ _copy_cookie_jar, # type: ignore[reportPrivateUsage]
54
+ cookiejar_from_dict,
55
+ get_cookie_header,
56
+ )
57
+ from .exceptions import (
58
+ ChunkedEncodingError,
59
+ ConnectionError,
60
+ ContentDecodingError,
61
+ HTTPError,
62
+ InvalidJSONError,
63
+ InvalidURL,
64
+ MissingSchema,
65
+ StreamConsumedError,
66
+ )
67
+ from .exceptions import JSONDecodeError as RequestsJSONDecodeError
68
+ from .exceptions import SSLError as RequestsSSLError
69
+ from .hooks import default_hooks
70
+ from .status_codes import codes
71
+ from .structures import CaseInsensitiveDict
72
+ from .utils import (
73
+ check_header_validity,
74
+ get_auth_from_url,
75
+ guess_filename,
76
+ guess_json_utf,
77
+ iter_slices,
78
+ parse_header_links,
79
+ requote_uri,
80
+ stream_decode_response_unicode,
81
+ super_len,
82
+ to_key_val_list,
83
+ )
84
+
85
+ if TYPE_CHECKING:
86
+ from http.cookiejar import CookieJar
87
+
88
+ from typing_extensions import Self
89
+
90
+ from . import _types as _t
91
+ from .adapters import HTTPAdapter
92
+ from .cookies import RequestsCookieJar
93
+
94
+ #: The set of HTTP status codes that indicate an automatically
95
+ #: processable redirect.
96
+ REDIRECT_STATI: Final[tuple[int, ...]] = ( # type: ignore[assignment]
97
+ codes.moved, # 301
98
+ codes.found, # 302
99
+ codes.other, # 303
100
+ codes.temporary_redirect, # 307
101
+ codes.permanent_redirect, # 308
102
+ )
103
+
104
+ DEFAULT_REDIRECT_LIMIT: int = 30
105
+ CONTENT_CHUNK_SIZE: int = 10 * 1024
106
+ ITER_CHUNK_SIZE: int = 512
107
+
108
+
109
+ class RequestEncodingMixin:
110
+ url: str | None
111
+
112
+ @property
113
+ def path_url(self) -> str:
114
+ """Build the path URL to use."""
115
+
116
+ url: list[str] = []
117
+
118
+ p = urlsplit(cast(str, self.url))
119
+
120
+ path = p.path
121
+ if not path:
122
+ path = "/"
123
+
124
+ url.append(path)
125
+
126
+ query = p.query
127
+ if query:
128
+ url.append("?")
129
+ url.append(query)
130
+
131
+ return "".join(url)
132
+
133
+ @overload
134
+ @staticmethod
135
+ def _encode_params(data: str) -> str: ...
136
+
137
+ @overload
138
+ @staticmethod
139
+ def _encode_params(data: bytes) -> bytes: ...
140
+
141
+ @overload
142
+ @staticmethod
143
+ def _encode_params(
144
+ data: _t.SupportsRead[str | bytes],
145
+ ) -> _t.SupportsRead[str | bytes]: ...
146
+
147
+ @overload
148
+ @staticmethod
149
+ def _encode_params(data: _t.KVDataType) -> str: ...
150
+
151
+ @staticmethod
152
+ def _encode_params(
153
+ data: _t.EncodableDataType,
154
+ ) -> str | bytes | _t.SupportsRead[str | bytes]:
155
+ """Encode parameters in a piece of data.
156
+
157
+ Will successfully encode parameters when passed as a dict or a list of
158
+ 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
159
+ if parameters are supplied as a dict.
160
+ """
161
+
162
+ if isinstance(data, (str, bytes)):
163
+ return data
164
+ elif isinstance(data, _SupportsRead):
165
+ return data
166
+ elif hasattr(data, "__iter__"):
167
+ result: list[tuple[bytes, bytes]] = []
168
+ for k, vs in to_key_val_list(data):
169
+ if isinstance(vs, basestring) or not hasattr(vs, "__iter__"):
170
+ vs = [vs]
171
+ for v in vs:
172
+ if v is not None:
173
+ result.append(
174
+ (
175
+ k.encode("utf-8") if isinstance(k, str) else k,
176
+ v.encode("utf-8") if isinstance(v, str) else v,
177
+ )
178
+ )
179
+ return urlencode(result, doseq=True)
180
+ else:
181
+ return data # type: ignore[return-value] # unreachable for valid _t.DataType
182
+
183
+ @staticmethod
184
+ def _encode_files(
185
+ files: _t.FilesType, data: _t.RawDataType | None
186
+ ) -> tuple[bytes, str]:
187
+ """Build the body for a multipart/form-data request.
188
+
189
+ Will successfully encode files when passed as a dict or a list of
190
+ tuples. Order is retained if data is a list of tuples but arbitrary
191
+ if parameters are supplied as a dict.
192
+ The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)
193
+ or 4-tuples (filename, fileobj, contentype, custom_headers).
194
+ """
195
+ if not files:
196
+ raise ValueError("Files must be provided.")
197
+ elif isinstance(data, basestring):
198
+ raise ValueError("Data must not be a string.")
199
+
200
+ new_fields: list[RequestField | tuple[str, bytes]] = []
201
+ fields = to_key_val_list(data or {})
202
+ files = to_key_val_list(files or {})
203
+
204
+ for field, val in fields:
205
+ if isinstance(val, basestring) or not hasattr(val, "__iter__"):
206
+ val = [val]
207
+ for v in val:
208
+ if v is not None:
209
+ # Don't call str() on bytestrings: in Py3 it all goes wrong.
210
+ if not isinstance(v, bytes):
211
+ v = str(v)
212
+
213
+ new_fields.append(
214
+ (
215
+ field.decode("utf-8")
216
+ if isinstance(field, bytes)
217
+ else field,
218
+ v.encode("utf-8") if isinstance(v, str) else v,
219
+ )
220
+ )
221
+
222
+ for k, v in files:
223
+ # support for explicit filename
224
+ ft = None
225
+ fh = None
226
+ if isinstance(v, (tuple, list)):
227
+ if len(v) == 2:
228
+ fn, fp = v
229
+ elif len(v) == 3:
230
+ fn, fp, ft = v
231
+ else:
232
+ fn, fp, ft, fh = v
233
+ else:
234
+ fn = guess_filename(v) or k
235
+ fp = v
236
+
237
+ if isinstance(fp, (str, bytes, bytearray)):
238
+ fdata = fp
239
+ elif isinstance(fp, _SupportsRead): # type: ignore[reportUnnecessaryIsInstance] # defensive check for untyped callers
240
+ fdata = fp.read()
241
+ elif fp is None: # type: ignore[reportUnnecessaryComparison] # defensive check for untyped callers
242
+ continue
243
+ else:
244
+ fdata = fp
245
+
246
+ rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)
247
+ rf.make_multipart(content_type=ft)
248
+ new_fields.append(rf)
249
+
250
+ body, content_type = encode_multipart_formdata(new_fields)
251
+
252
+ return body, content_type
253
+
254
+
255
+ class RequestHooksMixin:
256
+ hooks: dict[str, list[_t.HookType]]
257
+
258
+ def register_hook(
259
+ self, event: str, hook: Iterable[_t.HookType] | _t.HookType
260
+ ) -> None:
261
+ """Properly register a hook."""
262
+
263
+ if event not in self.hooks:
264
+ raise ValueError(f'Unsupported event specified, with event name "{event}"')
265
+
266
+ if isinstance(hook, Callable):
267
+ self.hooks[event].append(hook)
268
+ elif hasattr(hook, "__iter__"):
269
+ self.hooks[event].extend(h for h in hook if isinstance(h, Callable)) # type: ignore[reportUnnecessaryIsInstance] # defensive runtime filter
270
+
271
+ def deregister_hook(self, event: str, hook: _t.HookType) -> bool:
272
+ """Deregister a previously registered hook.
273
+ Returns True if the hook existed, False if not.
274
+ """
275
+
276
+ try:
277
+ self.hooks[event].remove(hook)
278
+ return True
279
+ except ValueError:
280
+ return False
281
+
282
+
283
+ class Request(RequestHooksMixin):
284
+ """A user-created :class:`Request <Request>` object.
285
+
286
+ Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.
287
+
288
+ :param method: HTTP method to use.
289
+ :param url: URL to send.
290
+ :param headers: dictionary of headers to send.
291
+ :param files: dictionary of {filename: fileobject} files to multipart upload.
292
+ :param data: the body to attach to the request. If a dictionary or
293
+ list of tuples ``[(key, value)]`` is provided, form-encoding will
294
+ take place.
295
+ :param json: json for the body to attach to the request (if files or data is not specified).
296
+ :param params: URL parameters to append to the URL. If a dictionary or
297
+ list of tuples ``[(key, value)]`` is provided, form-encoding will
298
+ take place.
299
+ :param auth: Auth handler or (user, pass) tuple.
300
+ :param cookies: dictionary or CookieJar of cookies to attach to this request.
301
+ :param hooks: dictionary of callback hooks, for internal usage.
302
+
303
+ Usage::
304
+
305
+ >>> import requests
306
+ >>> req = requests.Request('GET', 'https://httpbin.org/get')
307
+ >>> req.prepare()
308
+ <PreparedRequest [GET]>
309
+ """
310
+
311
+ method: str | None
312
+ url: _t.UriType | None
313
+ headers: Mapping[str, str | bytes]
314
+ files: _t.FilesType
315
+ data: _t.DataType
316
+ json: _t.JsonType
317
+ params: _t.ParamsType
318
+ auth: _t.AuthType
319
+ cookies: RequestsCookieJar | CookieJar | dict[str, str] | None
320
+
321
+ def __init__(
322
+ self,
323
+ method: str | None = None,
324
+ url: _t.UriType | None = None,
325
+ headers: _t.HeadersType = None,
326
+ files: _t.FilesType = None,
327
+ data: _t.DataType = None,
328
+ params: _t.ParamsType = None,
329
+ auth: _t.AuthType = None,
330
+ cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,
331
+ hooks: _t.HooksInputType | None = None,
332
+ json: _t.JsonType = None,
333
+ ) -> None:
334
+ # Default empty dicts for dict params.
335
+ data = [] if data is None else data
336
+ files = [] if files is None else files
337
+ headers = {} if headers is None else headers
338
+ params = {} if params is None else params
339
+ hooks = {} if hooks is None else hooks
340
+
341
+ self.hooks = default_hooks()
342
+ for k, v in list(hooks.items()):
343
+ self.register_hook(event=k, hook=v)
344
+
345
+ self.method = method
346
+ self.url = url
347
+ self.headers = headers
348
+ self.files = files
349
+ self.data = data
350
+ self.json = json
351
+ self.params = params
352
+ self.auth = auth
353
+ self.cookies = cookies
354
+
355
+ def __repr__(self) -> str:
356
+ return f"<Request [{self.method}]>"
357
+
358
+ def prepare(self) -> PreparedRequest:
359
+ """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it."""
360
+ p = PreparedRequest()
361
+ p.prepare(
362
+ method=self.method,
363
+ url=self.url,
364
+ headers=self.headers,
365
+ files=self.files,
366
+ data=self.data,
367
+ json=self.json,
368
+ params=self.params,
369
+ auth=self.auth,
370
+ cookies=self.cookies,
371
+ hooks=self.hooks,
372
+ )
373
+ return p
374
+
375
+
376
+ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
377
+ """The fully mutable :class:`PreparedRequest <PreparedRequest>` object,
378
+ containing the exact bytes that will be sent to the server.
379
+
380
+ Instances are generated from a :class:`Request <Request>` object, and
381
+ should not be instantiated manually; doing so may produce undesirable
382
+ effects.
383
+
384
+ Usage::
385
+
386
+ >>> import requests
387
+ >>> req = requests.Request('GET', 'https://httpbin.org/get')
388
+ >>> r = req.prepare()
389
+ >>> r
390
+ <PreparedRequest [GET]>
391
+
392
+ >>> s = requests.Session()
393
+ >>> s.send(r)
394
+ <Response [200]>
395
+ """
396
+
397
+ method: str | None
398
+ url: str | None
399
+ headers: CaseInsensitiveDict[str | bytes]
400
+ _cookies: RequestsCookieJar | CookieJar | None
401
+ body: _t.BodyType
402
+ hooks: dict[str, list[_t.HookType]]
403
+ _body_position: int | object | None
404
+
405
+ def __init__(self) -> None:
406
+ #: HTTP verb to send to the server.
407
+ self.method = None
408
+ #: HTTP URL to send the request to.
409
+ self.url = None
410
+ #: dictionary of HTTP headers.
411
+ self.headers = None # type: ignore[assignment]
412
+ # The `CookieJar` used to create the Cookie header will be stored here
413
+ # after prepare_cookies is called
414
+ self._cookies = None
415
+ #: request body to send to the server.
416
+ self.body = None
417
+ #: dictionary of callback hooks, for internal usage.
418
+ self.hooks = default_hooks()
419
+ #: integer denoting starting position of a readable file-like body.
420
+ self._body_position = None
421
+
422
+ def prepare(
423
+ self,
424
+ method: str | None = None,
425
+ url: _t.UriType | None = None,
426
+ headers: Mapping[str, str | bytes] | None = None,
427
+ files: _t.FilesType = None,
428
+ data: _t.DataType = None,
429
+ params: _t.ParamsType = None,
430
+ auth: _t.AuthType = None,
431
+ cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,
432
+ hooks: _t.HooksInputType | None = None,
433
+ json: _t.JsonType = None,
434
+ ) -> None:
435
+ """Prepares the entire request with the given parameters."""
436
+
437
+ url = cast("_t.UriType", url)
438
+ self.prepare_method(method)
439
+ self.prepare_url(url, params)
440
+ self.prepare_headers(headers)
441
+ self.prepare_cookies(cookies)
442
+ self.prepare_body(data, files, json)
443
+ self.prepare_auth(auth, url)
444
+
445
+ # Note that prepare_auth must be last to enable authentication schemes
446
+ # such as OAuth to work on a fully prepared request.
447
+
448
+ # This MUST go after prepare_auth. Authenticators could add a hook
449
+ self.prepare_hooks(hooks)
450
+
451
+ def __repr__(self) -> str:
452
+ return f"<PreparedRequest [{self.method}]>"
453
+
454
+ def copy(self) -> PreparedRequest:
455
+ p = PreparedRequest()
456
+ p.method = self.method
457
+ p.url = self.url
458
+ p.headers = self.headers.copy() if self.headers is not None else None # type: ignore[assignment]
459
+ p._cookies = _copy_cookie_jar(self._cookies)
460
+ p.body = self.body
461
+ p.hooks = self.hooks
462
+ p._body_position = self._body_position
463
+ return p
464
+
465
+ def prepare_method(self, method: str | None) -> None:
466
+ """Prepares the given HTTP method."""
467
+ self.method = method
468
+ if self.method is not None:
469
+ self.method = to_native_string(self.method.upper())
470
+
471
+ @staticmethod
472
+ def _get_idna_encoded_host(host: str) -> str:
473
+ import idna
474
+
475
+ try:
476
+ host = idna.encode(host, uts46=True).decode("utf-8")
477
+ except idna.IDNAError:
478
+ raise UnicodeError
479
+ return host
480
+
481
+ def prepare_url(
482
+ self,
483
+ url: _t.UriType,
484
+ params: _t.ParamsType,
485
+ ) -> None:
486
+ """Prepares the given HTTP URL."""
487
+ #: Accept objects that have string representations.
488
+ #: We're unable to blindly call unicode/str functions
489
+ #: as this will include the bytestring indicator (b'')
490
+ #: on python 3.x.
491
+ #: https://github.com/psf/requests/pull/2238
492
+ if isinstance(url, bytes):
493
+ url = url.decode("utf8")
494
+ else:
495
+ url = str(url)
496
+
497
+ # Remove leading whitespaces from url
498
+ url = url.lstrip()
499
+
500
+ # Don't do any URL preparation for non-HTTP schemes like `mailto`,
501
+ # `data` etc to work around exceptions from `url_parse`, which
502
+ # handles RFC 3986 only.
503
+ if ":" in url and not url.lower().startswith("http"):
504
+ self.url = url
505
+ return
506
+
507
+ # Support for unicode domain names and paths.
508
+ try:
509
+ scheme, auth, host, port, path, query, fragment = parse_url(url)
510
+ except LocationParseError as e:
511
+ raise InvalidURL(*e.args)
512
+
513
+ if not scheme:
514
+ raise MissingSchema(
515
+ f"Invalid URL {url!r}: No scheme supplied. "
516
+ f"Perhaps you meant https://{url}?"
517
+ )
518
+
519
+ if not host:
520
+ raise InvalidURL(f"Invalid URL {url!r}: No host supplied")
521
+
522
+ # In general, we want to try IDNA encoding the hostname if the string contains
523
+ # non-ASCII characters. This allows users to automatically get the correct IDNA
524
+ # behaviour. For strings containing only ASCII characters, we need to also verify
525
+ # it doesn't start with a wildcard (*), before allowing the unencoded hostname.
526
+ if not unicode_is_ascii(host):
527
+ try:
528
+ host = self._get_idna_encoded_host(host)
529
+ except UnicodeError:
530
+ raise InvalidURL("URL has an invalid label.")
531
+ elif host.startswith(("*", ".")):
532
+ raise InvalidURL("URL has an invalid label.")
533
+
534
+ # Carefully reconstruct the network location
535
+ netloc = auth or ""
536
+ if netloc:
537
+ netloc += "@"
538
+ netloc += host
539
+ if port:
540
+ netloc += f":{port}"
541
+
542
+ # Bare domains aren't valid URLs.
543
+ if not path:
544
+ path = "/"
545
+
546
+ if isinstance(params, (str, bytes)):
547
+ params = to_native_string(params)
548
+
549
+ if params is not None:
550
+ enc_params = self._encode_params(params)
551
+ else:
552
+ enc_params = ""
553
+
554
+ if enc_params:
555
+ if query:
556
+ query = f"{query}&{enc_params}"
557
+ else:
558
+ query = enc_params
559
+
560
+ url = requote_uri(urlunparse((scheme, netloc, path, "", query, fragment)))
561
+ self.url = url
562
+
563
+ def prepare_headers(self, headers: Mapping[str, str | bytes] | None) -> None:
564
+ """Prepares the given HTTP headers."""
565
+
566
+ self.headers = CaseInsensitiveDict()
567
+ if headers:
568
+ for header in headers.items():
569
+ # Raise exception on invalid header value.
570
+ check_header_validity(header)
571
+ name, value = header
572
+ self.headers[to_native_string(name)] = value
573
+
574
+ def prepare_body(
575
+ self, data: _t.DataType, files: _t.FilesType, json: _t.JsonType = None
576
+ ) -> None:
577
+ """Prepares the given HTTP body data."""
578
+
579
+ # Check if file, fo, generator, iterator.
580
+ # If not, run through normal process.
581
+
582
+ # Nottin' on you.
583
+ body = None
584
+ content_type = None
585
+
586
+ if not data and json is not None:
587
+ # urllib3 requires a bytes-like body. Python 2's json.dumps
588
+ # provides this natively, but Python 3 gives a Unicode string.
589
+ content_type = "application/json"
590
+
591
+ try:
592
+ body = complexjson.dumps(json, allow_nan=False)
593
+ except ValueError as ve:
594
+ raise InvalidJSONError(ve, request=self)
595
+
596
+ if not isinstance(body, bytes):
597
+ body = body.encode("utf-8")
598
+
599
+ # data that proxies attributes to underlying objects needs hasattr
600
+ is_iterable = isinstance(data, Iterable) or hasattr(data, "__iter__")
601
+ if is_iterable and not isinstance(data, (str, bytes, list, tuple, Mapping)):
602
+ try:
603
+ length = super_len(data)
604
+ except (TypeError, AttributeError, UnsupportedOperation):
605
+ length = None
606
+
607
+ body = data
608
+
609
+ if getattr(body, "tell", None) is not None:
610
+ # Record the current file position before reading.
611
+ # This will allow us to rewind a file in the event
612
+ # of a redirect.
613
+ try:
614
+ self._body_position = body.tell() # type: ignore[union-attr] # guarded by getattr check
615
+ except OSError:
616
+ # This differentiates from None, allowing us to catch
617
+ # a failed `tell()` later when trying to rewind the body
618
+ self._body_position = object()
619
+
620
+ if files:
621
+ raise NotImplementedError(
622
+ "Streamed bodies and files are mutually exclusive."
623
+ )
624
+
625
+ if length:
626
+ self.headers["Content-Length"] = builtin_str(length)
627
+ else:
628
+ self.headers["Transfer-Encoding"] = "chunked"
629
+ else:
630
+ # After is_stream filtering, remaining data is raw (not streamed)
631
+ raw_data = cast("_t.RawDataType | None", data)
632
+
633
+ # Multi-part file uploads.
634
+ if files:
635
+ (body, content_type) = self._encode_files(files, raw_data)
636
+ else:
637
+ if raw_data:
638
+ body = self._encode_params(raw_data)
639
+ if isinstance(data, basestring) or isinstance(data, _SupportsRead):
640
+ content_type = None
641
+ else:
642
+ content_type = "application/x-www-form-urlencoded"
643
+
644
+ self.prepare_content_length(body)
645
+
646
+ # Add content-type if it wasn't explicitly provided.
647
+ if content_type and ("content-type" not in self.headers):
648
+ self.headers["Content-Type"] = content_type
649
+
650
+ self.body = body # type: ignore[assignment] # body transforms from DataType to BodyType
651
+
652
+ def prepare_content_length(self, body: _t.BodyType) -> None:
653
+ """Prepare Content-Length header based on request method and body"""
654
+ if body is not None:
655
+ length = super_len(body)
656
+ if length:
657
+ # If length exists, set it. Otherwise, we fallback
658
+ # to Transfer-Encoding: chunked.
659
+ self.headers["Content-Length"] = builtin_str(length)
660
+ elif (
661
+ self.method not in ("GET", "HEAD")
662
+ and self.headers.get("Content-Length") is None
663
+ ):
664
+ # Set Content-Length to 0 for methods that can have a body
665
+ # but don't provide one. (i.e. not GET or HEAD)
666
+ self.headers["Content-Length"] = "0"
667
+
668
+ def prepare_auth(
669
+ self,
670
+ auth: _t.AuthType,
671
+ url: _t.UriType = "",
672
+ ) -> None:
673
+ """Prepares the given HTTP auth data."""
674
+
675
+ # If no Auth is explicitly provided, extract it from the URL first.
676
+ if auth is None:
677
+ url_auth = get_auth_from_url(cast(str, self.url))
678
+ auth = url_auth if any(url_auth) else None
679
+
680
+ if auth:
681
+ if isinstance(auth, tuple) and len(auth) == 2: # type: ignore[arg-type] # pyright widens tuple from Callable in AuthType
682
+ # special-case basic HTTP auth
683
+ auth_handler = HTTPBasicAuth(*auth) # type: ignore[arg-type] # pyright widens tuple from Callable in AuthType
684
+ else:
685
+ # TODO: can be fixed by flipping the conditionals
686
+ auth_handler = cast("Callable[..., PreparedRequest]", auth)
687
+
688
+ # Allow auth to make its changes.
689
+ r = auth_handler(self)
690
+
691
+ # Update self to reflect the auth changes.
692
+ self.__dict__.update(r.__dict__)
693
+
694
+ # Recompute Content-Length
695
+ self.prepare_content_length(self.body)
696
+
697
+ def prepare_cookies(
698
+ self, cookies: RequestsCookieJar | CookieJar | dict[str, str] | None
699
+ ) -> None:
700
+ """Prepares the given HTTP cookie data.
701
+
702
+ This function eventually generates a ``Cookie`` header from the
703
+ given cookies using cookielib. Due to cookielib's design, the header
704
+ will not be regenerated if it already exists, meaning this function
705
+ can only be called once for the life of the
706
+ :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls
707
+ to ``prepare_cookies`` will have no actual effect, unless the "Cookie"
708
+ header is removed beforehand.
709
+ """
710
+ if isinstance(cookies, cookielib.CookieJar):
711
+ self._cookies = cookies
712
+ else:
713
+ self._cookies = cookiejar_from_dict(cookies)
714
+
715
+ cookies_jar = cast("CookieJar", self._cookies)
716
+ cookie_header = get_cookie_header(cookies_jar, self)
717
+ if cookie_header is not None:
718
+ self.headers["Cookie"] = cookie_header
719
+
720
+ def prepare_hooks(self, hooks: _t.HooksInputType | None) -> None:
721
+ """Prepares the given hooks."""
722
+ # hooks can be passed as None to the prepare method and to this
723
+ # method. To prevent iterating over None, simply use an empty list
724
+ # if hooks is False-y
725
+ hooks = hooks or {}
726
+ for event in hooks:
727
+ self.register_hook(event, hooks[event])
728
+
729
+
730
+ class Response:
731
+ """The :class:`Response <Response>` object, which contains a
732
+ server's response to an HTTP request.
733
+ """
734
+
735
+ _content: bytes | Literal[False] | None
736
+ _content_consumed: bool
737
+ _next: PreparedRequest | None
738
+ status_code: int
739
+ headers: CaseInsensitiveDict[str]
740
+ raw: Any
741
+ url: str
742
+ encoding: str | None
743
+ history: list[Response]
744
+ reason: str
745
+ cookies: RequestsCookieJar
746
+ elapsed: datetime.timedelta
747
+ request: PreparedRequest
748
+ connection: HTTPAdapter
749
+
750
+ __attrs__: list[str] = [
751
+ "_content",
752
+ "status_code",
753
+ "headers",
754
+ "url",
755
+ "history",
756
+ "encoding",
757
+ "reason",
758
+ "cookies",
759
+ "elapsed",
760
+ "request",
761
+ ]
762
+
763
+ def __init__(self) -> None:
764
+ self._content = False
765
+ self._content_consumed = False
766
+ self._next = None
767
+
768
+ #: Integer Code of responded HTTP Status, e.g. 404 or 200.
769
+ self.status_code = None # type: ignore[assignment]
770
+
771
+ #: Case-insensitive Dictionary of Response Headers.
772
+ #: For example, ``headers['content-encoding']`` will return the
773
+ #: value of a ``'Content-Encoding'`` response header.
774
+ self.headers = CaseInsensitiveDict()
775
+
776
+ #: File-like object representation of response (for advanced usage).
777
+ #: Use of ``raw`` requires that ``stream=True`` be set on the request.
778
+ #: This requirement does not apply for use internally to Requests.
779
+ self.raw = None
780
+
781
+ #: Final URL location of Response.
782
+ self.url = None # type: ignore[assignment]
783
+
784
+ #: Encoding to decode with when accessing r.text.
785
+ self.encoding = None
786
+
787
+ #: A list of :class:`Response <Response>` objects from
788
+ #: the history of the Request. Any redirect responses will end
789
+ #: up here. The list is sorted from the oldest to the most recent request.
790
+ self.history = []
791
+
792
+ #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK".
793
+ self.reason = None # type: ignore[assignment]
794
+
795
+ #: A CookieJar of Cookies the server sent back.
796
+ self.cookies = cookiejar_from_dict({})
797
+
798
+ #: The amount of time elapsed between sending the request
799
+ #: and the arrival of the response (as a timedelta).
800
+ #: This property specifically measures the time taken between sending
801
+ #: the first byte of the request and finishing parsing the headers. It
802
+ #: is therefore unaffected by consuming the response content or the
803
+ #: value of the ``stream`` keyword argument.
804
+ self.elapsed = datetime.timedelta(0)
805
+
806
+ #: The :class:`PreparedRequest <PreparedRequest>` object to which this
807
+ #: is a response.
808
+ self.request = None # type: ignore[assignment]
809
+
810
+ def __enter__(self) -> Self:
811
+ return self
812
+
813
+ def __exit__(self, *args: Any) -> None:
814
+ self.close()
815
+
816
+ def __getstate__(self) -> dict[str, Any]:
817
+ # Consume everything; accessing the content attribute makes
818
+ # sure the content has been fully read.
819
+ if not self._content_consumed:
820
+ self.content
821
+
822
+ return {attr: getattr(self, attr, None) for attr in self.__attrs__}
823
+
824
+ def __setstate__(self, state: dict[str, Any]) -> None:
825
+ for name, value in state.items():
826
+ setattr(self, name, value)
827
+
828
+ # pickled objects do not have .raw
829
+ setattr(self, "_content_consumed", True)
830
+ setattr(self, "raw", None)
831
+
832
+ def __repr__(self) -> str:
833
+ return f"<Response [{self.status_code}]>"
834
+
835
+ def __bool__(self) -> bool:
836
+ """Returns True if :attr:`status_code` is less than 400.
837
+
838
+ This attribute checks if the status code of the response is between
839
+ 400 and 600 to see if there was a client error or a server error. If
840
+ the status code, is between 200 and 400, this will return True. This
841
+ is **not** a check to see if the response code is ``200 OK``.
842
+ """
843
+ return self.ok
844
+
845
+ def __nonzero__(self) -> bool:
846
+ """Returns True if :attr:`status_code` is less than 400.
847
+
848
+ This attribute checks if the status code of the response is between
849
+ 400 and 600 to see if there was a client error or a server error. If
850
+ the status code, is between 200 and 400, this will return True. This
851
+ is **not** a check to see if the response code is ``200 OK``.
852
+ """
853
+ return self.ok
854
+
855
+ def __iter__(self) -> Iterator[bytes]:
856
+ """Allows you to use a response as an iterator."""
857
+ return self.iter_content(128)
858
+
859
+ @property
860
+ def ok(self) -> bool:
861
+ """Returns True if :attr:`status_code` is less than 400, False if not.
862
+
863
+ This attribute checks if the status code of the response is between
864
+ 400 and 600 to see if there was a client error or a server error. If
865
+ the status code is between 200 and 400, this will return True. This
866
+ is **not** a check to see if the response code is ``200 OK``.
867
+ """
868
+ try:
869
+ self.raise_for_status()
870
+ except HTTPError:
871
+ return False
872
+ return True
873
+
874
+ @property
875
+ def is_redirect(self) -> bool:
876
+ """True if this Response is a well-formed HTTP redirect that could have
877
+ been processed automatically (by :meth:`Session.resolve_redirects`).
878
+ """
879
+ return "location" in self.headers and self.status_code in REDIRECT_STATI
880
+
881
+ @property
882
+ def is_permanent_redirect(self) -> bool:
883
+ """True if this Response one of the permanent versions of redirect."""
884
+ return "location" in self.headers and self.status_code in (
885
+ codes.moved_permanently,
886
+ codes.permanent_redirect,
887
+ )
888
+
889
+ @property
890
+ def next(self) -> PreparedRequest | None:
891
+ """Returns a PreparedRequest for the next request in a redirect chain, if there is one."""
892
+ return self._next
893
+
894
+ @property
895
+ def apparent_encoding(self) -> str | None:
896
+ """The apparent encoding, provided by the charset_normalizer or chardet libraries."""
897
+ if chardet is not None:
898
+ return chardet.detect(self.content)["encoding"]
899
+ else:
900
+ # If no character detection library is available, we'll fall back
901
+ # to a standard Python utf-8 str.
902
+ return "utf-8"
903
+
904
+ @overload
905
+ def iter_content(
906
+ self, chunk_size: int | None = 1, decode_unicode: Literal[False] = False
907
+ ) -> Iterator[bytes]: ...
908
+ @overload
909
+ def iter_content(
910
+ self, chunk_size: int | None = 1, *, decode_unicode: Literal[True]
911
+ ) -> Iterator[str | bytes]: ...
912
+ def iter_content(
913
+ self, chunk_size: int | None = 1, decode_unicode: bool = False
914
+ ) -> Iterator[str | bytes]:
915
+ """Iterates over the response data. When stream=True is set on the
916
+ request, this avoids reading the content at once into memory for
917
+ large responses. The chunk size is the number of bytes it should
918
+ read into memory. This is not necessarily the length of each item
919
+ returned as decoding can take place.
920
+
921
+ chunk_size must be of type int or None. A value of None will
922
+ function differently depending on the value of `stream`.
923
+ stream=True will read data as it arrives in whatever size the
924
+ chunks are received. If stream=False, data is returned as
925
+ a single chunk.
926
+
927
+ If decode_unicode is True, content will be decoded using encoding
928
+ information from the response. If no encoding information is available,
929
+ bytes will be returned. This can be bypassed by manually setting
930
+ `encoding` on the response.
931
+ """
932
+
933
+ def generate() -> Generator[bytes, None, None]:
934
+ # Special case for urllib3.
935
+ if hasattr(self.raw, "stream"):
936
+ try:
937
+ yield from self.raw.stream(chunk_size, decode_content=True)
938
+ except ProtocolError as e:
939
+ raise ChunkedEncodingError(e)
940
+ except DecodeError as e:
941
+ raise ContentDecodingError(e)
942
+ except ReadTimeoutError as e:
943
+ raise ConnectionError(e)
944
+ except SSLError as e:
945
+ raise RequestsSSLError(e)
946
+ else:
947
+ # Standard file-like object.
948
+ while True:
949
+ chunk = self.raw.read(chunk_size)
950
+ if not chunk:
951
+ break
952
+ yield chunk
953
+
954
+ self._content_consumed = True
955
+
956
+ if self._content_consumed and isinstance(self._content, bool):
957
+ raise StreamConsumedError()
958
+ elif chunk_size is not None and not isinstance(chunk_size, int): # type: ignore[reportUnnecessaryIsInstance] # runtime guard for untyped callers
959
+ raise TypeError(
960
+ f"chunk_size must be an int, it is instead a {type(chunk_size)}."
961
+ )
962
+
963
+ if self._content_consumed:
964
+ # simulate reading small chunks of the content
965
+ content = cast(bytes, self._content)
966
+ chunks = iter_slices(content, chunk_size)
967
+ else:
968
+ chunks = generate()
969
+
970
+ if decode_unicode:
971
+ chunks = stream_decode_response_unicode(chunks, self)
972
+
973
+ return chunks
974
+
975
+ @overload
976
+ def iter_lines(
977
+ self,
978
+ chunk_size: int = ITER_CHUNK_SIZE,
979
+ decode_unicode: Literal[False] = False,
980
+ delimiter: bytes | None = None,
981
+ ) -> Iterator[bytes]: ...
982
+ @overload
983
+ def iter_lines(
984
+ self,
985
+ chunk_size: int = ITER_CHUNK_SIZE,
986
+ *,
987
+ decode_unicode: Literal[True],
988
+ delimiter: str | bytes | None = None,
989
+ ) -> Iterator[str | bytes]: ...
990
+ def iter_lines(
991
+ self,
992
+ chunk_size: int = ITER_CHUNK_SIZE,
993
+ decode_unicode: bool = False,
994
+ delimiter: str | bytes | None = None,
995
+ ) -> Iterator[str | bytes]:
996
+ """Iterates over the response data, one line at a time. When
997
+ stream=True is set on the request, this avoids reading the
998
+ content at once into memory for large responses.
999
+
1000
+ The decode_unicode param works the same as in `iter_content`, with the
1001
+ same caveats.
1002
+
1003
+ .. note:: This method is not reentrant safe.
1004
+ """
1005
+
1006
+ pending: str | bytes | None = None
1007
+
1008
+ for chunk in self.iter_content(
1009
+ chunk_size=chunk_size, decode_unicode=decode_unicode
1010
+ ):
1011
+ if pending is not None:
1012
+ # TODO: remove cast after iter_lines rewrite
1013
+ chunk = cast("str | bytes", pending + chunk) # type: ignore[operator]
1014
+
1015
+ if delimiter:
1016
+ lines = chunk.split(delimiter) # type: ignore[arg-type]
1017
+ else:
1018
+ lines = chunk.splitlines()
1019
+
1020
+ if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:
1021
+ pending = lines.pop()
1022
+ else:
1023
+ pending = None
1024
+
1025
+ yield from lines
1026
+
1027
+ if pending is not None:
1028
+ yield pending
1029
+
1030
+ @property
1031
+ def content(self) -> bytes:
1032
+ """Content of the response, in bytes."""
1033
+
1034
+ if self._content is False:
1035
+ # Read the contents.
1036
+ if self._content_consumed:
1037
+ raise RuntimeError("The content for this response was already consumed")
1038
+
1039
+ if self.status_code == 0 or self.raw is None:
1040
+ self._content = None
1041
+ else:
1042
+ self._content = b"".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b""
1043
+
1044
+ self._content_consumed = True
1045
+ # don't need to release the connection; that's been handled by urllib3
1046
+ # since we exhausted the data.
1047
+ return self._content # type: ignore[return-value]
1048
+
1049
+ @property
1050
+ def text(self) -> str:
1051
+ """Content of the response, in unicode.
1052
+
1053
+ If Response.encoding is None, encoding will be guessed using
1054
+ ``charset_normalizer`` or ``chardet``.
1055
+
1056
+ The encoding of the response content is determined based solely on HTTP
1057
+ headers, following RFC 2616 to the letter. If you can take advantage of
1058
+ non-HTTP knowledge to make a better guess at the encoding, you should
1059
+ set ``r.encoding`` appropriately before accessing this property.
1060
+ """
1061
+
1062
+ # Try charset from content-type
1063
+ content = None
1064
+ encoding = self.encoding
1065
+
1066
+ if not self.content:
1067
+ return ""
1068
+
1069
+ # Fallback to auto-detected encoding.
1070
+ if self.encoding is None:
1071
+ encoding = self.apparent_encoding
1072
+
1073
+ # Decode unicode from given encoding.
1074
+ try:
1075
+ content = str(self.content, encoding or "utf-8", errors="replace")
1076
+ except (LookupError, TypeError):
1077
+ # A LookupError is raised if the encoding was not found which could
1078
+ # indicate a misspelling or similar mistake.
1079
+ #
1080
+ # A TypeError can be raised if encoding is None
1081
+ #
1082
+ # So we try blindly encoding.
1083
+ content = str(self.content, errors="replace")
1084
+
1085
+ return content
1086
+
1087
+ def json(self, **kwargs: Any) -> Any:
1088
+ r"""Decodes the JSON response body (if any) as a Python object.
1089
+
1090
+ This may return a dictionary, list, etc. depending on what is in the response.
1091
+
1092
+ :param \*\*kwargs: Optional arguments that ``json.loads`` takes.
1093
+ :raises requests.exceptions.JSONDecodeError: If the response body does not
1094
+ contain valid json.
1095
+ """
1096
+
1097
+ if not self.encoding and self.content and len(self.content) > 3:
1098
+ # No encoding set. JSON RFC 4627 section 3 states we should expect
1099
+ # UTF-8, -16 or -32. Detect which one to use; If the detection or
1100
+ # decoding fails, fall back to `self.text` (using charset_normalizer to make
1101
+ # a best guess).
1102
+ encoding = guess_json_utf(self.content)
1103
+ if encoding is not None:
1104
+ try:
1105
+ return complexjson.loads(self.content.decode(encoding), **kwargs)
1106
+ except UnicodeDecodeError:
1107
+ # Wrong UTF codec detected; usually because it's not UTF-8
1108
+ # but some other 8-bit codec. This is an RFC violation,
1109
+ # and the server didn't bother to tell us what codec *was*
1110
+ # used.
1111
+ pass
1112
+ except JSONDecodeError as e:
1113
+ raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
1114
+
1115
+ try:
1116
+ return complexjson.loads(self.text, **kwargs)
1117
+ except JSONDecodeError as e:
1118
+ # Catch JSON-related errors and raise as requests.JSONDecodeError
1119
+ # This aliases json.JSONDecodeError and simplejson.JSONDecodeError
1120
+ raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
1121
+
1122
+ @property
1123
+ def links(self) -> dict[str, dict[str, str]]:
1124
+ """Returns the parsed header links of the response, if any."""
1125
+
1126
+ header = self.headers.get("link")
1127
+
1128
+ resolved_links: dict[str, dict[str, str]] = {}
1129
+
1130
+ if header:
1131
+ links = parse_header_links(header)
1132
+
1133
+ for link in links:
1134
+ key = link.get("rel") or link.get("url")
1135
+ if key is not None:
1136
+ resolved_links[key] = link
1137
+
1138
+ return resolved_links
1139
+
1140
+ def raise_for_status(self) -> None:
1141
+ """Raises :class:`HTTPError`, if one occurred."""
1142
+
1143
+ http_error_msg = ""
1144
+ if isinstance(self.reason, bytes):
1145
+ # We attempt to decode utf-8 first because some servers
1146
+ # choose to localize their reason strings. If the string
1147
+ # isn't utf-8, we fall back to iso-8859-1 for all other
1148
+ # encodings. (See PR #3538)
1149
+ try:
1150
+ reason = self.reason.decode("utf-8")
1151
+ except UnicodeDecodeError:
1152
+ reason = self.reason.decode("iso-8859-1")
1153
+ else:
1154
+ reason = self.reason
1155
+
1156
+ if 400 <= self.status_code < 500:
1157
+ http_error_msg = (
1158
+ f"{self.status_code} Client Error: {reason} for url: {self.url}"
1159
+ )
1160
+
1161
+ elif 500 <= self.status_code < 600:
1162
+ http_error_msg = (
1163
+ f"{self.status_code} Server Error: {reason} for url: {self.url}"
1164
+ )
1165
+
1166
+ if http_error_msg:
1167
+ raise HTTPError(http_error_msg, response=self)
1168
+
1169
+ def close(self) -> None:
1170
+ """Releases the connection back to the pool. Once this method has been
1171
+ called the underlying ``raw`` object must not be accessed again.
1172
+
1173
+ *Note: Should not normally need to be called explicitly.*
1174
+ """
1175
+ if not self._content_consumed:
1176
+ self.raw.close()
1177
+
1178
+ release_conn = getattr(self.raw, "release_conn", None)
1179
+ if release_conn is not None:
1180
+ release_conn()
data/diffusion/.venv/lib/python3.11/site-packages/requests/packages.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ from .compat import chardet
4
+
5
+ # This code exists for backwards compatibility reasons.
6
+ # I don't like it either. Just look the other way. :)
7
+
8
+ for package in ("urllib3", "idna"):
9
+ locals()[package] = __import__(package)
10
+ # This traversal is apparently necessary such that the identities are
11
+ # preserved (requests.packages.urllib3.* is urllib3.*)
12
+ for mod in list(sys.modules):
13
+ if mod == package or mod.startswith(f"{package}."):
14
+ sys.modules[f"requests.packages.{mod}"] = sys.modules[mod]
15
+
16
+ if chardet is not None:
17
+ target = chardet.__name__
18
+ for mod in list(sys.modules):
19
+ if mod == target or mod.startswith(f"{target}."):
20
+ imported_mod = sys.modules[mod]
21
+ sys.modules[f"requests.packages.{mod}"] = imported_mod
22
+ mod = mod.replace(target, "chardet")
23
+ sys.modules[f"requests.packages.{mod}"] = imported_mod
data/diffusion/.venv/lib/python3.11/site-packages/requests/py.typed ADDED
File without changes
data/diffusion/.venv/lib/python3.11/site-packages/requests/sessions.py ADDED
@@ -0,0 +1,920 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.sessions
3
+ ~~~~~~~~~~~~~~~~~
4
+
5
+ This module provides a Session object to manage and persist settings across
6
+ requests (cookies, auth, proxies).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import sys
13
+ import time
14
+ from collections import OrderedDict
15
+ from collections.abc import Generator, Mapping, MutableMapping
16
+ from datetime import timedelta
17
+ from typing import TYPE_CHECKING, Any, cast
18
+
19
+ from ._internal_utils import to_native_string
20
+ from ._types import is_prepared as _is_prepared
21
+ from .adapters import HTTPAdapter
22
+ from .auth import _basic_auth_str # type: ignore[reportPrivateUsage]
23
+ from .compat import cookielib, urljoin, urlparse
24
+ from .cookies import (
25
+ RequestsCookieJar,
26
+ cookiejar_from_dict,
27
+ extract_cookies_to_jar,
28
+ merge_cookies,
29
+ )
30
+ from .exceptions import (
31
+ ChunkedEncodingError,
32
+ ContentDecodingError,
33
+ InvalidSchema,
34
+ TooManyRedirects,
35
+ )
36
+ from .hooks import default_hooks, dispatch_hook
37
+
38
+ # formerly defined here, reexposed here for backward compatibility
39
+ from .models import ( # noqa: F401
40
+ DEFAULT_REDIRECT_LIMIT,
41
+ REDIRECT_STATI, # type: ignore[reportUnusedImport]
42
+ PreparedRequest,
43
+ Request,
44
+ Response,
45
+ )
46
+ from .status_codes import codes
47
+ from .structures import CaseInsensitiveDict
48
+ from .utils import ( # noqa: F401
49
+ DEFAULT_PORTS,
50
+ default_headers,
51
+ get_auth_from_url,
52
+ get_environ_proxies,
53
+ get_netrc_auth,
54
+ requote_uri,
55
+ resolve_proxies,
56
+ rewind_body,
57
+ should_bypass_proxies, # type: ignore[reportUnusedImport] # re-export for external consumers
58
+ to_key_val_list,
59
+ )
60
+
61
+ if TYPE_CHECKING:
62
+ from http.cookiejar import CookieJar
63
+
64
+ from typing_extensions import Self, Unpack
65
+
66
+ from . import _types as _t
67
+ from .adapters import BaseAdapter
68
+
69
+ # Preferred clock, based on which one is more accurate on a given system.
70
+ if sys.platform == "win32":
71
+ preferred_clock = time.perf_counter
72
+ else:
73
+ preferred_clock = time.time
74
+
75
+
76
+ def merge_setting(
77
+ request_setting: Any, session_setting: Any, dict_class: type = OrderedDict
78
+ ) -> Any:
79
+ """Determines appropriate setting for a given request, taking into account
80
+ the explicit setting on that request, and the setting in the session. If a
81
+ setting is a dictionary, they will be merged together using `dict_class`
82
+ """
83
+
84
+ if session_setting is None:
85
+ return request_setting
86
+
87
+ if request_setting is None:
88
+ return session_setting
89
+
90
+ # Bypass if not a dictionary (e.g. verify)
91
+ if not (
92
+ isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping)
93
+ ):
94
+ return request_setting
95
+
96
+ merged_setting = dict_class(to_key_val_list(session_setting)) # type: ignore[arg-type] # isinstance narrows Any to Mapping[Unknown]
97
+ merged_setting.update(to_key_val_list(request_setting)) # type: ignore[arg-type]
98
+
99
+ # Remove keys that are set to None. Extract keys first to avoid altering
100
+ # the dictionary during iteration.
101
+ none_keys = [k for (k, v) in merged_setting.items() if v is None]
102
+ for key in none_keys:
103
+ del merged_setting[key]
104
+
105
+ return merged_setting
106
+
107
+
108
+ def merge_hooks(
109
+ request_hooks: _t.HooksType,
110
+ session_hooks: _t.HooksType,
111
+ dict_class: type = OrderedDict,
112
+ ) -> _t.HooksType:
113
+ """Properly merges both requests and session hooks.
114
+
115
+ This is necessary because when request_hooks == {'response': []}, the
116
+ merge breaks Session hooks entirely.
117
+ """
118
+ if session_hooks is None or session_hooks.get("response") == []:
119
+ return request_hooks
120
+
121
+ if request_hooks is None or request_hooks.get("response") == []:
122
+ return session_hooks
123
+
124
+ return merge_setting(request_hooks, session_hooks, dict_class)
125
+
126
+
127
+ class SessionRedirectMixin:
128
+ max_redirects: int
129
+ trust_env: bool
130
+ cookies: RequestsCookieJar
131
+
132
+ def send(self, request: PreparedRequest, **kwargs: Any) -> Response: ...
133
+
134
+ def get_redirect_target(self, resp: Response) -> str | None:
135
+ """Receives a Response. Returns a redirect URI or ``None``"""
136
+ # Due to the nature of how requests processes redirects this method will
137
+ # be called at least once upon the original response and at least twice
138
+ # on each subsequent redirect response (if any).
139
+ # If a custom mixin is used to handle this logic, it may be advantageous
140
+ # to cache the redirect location onto the response object as a private
141
+ # attribute.
142
+ if resp.is_redirect:
143
+ location = resp.headers["location"]
144
+ # Currently the underlying http module on py3 decode headers
145
+ # in latin1, but empirical evidence suggests that latin1 is very
146
+ # rarely used with non-ASCII characters in HTTP headers.
147
+ # It is more likely to get UTF8 header rather than latin1.
148
+ # This causes incorrect handling of UTF8 encoded location headers.
149
+ # To solve this, we re-encode the location in latin1.
150
+ location = location.encode("latin1")
151
+ return to_native_string(location, "utf8")
152
+ return None
153
+
154
+ def should_strip_auth(self, old_url: str, new_url: str) -> bool:
155
+ """Decide whether Authorization header should be removed when redirecting"""
156
+ old_parsed = urlparse(old_url)
157
+ new_parsed = urlparse(new_url)
158
+ if old_parsed.hostname != new_parsed.hostname:
159
+ return True
160
+ # Special case: allow http -> https redirect when using the standard
161
+ # ports. This isn't specified by RFC 7235, but is kept to avoid
162
+ # breaking backwards compatibility with older versions of requests
163
+ # that allowed any redirects on the same host.
164
+ if (
165
+ old_parsed.scheme == "http"
166
+ and old_parsed.port in (80, None)
167
+ and new_parsed.scheme == "https"
168
+ and new_parsed.port in (443, None)
169
+ ):
170
+ return False
171
+
172
+ # Handle default port usage corresponding to scheme.
173
+ changed_port = old_parsed.port != new_parsed.port
174
+ changed_scheme = old_parsed.scheme != new_parsed.scheme
175
+ default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)
176
+ if (
177
+ not changed_scheme
178
+ and old_parsed.port in default_port
179
+ and new_parsed.port in default_port
180
+ ):
181
+ return False
182
+
183
+ # Standard case: root URI must match
184
+ return changed_port or changed_scheme
185
+
186
+ def resolve_redirects(
187
+ self,
188
+ resp: Response,
189
+ req: PreparedRequest,
190
+ stream: bool = False,
191
+ timeout: _t.TimeoutType = None,
192
+ verify: _t.VerifyType = True,
193
+ cert: _t.CertType = None,
194
+ proxies: dict[str, str] | None = None,
195
+ yield_requests: bool = False,
196
+ **adapter_kwargs: Any,
197
+ ) -> Generator[Response, None, None]:
198
+ """Receives a Response. Returns a generator of Responses or Requests."""
199
+
200
+ hist: list[Response] = [] # keep track of history
201
+
202
+ url = self.get_redirect_target(resp)
203
+ previous_fragment = urlparse(req.url).fragment
204
+ while url:
205
+ prepared_request = req.copy()
206
+
207
+ # Update history and keep track of redirects.
208
+ resp.history = hist[:]
209
+ hist.append(resp)
210
+
211
+ try:
212
+ resp.content # Consume socket so it can be released
213
+ except (ChunkedEncodingError, ContentDecodingError, RuntimeError):
214
+ resp.raw.read(decode_content=False)
215
+
216
+ if len(resp.history) >= self.max_redirects:
217
+ raise TooManyRedirects(
218
+ f"Exceeded {self.max_redirects} redirects.", response=resp
219
+ )
220
+
221
+ # Release the connection back into the pool.
222
+ resp.close()
223
+
224
+ # Handle redirection without scheme (see: RFC 1808 Section 4)
225
+ if url.startswith("//"):
226
+ parsed_rurl = urlparse(resp.url)
227
+ url = ":".join([to_native_string(parsed_rurl.scheme), url])
228
+
229
+ # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)
230
+ parsed = urlparse(url)
231
+ if parsed.fragment == "" and previous_fragment:
232
+ parsed = parsed._replace(fragment=previous_fragment)
233
+ elif parsed.fragment:
234
+ previous_fragment = parsed.fragment
235
+ url = parsed.geturl()
236
+
237
+ # Facilitate relative 'location' headers, as allowed by RFC 7231.
238
+ # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
239
+ # Compliant with RFC3986, we percent encode the url.
240
+ if not parsed.netloc:
241
+ url = urljoin(resp.url, requote_uri(url))
242
+ else:
243
+ url = requote_uri(url)
244
+
245
+ prepared_request.url = to_native_string(url)
246
+
247
+ self.rebuild_method(prepared_request, resp)
248
+
249
+ # https://github.com/psf/requests/issues/1084
250
+ if resp.status_code not in (
251
+ codes.temporary_redirect,
252
+ codes.permanent_redirect,
253
+ ):
254
+ # https://github.com/psf/requests/issues/3490
255
+ purged_headers = ("Content-Length", "Content-Type", "Transfer-Encoding")
256
+ for header in purged_headers:
257
+ prepared_request.headers.pop(header, None)
258
+ prepared_request.body = None
259
+
260
+ headers = prepared_request.headers
261
+ headers.pop("Cookie", None)
262
+
263
+ # Extract any cookies sent on the response to the cookiejar
264
+ # in the new request. Because we've mutated our copied prepared
265
+ # request, use the old one that we haven't yet touched.
266
+ cookie_jar = cast("CookieJar", prepared_request._cookies) # type: ignore[reportPrivateUsage]
267
+ extract_cookies_to_jar(cookie_jar, req, resp.raw)
268
+ merge_cookies(cookie_jar, self.cookies)
269
+ prepared_request.prepare_cookies(cookie_jar)
270
+
271
+ # Rebuild auth and proxy information.
272
+ proxies = self.rebuild_proxies(prepared_request, proxies)
273
+ self.rebuild_auth(prepared_request, resp)
274
+
275
+ # A failed tell() sets `_body_position` to `object()`. This non-None
276
+ # value ensures `rewindable` will be True, allowing us to raise an
277
+ # UnrewindableBodyError, instead of hanging the connection.
278
+ rewindable = prepared_request._body_position is not None and ( # type: ignore[reportPrivateUsage]
279
+ "Content-Length" in headers or "Transfer-Encoding" in headers
280
+ )
281
+
282
+ # Attempt to rewind consumed file-like object.
283
+ if rewindable:
284
+ rewind_body(prepared_request)
285
+
286
+ # Override the original request.
287
+ req = prepared_request
288
+
289
+ if yield_requests:
290
+ yield req # type: ignore[misc] # Internal use only, returns PreparedRequest
291
+ else:
292
+ resp = self.send(
293
+ req,
294
+ stream=stream,
295
+ timeout=timeout,
296
+ verify=verify,
297
+ cert=cert,
298
+ proxies=proxies,
299
+ allow_redirects=False,
300
+ **adapter_kwargs,
301
+ )
302
+
303
+ extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)
304
+
305
+ # extract redirect url, if any, for the next loop
306
+ url = self.get_redirect_target(resp)
307
+ yield resp
308
+
309
+ def rebuild_auth(
310
+ self, prepared_request: PreparedRequest, response: Response
311
+ ) -> None:
312
+ """When being redirected we may want to strip authentication from the
313
+ request to avoid leaking credentials. This method intelligently removes
314
+ and reapplies authentication where possible to avoid credential loss.
315
+ """
316
+ original_request = response.request
317
+ assert _is_prepared(original_request)
318
+ assert _is_prepared(prepared_request)
319
+
320
+ headers = prepared_request.headers
321
+ original_url = original_request.url
322
+ url = prepared_request.url
323
+
324
+ if "Authorization" in headers and self.should_strip_auth(original_url, url):
325
+ # If we get redirected to a new host, we should strip out any
326
+ # authentication headers.
327
+ del headers["Authorization"]
328
+
329
+ # .netrc might have more auth for us on our new host.
330
+ new_auth = get_netrc_auth(url) if self.trust_env else None
331
+ if new_auth is not None:
332
+ prepared_request.prepare_auth(new_auth)
333
+
334
+ def rebuild_proxies(
335
+ self,
336
+ prepared_request: PreparedRequest,
337
+ proxies: dict[str, str] | None,
338
+ ) -> dict[str, str]:
339
+ """This method re-evaluates the proxy configuration by considering the
340
+ environment variables. If we are redirected to a URL covered by
341
+ NO_PROXY, we strip the proxy configuration. Otherwise, we set missing
342
+ proxy keys for this URL (in case they were stripped by a previous
343
+ redirect).
344
+
345
+ This method also replaces the Proxy-Authorization header where
346
+ necessary.
347
+
348
+ :rtype: dict
349
+ """
350
+ assert _is_prepared(prepared_request)
351
+ headers = prepared_request.headers
352
+ scheme = urlparse(prepared_request.url).scheme
353
+ new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)
354
+
355
+ if "Proxy-Authorization" in headers:
356
+ del headers["Proxy-Authorization"]
357
+
358
+ try:
359
+ username, password = get_auth_from_url(new_proxies[scheme])
360
+ except KeyError:
361
+ username, password = None, None
362
+
363
+ # urllib3 handles proxy authorization for us in the standard adapter.
364
+ # Avoid appending this to TLS tunneled requests where it may be leaked.
365
+ if not scheme.startswith("https") and username and password:
366
+ headers["Proxy-Authorization"] = _basic_auth_str(username, password)
367
+
368
+ return new_proxies
369
+
370
+ def rebuild_method(
371
+ self, prepared_request: PreparedRequest, response: Response
372
+ ) -> None:
373
+ """When being redirected we may want to change the method of the request
374
+ based on certain specs or browser behavior.
375
+ """
376
+ method = prepared_request.method
377
+
378
+ # https://tools.ietf.org/html/rfc7231#section-6.4.4
379
+ if response.status_code == codes.see_other and method != "HEAD":
380
+ method = "GET"
381
+
382
+ # Do what the browsers do, despite standards...
383
+ # First, turn 302s into GETs.
384
+ if response.status_code == codes.found and method != "HEAD":
385
+ method = "GET"
386
+
387
+ # Second, if a POST is responded to with a 301, turn it into a GET.
388
+ # This bizarre behaviour is explained in Issue 1704.
389
+ if response.status_code == codes.moved and method == "POST":
390
+ method = "GET"
391
+
392
+ prepared_request.method = method
393
+
394
+
395
+ class Session(SessionRedirectMixin):
396
+ """A Requests session.
397
+
398
+ Provides cookie persistence, connection-pooling, and configuration.
399
+
400
+ Basic Usage::
401
+
402
+ >>> import requests
403
+ >>> s = requests.Session()
404
+ >>> s.get('https://httpbin.org/get')
405
+ <Response [200]>
406
+
407
+ Or as a context manager::
408
+
409
+ >>> with requests.Session() as s:
410
+ ... s.get('https://httpbin.org/get')
411
+ <Response [200]>
412
+ """
413
+
414
+ headers: CaseInsensitiveDict[str]
415
+ auth: _t.AuthType
416
+ proxies: dict[str, str]
417
+ hooks: dict[str, list[_t.HookType]]
418
+ params: MutableMapping[str, Any]
419
+ stream: bool
420
+ verify: _t.VerifyType
421
+ cert: _t.CertType
422
+ max_redirects: int
423
+ trust_env: bool
424
+ cookies: RequestsCookieJar
425
+ adapters: MutableMapping[str, BaseAdapter]
426
+
427
+ __attrs__: list[str] = [
428
+ "headers",
429
+ "cookies",
430
+ "auth",
431
+ "proxies",
432
+ "hooks",
433
+ "params",
434
+ "verify",
435
+ "cert",
436
+ "adapters",
437
+ "stream",
438
+ "trust_env",
439
+ "max_redirects",
440
+ ]
441
+
442
+ def __init__(self) -> None:
443
+ #: A case-insensitive dictionary of headers to be sent on each
444
+ #: :class:`Request <Request>` sent from this
445
+ #: :class:`Session <Session>`.
446
+ self.headers = default_headers()
447
+
448
+ #: Default Authentication tuple or object to attach to
449
+ #: :class:`Request <Request>`.
450
+ self.auth = None
451
+
452
+ #: Dictionary mapping protocol or protocol and host to the URL of the proxy
453
+ #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to
454
+ #: be used on each :class:`Request <Request>`.
455
+ self.proxies = {}
456
+
457
+ #: Event-handling hooks.
458
+ self.hooks = default_hooks()
459
+
460
+ #: Dictionary of querystring data to attach to each
461
+ #: :class:`Request <Request>`. The dictionary values may be lists for
462
+ #: representing multivalued query parameters.
463
+ self.params = {}
464
+
465
+ #: Stream response content default.
466
+ self.stream = False
467
+
468
+ #: SSL Verification default.
469
+ #: Defaults to `True`, requiring requests to verify the TLS certificate at the
470
+ #: remote end.
471
+ #: If verify is set to `False`, requests will accept any TLS certificate
472
+ #: presented by the server, and will ignore hostname mismatches and/or
473
+ #: expired certificates, which will make your application vulnerable to
474
+ #: man-in-the-middle (MitM) attacks.
475
+ #: Only set this to `False` for testing.
476
+ #: If verify is set to a string, it must be the path to a CA bundle file
477
+ #: that will be used to verify the TLS certificate.
478
+ self.verify = True
479
+
480
+ #: SSL client certificate default, if String, path to ssl client
481
+ #: cert file (.pem). If Tuple, ('cert', 'key') pair.
482
+ self.cert = None
483
+
484
+ #: Maximum number of redirects allowed. If the request exceeds this
485
+ #: limit, a :class:`TooManyRedirects` exception is raised.
486
+ #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is
487
+ #: 30.
488
+ self.max_redirects = DEFAULT_REDIRECT_LIMIT
489
+
490
+ #: Trust environment settings for proxy configuration, default
491
+ #: authentication and similar.
492
+ self.trust_env = True
493
+
494
+ #: A CookieJar containing all currently outstanding cookies set on this
495
+ #: session. By default it is a
496
+ #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but
497
+ #: may be any other ``cookielib.CookieJar`` compatible object.
498
+ self.cookies = cookiejar_from_dict({})
499
+
500
+ # Default connection adapters.
501
+ self.adapters = OrderedDict()
502
+ self.mount("https://", HTTPAdapter())
503
+ self.mount("http://", HTTPAdapter())
504
+
505
+ def __enter__(self) -> Self:
506
+ return self
507
+
508
+ def __exit__(self, *args: Any) -> None:
509
+ self.close()
510
+
511
+ def prepare_request(self, request: Request) -> PreparedRequest:
512
+ """Constructs a :class:`PreparedRequest <PreparedRequest>` for
513
+ transmission and returns it. The :class:`PreparedRequest` has settings
514
+ merged from the :class:`Request <Request>` instance and those of the
515
+ :class:`Session`.
516
+
517
+ :param request: :class:`Request` instance to prepare with this
518
+ session's settings.
519
+ :rtype: requests.PreparedRequest
520
+ """
521
+ url = cast("_t.UriType", request.url)
522
+ method = cast(str, request.method)
523
+
524
+ cookies = request.cookies or {}
525
+
526
+ # Bootstrap CookieJar.
527
+ if not isinstance(cookies, cookielib.CookieJar):
528
+ cookies = cookiejar_from_dict(cookies)
529
+
530
+ # Merge with session cookies
531
+ merged_cookies = merge_cookies(
532
+ merge_cookies(RequestsCookieJar(), self.cookies), cookies
533
+ )
534
+
535
+ # Set environment's basic authentication if not explicitly set.
536
+ auth = request.auth
537
+ if self.trust_env and not auth and not self.auth:
538
+ auth = get_netrc_auth(url)
539
+
540
+ p = PreparedRequest()
541
+ p.prepare(
542
+ method=method.upper(),
543
+ url=url,
544
+ files=request.files,
545
+ data=request.data,
546
+ json=request.json,
547
+ headers=merge_setting(
548
+ request.headers, self.headers, dict_class=CaseInsensitiveDict
549
+ ),
550
+ params=merge_setting(request.params, self.params),
551
+ auth=merge_setting(auth, self.auth),
552
+ cookies=merged_cookies,
553
+ hooks=merge_hooks(request.hooks, self.hooks),
554
+ )
555
+ return p
556
+
557
+ def request(
558
+ self,
559
+ method: str,
560
+ url: _t.UriType,
561
+ params: _t.ParamsType = None,
562
+ data: _t.DataType = None,
563
+ headers: _t.HeadersType = None,
564
+ cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,
565
+ files: _t.FilesType = None,
566
+ auth: _t.AuthType = None,
567
+ timeout: _t.TimeoutType = None,
568
+ allow_redirects: bool = True,
569
+ proxies: dict[str, str] | None = None,
570
+ hooks: _t.HooksInputType | None = None,
571
+ stream: bool | None = None,
572
+ verify: _t.VerifyType | None = None,
573
+ cert: _t.CertType = None,
574
+ json: _t.JsonType = None,
575
+ ) -> Response:
576
+ """Constructs a :class:`Request <Request>`, prepares it and sends it.
577
+ Returns :class:`Response <Response>` object.
578
+
579
+ :param method: method for the new :class:`Request` object.
580
+ :param url: URL for the new :class:`Request` object.
581
+ :param params: (optional) Dictionary or bytes to be sent in the query
582
+ string for the :class:`Request`.
583
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
584
+ object to send in the body of the :class:`Request`.
585
+ :param json: (optional) json to send in the body of the
586
+ :class:`Request`.
587
+ :param headers: (optional) Dictionary of HTTP Headers to send with the
588
+ :class:`Request`.
589
+ :param cookies: (optional) Dict or CookieJar object to send with the
590
+ :class:`Request`.
591
+ :param files: (optional) Dictionary of ``'filename': file-like-objects``
592
+ for multipart encoding upload.
593
+ :param auth: (optional) Auth tuple or callable to enable
594
+ Basic/Digest/Custom HTTP Auth.
595
+ :param timeout: (optional) How many seconds to wait for the server to send
596
+ data before giving up, as a float, or a :ref:`(connect timeout,
597
+ read timeout) <timeouts>` tuple.
598
+ :type timeout: float or tuple
599
+ :param allow_redirects: (optional) Set to True by default.
600
+ :type allow_redirects: bool
601
+ :param proxies: (optional) Dictionary mapping protocol or protocol and
602
+ hostname to the URL of the proxy.
603
+ :param hooks: (optional) Dictionary mapping hook name to one event or
604
+ list of events, event must be callable.
605
+ :param stream: (optional) whether to immediately download the response
606
+ content. Defaults to ``False``.
607
+ :param verify: (optional) Either a boolean, in which case it controls whether we verify
608
+ the server's TLS certificate, or a string, in which case it must be a path
609
+ to a CA bundle to use. Defaults to ``True``. When set to
610
+ ``False``, requests will accept any TLS certificate presented by
611
+ the server, and will ignore hostname mismatches and/or expired
612
+ certificates, which will make your application vulnerable to
613
+ man-in-the-middle (MitM) attacks. Setting verify to ``False``
614
+ may be useful during local development or testing.
615
+ :param cert: (optional) if String, path to ssl client cert file (.pem).
616
+ If Tuple, ('cert', 'key') pair.
617
+ :rtype: requests.Response
618
+ """
619
+ if isinstance(url, bytes):
620
+ url = url.decode("utf-8")
621
+
622
+ # Create the Request.
623
+ req = Request(
624
+ method=method.upper(),
625
+ url=url,
626
+ headers=headers,
627
+ files=files,
628
+ data=data or {},
629
+ json=json,
630
+ params=params or {},
631
+ auth=auth,
632
+ cookies=cookies,
633
+ hooks=hooks,
634
+ )
635
+ prep = self.prepare_request(req)
636
+
637
+ assert _is_prepared(prep)
638
+
639
+ proxies = proxies or {}
640
+
641
+ settings = self.merge_environment_settings(
642
+ prep.url, proxies, stream, verify, cert
643
+ )
644
+
645
+ # Send the request.
646
+ send_kwargs = {
647
+ "timeout": timeout,
648
+ "allow_redirects": allow_redirects,
649
+ }
650
+ send_kwargs.update(settings)
651
+ resp = self.send(prep, **send_kwargs)
652
+
653
+ return resp
654
+
655
+ def get(
656
+ self,
657
+ url: _t.UriType,
658
+ params: _t.ParamsType = None,
659
+ **kwargs: Unpack[_t.GetKwargs],
660
+ ) -> Response:
661
+ r"""Sends a GET request. Returns :class:`Response` object.
662
+
663
+ :param url: URL for the new :class:`Request` object.
664
+ :param params: (optional) Dictionary, list of tuples or bytes to send
665
+ in the query string for the :class:`Request`.
666
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
667
+ :rtype: requests.Response
668
+ """
669
+
670
+ kwargs.setdefault("allow_redirects", True)
671
+ return self.request("GET", url, params=params, **kwargs)
672
+
673
+ def options(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:
674
+ r"""Sends a OPTIONS request. Returns :class:`Response` object.
675
+
676
+ :param url: URL for the new :class:`Request` object.
677
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
678
+ :rtype: requests.Response
679
+ """
680
+
681
+ kwargs.setdefault("allow_redirects", True)
682
+ return self.request("OPTIONS", url, **kwargs)
683
+
684
+ def head(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:
685
+ r"""Sends a HEAD request. Returns :class:`Response` object.
686
+
687
+ :param url: URL for the new :class:`Request` object.
688
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
689
+ :rtype: requests.Response
690
+ """
691
+
692
+ kwargs.setdefault("allow_redirects", False)
693
+ return self.request("HEAD", url, **kwargs)
694
+
695
+ def post(
696
+ self,
697
+ url: _t.UriType,
698
+ data: _t.DataType = None,
699
+ json: _t.JsonType = None,
700
+ **kwargs: Unpack[_t.PostKwargs],
701
+ ) -> Response:
702
+ r"""Sends a POST request. Returns :class:`Response` object.
703
+
704
+ :param url: URL for the new :class:`Request` object.
705
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
706
+ object to send in the body of the :class:`Request`.
707
+ :param json: (optional) json to send in the body of the :class:`Request`.
708
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
709
+ :rtype: requests.Response
710
+ """
711
+
712
+ return self.request("POST", url, data=data, json=json, **kwargs)
713
+
714
+ def put(
715
+ self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]
716
+ ) -> Response:
717
+ r"""Sends a PUT request. Returns :class:`Response` object.
718
+
719
+ :param url: URL for the new :class:`Request` object.
720
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
721
+ object to send in the body of the :class:`Request`.
722
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
723
+ :rtype: requests.Response
724
+ """
725
+
726
+ return self.request("PUT", url, data=data, **kwargs)
727
+
728
+ def patch(
729
+ self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]
730
+ ) -> Response:
731
+ r"""Sends a PATCH request. Returns :class:`Response` object.
732
+
733
+ :param url: URL for the new :class:`Request` object.
734
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
735
+ object to send in the body of the :class:`Request`.
736
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
737
+ :rtype: requests.Response
738
+ """
739
+
740
+ return self.request("PATCH", url, data=data, **kwargs)
741
+
742
+ def delete(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:
743
+ r"""Sends a DELETE request. Returns :class:`Response` object.
744
+
745
+ :param url: URL for the new :class:`Request` object.
746
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
747
+ :rtype: requests.Response
748
+ """
749
+
750
+ return self.request("DELETE", url, **kwargs)
751
+
752
+ def send(self, request: PreparedRequest, **kwargs: Any) -> Response:
753
+ """Send a given PreparedRequest.
754
+
755
+ :rtype: requests.Response
756
+ """
757
+ # Set defaults that the hooks can utilize to ensure they always have
758
+ # the correct parameters to reproduce the previous request.
759
+ kwargs.setdefault("stream", self.stream)
760
+ kwargs.setdefault("verify", self.verify)
761
+ kwargs.setdefault("cert", self.cert)
762
+ if "proxies" not in kwargs:
763
+ kwargs["proxies"] = resolve_proxies(request, self.proxies, self.trust_env)
764
+
765
+ # It's possible that users might accidentally send a Request object.
766
+ # Guard against that specific failure case.
767
+ if isinstance(request, Request):
768
+ raise ValueError("You can only send PreparedRequests.")
769
+
770
+ assert _is_prepared(request)
771
+
772
+ # Set up variables needed for resolve_redirects and dispatching of hooks
773
+ allow_redirects = kwargs.pop("allow_redirects", True)
774
+ stream = kwargs.get("stream")
775
+ hooks = request.hooks
776
+
777
+ # Get the appropriate adapter to use
778
+ adapter = self.get_adapter(url=request.url)
779
+
780
+ # Start time (approximately) of the request
781
+ start = preferred_clock()
782
+
783
+ # Send the request
784
+ r = adapter.send(request, **kwargs)
785
+
786
+ # Total elapsed time of the request (approximately)
787
+ elapsed = preferred_clock() - start
788
+ r.elapsed = timedelta(seconds=elapsed)
789
+
790
+ # Response manipulation hooks
791
+ r = dispatch_hook("response", hooks, r, **kwargs)
792
+
793
+ # Persist cookies
794
+ if r.history:
795
+ # If the hooks create history then we want those cookies too
796
+ for resp in r.history:
797
+ extract_cookies_to_jar(self.cookies, resp.request, resp.raw)
798
+
799
+ extract_cookies_to_jar(self.cookies, request, r.raw)
800
+
801
+ # Resolve redirects if allowed.
802
+ if allow_redirects:
803
+ # Redirect resolving generator.
804
+ gen = self.resolve_redirects(r, request, **kwargs)
805
+ history = [resp for resp in gen]
806
+ else:
807
+ history = []
808
+
809
+ # Shuffle things around if there's history.
810
+ if history:
811
+ # Insert the first (original) request at the start
812
+ history.insert(0, r)
813
+ # Get the last request made
814
+ r = history.pop()
815
+ r.history = history
816
+
817
+ # If redirects aren't being followed, store the response on the Request for Response.next().
818
+ if not allow_redirects:
819
+ try:
820
+ r._next = next( # type: ignore[assignment] # yield_requests=True returns PreparedRequest
821
+ self.resolve_redirects(r, request, yield_requests=True, **kwargs)
822
+ )
823
+ except StopIteration:
824
+ pass
825
+
826
+ if not stream:
827
+ r.content
828
+
829
+ return r
830
+
831
+ def merge_environment_settings(
832
+ self,
833
+ url: str,
834
+ proxies: dict[str, str] | None,
835
+ stream: bool | None,
836
+ verify: _t.VerifyType | None,
837
+ cert: _t.CertType,
838
+ ) -> dict[str, Any]:
839
+ """
840
+ Check the environment and merge it with some settings.
841
+
842
+ :rtype: dict
843
+ """
844
+ # Gather clues from the surrounding environment.
845
+ if self.trust_env:
846
+ # Set environment's proxies.
847
+ no_proxy = proxies.get("no_proxy") if proxies is not None else None
848
+ env_proxies = get_environ_proxies(url, no_proxy=no_proxy)
849
+ if proxies is not None:
850
+ for k, v in env_proxies.items():
851
+ proxies.setdefault(k, v)
852
+
853
+ # Look for requests environment configuration
854
+ # and be compatible with cURL.
855
+ if verify is True or verify is None:
856
+ verify = (
857
+ os.environ.get("REQUESTS_CA_BUNDLE")
858
+ or os.environ.get("CURL_CA_BUNDLE")
859
+ or verify
860
+ )
861
+
862
+ # Merge all the kwargs.
863
+ proxies = merge_setting(proxies, self.proxies)
864
+ stream = merge_setting(stream, self.stream)
865
+ verify = merge_setting(verify, self.verify)
866
+ cert = merge_setting(cert, self.cert)
867
+
868
+ return {"proxies": proxies, "stream": stream, "verify": verify, "cert": cert}
869
+
870
+ def get_adapter(self, url: str) -> BaseAdapter:
871
+ """
872
+ Returns the appropriate connection adapter for the given URL.
873
+
874
+ :rtype: requests.adapters.BaseAdapter
875
+ """
876
+ for prefix, adapter in self.adapters.items():
877
+ if url.lower().startswith(prefix.lower()):
878
+ return adapter
879
+
880
+ # Nothing matches :-/
881
+ raise InvalidSchema(f"No connection adapters were found for {url!r}")
882
+
883
+ def close(self) -> None:
884
+ """Closes all adapters and as such the session"""
885
+ for v in self.adapters.values():
886
+ v.close()
887
+
888
+ def mount(self, prefix: str, adapter: BaseAdapter) -> None:
889
+ """Registers a connection adapter to a prefix.
890
+
891
+ Adapters are sorted in descending order by prefix length.
892
+ """
893
+ self.adapters[prefix] = adapter
894
+ keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]
895
+
896
+ for key in keys_to_move:
897
+ self.adapters[key] = self.adapters.pop(key)
898
+
899
+ def __getstate__(self) -> dict[str, Any]:
900
+ state = {attr: getattr(self, attr, None) for attr in self.__attrs__}
901
+ return state
902
+
903
+ def __setstate__(self, state: dict[str, Any]) -> None:
904
+ for attr, value in state.items():
905
+ setattr(self, attr, value)
906
+
907
+
908
+ def session() -> Session:
909
+ """
910
+ Returns a :class:`Session` for context-management.
911
+
912
+ .. deprecated:: 1.0.0
913
+
914
+ This method has been deprecated since version 1.0.0 and is only kept for
915
+ backwards compatibility. New code should use :class:`~requests.sessions.Session`
916
+ to create a session. This may be removed at a future date.
917
+
918
+ :rtype: Session
919
+ """
920
+ return Session()
data/diffusion/.venv/lib/python3.11/site-packages/requests/status_codes.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ The ``codes`` object defines a mapping from common names for HTTP statuses
3
+ to their numerical codes, accessible either as attributes or as dictionary
4
+ items.
5
+
6
+ Example::
7
+
8
+ >>> import requests
9
+ >>> requests.codes['temporary_redirect']
10
+ 307
11
+ >>> requests.codes.teapot
12
+ 418
13
+ >>> requests.codes['\o/']
14
+ 200
15
+
16
+ Some codes have multiple names, and both upper- and lower-case versions of
17
+ the names are allowed. For example, ``codes.ok``, ``codes.OK``, and
18
+ ``codes.okay`` all correspond to the HTTP status code 200.
19
+ """
20
+
21
+ from .structures import LookupDict
22
+
23
+ _codes = {
24
+ # Informational.
25
+ 100: ("continue",),
26
+ 101: ("switching_protocols",),
27
+ 102: ("processing", "early-hints"),
28
+ 103: ("checkpoint",),
29
+ 122: ("uri_too_long", "request_uri_too_long"),
30
+ 200: ("ok", "okay", "all_ok", "all_okay", "all_good", "\\o/", "✓"),
31
+ 201: ("created",),
32
+ 202: ("accepted",),
33
+ 203: ("non_authoritative_info", "non_authoritative_information"),
34
+ 204: ("no_content",),
35
+ 205: ("reset_content", "reset"),
36
+ 206: ("partial_content", "partial"),
37
+ 207: ("multi_status", "multiple_status", "multi_stati", "multiple_stati"),
38
+ 208: ("already_reported",),
39
+ 226: ("im_used",),
40
+ # Redirection.
41
+ 300: ("multiple_choices",),
42
+ 301: ("moved_permanently", "moved", "\\o-"),
43
+ 302: ("found",),
44
+ 303: ("see_other", "other"),
45
+ 304: ("not_modified",),
46
+ 305: ("use_proxy",),
47
+ 306: ("switch_proxy",),
48
+ 307: ("temporary_redirect", "temporary_moved", "temporary"),
49
+ 308: (
50
+ "permanent_redirect",
51
+ "resume_incomplete",
52
+ "resume",
53
+ ), # "resume" and "resume_incomplete" to be removed in 3.0
54
+ # Client Error.
55
+ 400: ("bad_request", "bad"),
56
+ 401: ("unauthorized",),
57
+ 402: ("payment_required", "payment"),
58
+ 403: ("forbidden",),
59
+ 404: ("not_found", "-o-"),
60
+ 405: ("method_not_allowed", "not_allowed"),
61
+ 406: ("not_acceptable",),
62
+ 407: ("proxy_authentication_required", "proxy_auth", "proxy_authentication"),
63
+ 408: ("request_timeout", "timeout"),
64
+ 409: ("conflict",),
65
+ 410: ("gone",),
66
+ 411: ("length_required",),
67
+ 412: ("precondition_failed", "precondition"),
68
+ 413: ("request_entity_too_large", "content_too_large"),
69
+ 414: ("request_uri_too_large", "uri_too_long"),
70
+ 415: ("unsupported_media_type", "unsupported_media", "media_type"),
71
+ 416: (
72
+ "requested_range_not_satisfiable",
73
+ "requested_range",
74
+ "range_not_satisfiable",
75
+ ),
76
+ 417: ("expectation_failed",),
77
+ 418: ("im_a_teapot", "teapot", "i_am_a_teapot"),
78
+ 421: ("misdirected_request",),
79
+ 422: ("unprocessable_entity", "unprocessable", "unprocessable_content"),
80
+ 423: ("locked",),
81
+ 424: ("failed_dependency", "dependency"),
82
+ 425: ("unordered_collection", "unordered", "too_early"),
83
+ 426: ("upgrade_required", "upgrade"),
84
+ 428: ("precondition_required", "precondition"),
85
+ 429: ("too_many_requests", "too_many"),
86
+ 431: ("header_fields_too_large", "fields_too_large"),
87
+ 444: ("no_response", "none"),
88
+ 449: ("retry_with", "retry"),
89
+ 450: ("blocked_by_windows_parental_controls", "parental_controls"),
90
+ 451: ("unavailable_for_legal_reasons", "legal_reasons"),
91
+ 499: ("client_closed_request",),
92
+ # Server Error.
93
+ 500: ("internal_server_error", "server_error", "/o\\", "✗"),
94
+ 501: ("not_implemented",),
95
+ 502: ("bad_gateway",),
96
+ 503: ("service_unavailable", "unavailable"),
97
+ 504: ("gateway_timeout",),
98
+ 505: ("http_version_not_supported", "http_version"),
99
+ 506: ("variant_also_negotiates",),
100
+ 507: ("insufficient_storage",),
101
+ 509: ("bandwidth_limit_exceeded", "bandwidth"),
102
+ 510: ("not_extended",),
103
+ 511: ("network_authentication_required", "network_auth", "network_authentication"),
104
+ }
105
+
106
+ codes: LookupDict[int] = LookupDict(name="status_codes")
107
+
108
+
109
+ def _init():
110
+ for code, titles in _codes.items():
111
+ for title in titles:
112
+ setattr(codes, title, code)
113
+ if not title.startswith(("\\", "/")):
114
+ setattr(codes, title.upper(), code)
115
+
116
+ def doc(code: int) -> str:
117
+ names = ", ".join(f"``{n}``" for n in _codes[code])
118
+ return "* %d: %s" % (code, names)
119
+
120
+ global __doc__
121
+ __doc__ = (
122
+ __doc__ + "\n" + "\n".join(doc(code) for code in sorted(_codes))
123
+ if __doc__ is not None
124
+ else None
125
+ )
126
+
127
+
128
+ _init()
data/diffusion/.venv/lib/python3.11/site-packages/requests/structures.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.structures
3
+ ~~~~~~~~~~~~~~~~~~~
4
+
5
+ Data structures that power Requests.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections import OrderedDict
11
+ from collections.abc import Iterable, Iterator, Mapping
12
+ from typing import Any, Generic, TypeVar, overload
13
+
14
+ from .compat import MutableMapping
15
+
16
+ _VT = TypeVar("_VT")
17
+ _D = TypeVar("_D")
18
+
19
+
20
+ class CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]):
21
+ """A case-insensitive ``dict``-like object.
22
+
23
+ Implements all methods and operations of
24
+ ``MutableMapping`` as well as dict's ``copy``. Also
25
+ provides ``lower_items``.
26
+
27
+ All keys are expected to be strings. The structure remembers the
28
+ case of the last key to be set, and ``iter(instance)``,
29
+ ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``
30
+ will contain case-sensitive keys. However, querying and contains
31
+ testing is case insensitive::
32
+
33
+ cid = CaseInsensitiveDict()
34
+ cid['Accept'] = 'application/json'
35
+ cid['aCCEPT'] == 'application/json' # True
36
+ list(cid) == ['Accept'] # True
37
+
38
+ For example, ``headers['content-encoding']`` will return the
39
+ value of a ``'Content-Encoding'`` response header, regardless
40
+ of how the header name was originally stored.
41
+
42
+ If the constructor, ``.update``, or equality comparison
43
+ operations are given keys that have equal ``.lower()``s, the
44
+ behavior is undefined.
45
+ """
46
+
47
+ _store: OrderedDict[str, tuple[str, _VT]]
48
+
49
+ def __init__(
50
+ self,
51
+ data: Mapping[str, _VT] | Iterable[tuple[str, _VT]] | None = None,
52
+ **kwargs: _VT,
53
+ ) -> None:
54
+ self._store = OrderedDict()
55
+ if data is None:
56
+ data = {}
57
+ self.update(data, **kwargs)
58
+
59
+ def __setitem__(self, key: str, value: _VT) -> None:
60
+ # Use the lowercased key for lookups, but store the actual
61
+ # key alongside the value.
62
+ self._store[key.lower()] = (key, value)
63
+
64
+ def __getitem__(self, key: str) -> _VT:
65
+ return self._store[key.lower()][1]
66
+
67
+ def __delitem__(self, key: str) -> None:
68
+ del self._store[key.lower()]
69
+
70
+ def __iter__(self) -> Iterator[str]:
71
+ return (casedkey for casedkey, _ in self._store.values())
72
+
73
+ def __len__(self) -> int:
74
+ return len(self._store)
75
+
76
+ def lower_items(self) -> Iterator[tuple[str, _VT]]:
77
+ """Like iteritems(), but with all lowercase keys."""
78
+ return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())
79
+
80
+ def __eq__(self, other: object) -> bool:
81
+ if isinstance(other, Mapping):
82
+ other_dict: CaseInsensitiveDict[Any] = CaseInsensitiveDict(other) # type: ignore[reportUnknownArgumentType]
83
+ else:
84
+ return NotImplemented
85
+ # Compare insensitively
86
+ return dict(self.lower_items()) == dict(other_dict.lower_items())
87
+
88
+ # Copy is required
89
+ def copy(self) -> CaseInsensitiveDict[_VT]:
90
+ return CaseInsensitiveDict(self._store.values())
91
+
92
+ def __repr__(self) -> str:
93
+ return str(dict(self.items()))
94
+
95
+
96
+ class LookupDict(dict[str, _VT]):
97
+ """Dictionary lookup object."""
98
+
99
+ name: Any
100
+
101
+ def __init__(self, name: Any = None) -> None:
102
+ self.name = name
103
+ super().__init__()
104
+
105
+ def __repr__(self) -> str:
106
+ return f"<lookup '{self.name}'>"
107
+
108
+ def __getattr__(self, key: str) -> _VT | None:
109
+ # We need this for type checkers to infer typing
110
+ # on attribute access with status_codes.py
111
+ if key in self.__dict__:
112
+ return self.__dict__[key]
113
+ else:
114
+ raise AttributeError(
115
+ f"'{type(self).__name__}' object has no attribute '{key}'"
116
+ )
117
+
118
+ def __getitem__(self, key: str) -> _VT | None: # type: ignore[override]
119
+ # We allow fall-through here, so values default to None
120
+
121
+ return self.__dict__.get(key, None)
122
+
123
+ @overload
124
+ def get(self, key: str, default: None = None) -> _VT | None: ...
125
+
126
+ @overload
127
+ def get(self, key: str, default: _D | _VT) -> _D | _VT: ...
128
+
129
+ def get(self, key: str, default: _D | None = None) -> _VT | _D | None:
130
+ return self.__dict__.get(key, default)
data/diffusion/.venv/lib/python3.11/site-packages/requests/utils.py ADDED
@@ -0,0 +1,1155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.utils
3
+ ~~~~~~~~~~~~~~
4
+
5
+ This module provides utility functions that are used within Requests
6
+ that are also useful for external consumption.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import codecs
12
+ import contextlib
13
+ import io
14
+ import os
15
+ import re
16
+ import socket
17
+ import struct
18
+ import sys
19
+ import tempfile
20
+ import warnings
21
+ import zipfile
22
+ from collections import OrderedDict
23
+ from collections.abc import Generator, Iterable
24
+ from typing import (
25
+ TYPE_CHECKING,
26
+ Any,
27
+ Final,
28
+ TypeVar,
29
+ cast,
30
+ overload,
31
+ )
32
+
33
+ from urllib3.util import make_headers, parse_url
34
+
35
+ from . import certs
36
+ from .__version__ import __version__
37
+
38
+ # to_native_string is unused here, but imported here for backwards compatibility
39
+ from ._internal_utils import ( # noqa: F401
40
+ _HEADER_VALIDATORS_BYTE, # type: ignore[reportPrivateUsage]
41
+ _HEADER_VALIDATORS_STR, # type: ignore[reportPrivateUsage]
42
+ HEADER_VALIDATORS, # type: ignore[reportUnusedImport]
43
+ to_native_string, # type: ignore[reportUnusedImport]
44
+ )
45
+ from ._types import SupportsItems as _SupportsItems
46
+ from .compat import (
47
+ Mapping,
48
+ bytes,
49
+ getproxies,
50
+ getproxies_environment,
51
+ integer_types,
52
+ is_urllib3_1,
53
+ proxy_bypass,
54
+ proxy_bypass_environment, # type: ignore[attr-defined] # https://github.com/python/cpython/issues/145331
55
+ quote,
56
+ str,
57
+ unquote,
58
+ urlparse,
59
+ urlunparse,
60
+ )
61
+ from .compat import parse_http_list as _parse_list_header
62
+ from .cookies import cookiejar_from_dict
63
+ from .exceptions import (
64
+ FileModeWarning,
65
+ InvalidHeader,
66
+ InvalidURL,
67
+ UnrewindableBodyError,
68
+ )
69
+ from .structures import CaseInsensitiveDict
70
+
71
+ if TYPE_CHECKING:
72
+ from http.cookiejar import CookieJar
73
+ from io import BufferedWriter
74
+
75
+ from . import _types as _t
76
+ from .models import PreparedRequest, Request, Response
77
+
78
+ NETRC_FILES: Final = (".netrc", "_netrc")
79
+
80
+
81
+ # Certificate is extracted by certifi when needed.
82
+ DEFAULT_CA_BUNDLE_PATH: str = certs.where()
83
+
84
+
85
+ DEFAULT_PORTS: Final = {"http": 80, "https": 443}
86
+
87
+ _KT = TypeVar("_KT")
88
+ _VT = TypeVar("_VT")
89
+
90
+ # Ensure that ', ' is used to preserve previous delimiter behavior.
91
+ DEFAULT_ACCEPT_ENCODING: Final = ", ".join(
92
+ re.split(r",\s*", make_headers(accept_encoding=True)["accept-encoding"])
93
+ )
94
+
95
+
96
+ if sys.platform == "win32":
97
+ # provide a proxy_bypass version on Windows without DNS lookups
98
+
99
+ def proxy_bypass_registry(host: str) -> bool:
100
+ try:
101
+ import winreg
102
+ except ImportError:
103
+ return False
104
+
105
+ try:
106
+ internetSettings = winreg.OpenKey(
107
+ winreg.HKEY_CURRENT_USER,
108
+ r"Software\Microsoft\Windows\CurrentVersion\Internet Settings",
109
+ )
110
+ # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it
111
+ proxyEnable = int(winreg.QueryValueEx(internetSettings, "ProxyEnable")[0])
112
+ # ProxyOverride is almost always a string
113
+ proxyOverride = winreg.QueryValueEx(internetSettings, "ProxyOverride")[0]
114
+ except (OSError, ValueError):
115
+ return False
116
+ if not proxyEnable or not proxyOverride:
117
+ return False
118
+
119
+ # make a check value list from the registry entry: replace the
120
+ # '<local>' string by the localhost entry and the corresponding
121
+ # canonical entry.
122
+ proxyOverride = proxyOverride.split(";")
123
+ # filter out empty strings to avoid re.match return true in the following code.
124
+ proxyOverride = filter(None, proxyOverride)
125
+ # now check if we match one of the registry values.
126
+ for test in proxyOverride:
127
+ if test == "<local>":
128
+ if "." not in host:
129
+ return True
130
+ test = test.replace(".", r"\.") # mask dots
131
+ test = test.replace("*", r".*") # change glob sequence
132
+ test = test.replace("?", r".") # change glob char
133
+ if re.match(test, host, re.I):
134
+ return True
135
+ return False
136
+
137
+ def proxy_bypass(host: str) -> bool: # noqa
138
+ """Return True, if the host should be bypassed.
139
+
140
+ Checks proxy settings gathered from the environment, if specified,
141
+ or the registry.
142
+ """
143
+ if getproxies_environment():
144
+ return proxy_bypass_environment(host)
145
+ else:
146
+ return proxy_bypass_registry(host)
147
+
148
+
149
+ def dict_to_sequence(
150
+ d: _t.SupportsItems[Any, Any] | Iterable[tuple[Any, Any]],
151
+ ) -> Iterable[tuple[Any, Any]]:
152
+ """Returns an internal sequence dictionary update."""
153
+
154
+ if isinstance(d, _SupportsItems):
155
+ return d.items()
156
+
157
+ return d
158
+
159
+
160
+ def super_len(o: Any) -> int:
161
+ total_length = None
162
+ current_position = 0
163
+
164
+ if not is_urllib3_1 and isinstance(o, str):
165
+ # urllib3 2.x+ treats all strings as utf-8 instead
166
+ # of latin-1 (iso-8859-1) like http.client.
167
+ o = o.encode("utf-8")
168
+
169
+ if hasattr(o, "__len__"):
170
+ total_length = len(o)
171
+
172
+ elif hasattr(o, "len"):
173
+ total_length = o.len
174
+
175
+ elif hasattr(o, "fileno"):
176
+ try:
177
+ fileno = o.fileno()
178
+ except (io.UnsupportedOperation, AttributeError):
179
+ # AttributeError is a surprising exception, seeing as how we've just checked
180
+ # that `hasattr(o, 'fileno')`. It happens for objects obtained via
181
+ # `Tarfile.extractfile()`, per issue 5229.
182
+ pass
183
+ else:
184
+ total_length = os.fstat(fileno).st_size
185
+
186
+ # Having used fstat to determine the file length, we need to
187
+ # confirm that this file was opened up in binary mode.
188
+ if "b" not in o.mode:
189
+ warnings.warn(
190
+ (
191
+ "Requests has determined the content-length for this "
192
+ "request using the binary size of the file: however, the "
193
+ "file has been opened in text mode (i.e. without the 'b' "
194
+ "flag in the mode). This may lead to an incorrect "
195
+ "content-length. In Requests 3.0, support will be removed "
196
+ "for files in text mode."
197
+ ),
198
+ FileModeWarning,
199
+ )
200
+
201
+ if hasattr(o, "tell"):
202
+ try:
203
+ current_position = o.tell()
204
+ except OSError:
205
+ # This can happen in some weird situations, such as when the file
206
+ # is actually a special file descriptor like stdin. In this
207
+ # instance, we don't know what the length is, so set it to zero and
208
+ # let requests chunk it instead.
209
+ if total_length is not None:
210
+ current_position = total_length
211
+ else:
212
+ if hasattr(o, "seek") and total_length is None:
213
+ # StringIO and BytesIO have seek but no usable fileno
214
+ try:
215
+ # seek to end of file
216
+ o.seek(0, 2)
217
+ total_length = o.tell()
218
+
219
+ # seek back to current position to support
220
+ # partially read file-like objects
221
+ o.seek(current_position or 0)
222
+ except OSError:
223
+ total_length = 0
224
+
225
+ if total_length is None:
226
+ total_length = 0
227
+
228
+ return max(0, total_length - current_position)
229
+
230
+
231
+ def get_netrc_auth(
232
+ url: _t.UriType, raise_errors: bool = False
233
+ ) -> tuple[str, str] | None:
234
+ """Returns the Requests tuple auth for a given url from netrc."""
235
+
236
+ if isinstance(url, bytes):
237
+ url = url.decode("utf-8")
238
+
239
+ netrc_file = os.environ.get("NETRC")
240
+ if netrc_file is not None:
241
+ netrc_locations = (netrc_file,)
242
+ else:
243
+ netrc_locations = (f"~/{f}" for f in NETRC_FILES)
244
+
245
+ try:
246
+ from netrc import NetrcParseError, netrc
247
+
248
+ netrc_path = None
249
+
250
+ for f in netrc_locations:
251
+ loc = os.path.expanduser(f)
252
+ if os.path.exists(loc):
253
+ netrc_path = loc
254
+ break
255
+
256
+ # Abort early if there isn't one.
257
+ if netrc_path is None:
258
+ return
259
+
260
+ ri = urlparse(url)
261
+ host = ri.hostname
262
+
263
+ if host is None:
264
+ return
265
+
266
+ try:
267
+ _netrc = netrc(netrc_path).authenticators(host)
268
+ if _netrc and any(_netrc):
269
+ # Return with login / password
270
+ login_i = 0 if _netrc[0] else 1
271
+ return (_netrc[login_i] or "", _netrc[2] or "")
272
+ except (NetrcParseError, OSError):
273
+ # If there was a parsing error or a permissions issue reading the file,
274
+ # we'll just skip netrc auth unless explicitly asked to raise errors.
275
+ if raise_errors:
276
+ raise
277
+
278
+ # App Engine hackiness.
279
+ except (ImportError, AttributeError):
280
+ pass
281
+
282
+
283
+ def guess_filename(obj: Any) -> str | None:
284
+ """Tries to guess the filename of the given object."""
285
+ name = getattr(obj, "name", None)
286
+ if name and isinstance(name, (str, bytes)) and name[0] != "<" and name[-1] != ">":
287
+ return os.path.basename(name) # type: ignore[return-value] # urllib3 accepts bytes but types str only
288
+
289
+
290
+ def extract_zipped_paths(path: str) -> str:
291
+ """Replace nonexistent paths that look like they refer to a member of a zip
292
+ archive with the location of an extracted copy of the target, or else
293
+ just return the provided path unchanged.
294
+ """
295
+ if os.path.exists(path):
296
+ # this is already a valid path, no need to do anything further
297
+ return path
298
+
299
+ # find the first valid part of the provided path and treat that as a zip archive
300
+ # assume the rest of the path is the name of a member in the archive
301
+ archive, member = os.path.split(path)
302
+ while archive and not os.path.exists(archive):
303
+ archive, prefix = os.path.split(archive)
304
+ if not prefix:
305
+ # If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split),
306
+ # we _can_ end up in an infinite loop on a rare corner case affecting a small number of users
307
+ break
308
+ member = "/".join([prefix, member])
309
+
310
+ if not zipfile.is_zipfile(archive):
311
+ return path
312
+
313
+ zip_file = zipfile.ZipFile(archive)
314
+ if member not in zip_file.namelist():
315
+ return path
316
+
317
+ # we have a valid zip archive and a valid member of that archive
318
+ suffix = os.path.splitext(member.split("/")[-1])[-1]
319
+ fd, extracted_path = tempfile.mkstemp(suffix=suffix)
320
+ try:
321
+ os.write(fd, zip_file.read(member))
322
+ finally:
323
+ os.close(fd)
324
+
325
+ return extracted_path
326
+
327
+
328
+ @contextlib.contextmanager
329
+ def atomic_open(filename: str) -> Generator[BufferedWriter, None, None]:
330
+ """Write a file to the disk in an atomic fashion"""
331
+ tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename))
332
+ try:
333
+ with os.fdopen(tmp_descriptor, "wb") as tmp_handler:
334
+ yield tmp_handler
335
+ os.replace(tmp_name, filename)
336
+ except BaseException:
337
+ os.remove(tmp_name)
338
+ raise
339
+
340
+
341
+ def from_key_val_list(
342
+ value: Mapping[Any, Any] | Iterable[tuple[Any, Any]] | None,
343
+ ) -> dict[Any, Any] | None:
344
+ """Take an object and test to see if it can be represented as a
345
+ dictionary. Unless it can not be represented as such, return an
346
+ OrderedDict, e.g.,
347
+
348
+ ::
349
+
350
+ >>> from_key_val_list([('key', 'val')])
351
+ OrderedDict([('key', 'val')])
352
+ >>> from_key_val_list('string')
353
+ Traceback (most recent call last):
354
+ ...
355
+ ValueError: cannot encode objects that are not 2-tuples
356
+ >>> from_key_val_list({'key': 'val'})
357
+ OrderedDict([('key', 'val')])
358
+
359
+ :rtype: OrderedDict
360
+ """
361
+ if value is None:
362
+ return None
363
+
364
+ if isinstance(value, (str, bytes, bool, int)):
365
+ raise ValueError("cannot encode objects that are not 2-tuples")
366
+
367
+ return OrderedDict(value)
368
+
369
+
370
+ @overload
371
+ def to_key_val_list(value: None) -> None: ...
372
+ @overload
373
+ def to_key_val_list(
374
+ value: _t.SupportsItems[_KT, _VT] | Iterable[tuple[_KT, _VT]],
375
+ ) -> list[tuple[_KT, _VT]]: ...
376
+ def to_key_val_list(
377
+ value: _t.SupportsItems[_KT, _VT] | Iterable[tuple[_KT, _VT]] | None,
378
+ ) -> list[tuple[_KT, _VT]] | None:
379
+ """Take an object and test to see if it can be represented as a
380
+ dictionary. If it can be, return a list of tuples, e.g.,
381
+
382
+ ::
383
+
384
+ >>> to_key_val_list([('key', 'val')])
385
+ [('key', 'val')]
386
+ >>> to_key_val_list({'key': 'val'})
387
+ [('key', 'val')]
388
+ >>> to_key_val_list('string')
389
+ Traceback (most recent call last):
390
+ ...
391
+ ValueError: cannot encode objects that are not 2-tuples
392
+
393
+ :rtype: list
394
+ """
395
+ if value is None:
396
+ return None
397
+
398
+ if isinstance(value, (str, bytes, bool, int)):
399
+ raise ValueError("cannot encode objects that are not 2-tuples")
400
+
401
+ if isinstance(value, _SupportsItems):
402
+ return list(value.items())
403
+
404
+ return list(value)
405
+
406
+
407
+ # From mitsuhiko/werkzeug (used with permission).
408
+ def parse_list_header(value: str) -> list[str]:
409
+ """Parse lists as described by RFC 2068 Section 2.
410
+
411
+ In particular, parse comma-separated lists where the elements of
412
+ the list may include quoted-strings. A quoted-string could
413
+ contain a comma. A non-quoted string could have quotes in the
414
+ middle. Quotes are removed automatically after parsing.
415
+
416
+ It basically works like :func:`parse_set_header` just that items
417
+ may appear multiple times and case sensitivity is preserved.
418
+
419
+ The return value is a standard :class:`list`:
420
+
421
+ >>> parse_list_header('token, "quoted value"')
422
+ ['token', 'quoted value']
423
+
424
+ To create a header from the :class:`list` again, use the
425
+ :func:`dump_header` function.
426
+
427
+ :param value: a string with a list header.
428
+ :return: :class:`list`
429
+ :rtype: list
430
+ """
431
+ result: list[str] = []
432
+ for item in _parse_list_header(value):
433
+ if item[:1] == item[-1:] == '"':
434
+ item = unquote_header_value(item[1:-1])
435
+ result.append(item)
436
+ return result
437
+
438
+
439
+ # From mitsuhiko/werkzeug (used with permission).
440
+ def parse_dict_header(value: str) -> dict[str, str | None]:
441
+ """Parse lists of key, value pairs as described by RFC 2068 Section 2 and
442
+ convert them into a python dict:
443
+
444
+ >>> d = parse_dict_header('foo="is a fish", bar="as well"')
445
+ >>> type(d) is dict
446
+ True
447
+ >>> sorted(d.items())
448
+ [('bar', 'as well'), ('foo', 'is a fish')]
449
+
450
+ If there is no value for a key it will be `None`:
451
+
452
+ >>> parse_dict_header('key_without_value')
453
+ {'key_without_value': None}
454
+
455
+ To create a header from the :class:`dict` again, use the
456
+ :func:`dump_header` function.
457
+
458
+ :param value: a string with a dict header.
459
+ :return: :class:`dict`
460
+ :rtype: dict
461
+ """
462
+ result: dict[str, str | None] = {}
463
+ for item in _parse_list_header(value):
464
+ if "=" not in item:
465
+ result[item] = None
466
+ continue
467
+ name, value = item.split("=", 1)
468
+ if value[:1] == value[-1:] == '"':
469
+ value = unquote_header_value(value[1:-1])
470
+ result[name] = value
471
+ return result
472
+
473
+
474
+ # From mitsuhiko/werkzeug (used with permission).
475
+ def unquote_header_value(value: str, is_filename: bool = False) -> str:
476
+ r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).
477
+ This does not use the real unquoting but what browsers are actually
478
+ using for quoting.
479
+
480
+ :param value: the header value to unquote.
481
+ :rtype: str
482
+ """
483
+ if value and value[0] == value[-1] == '"':
484
+ # this is not the real unquoting, but fixing this so that the
485
+ # RFC is met will result in bugs with internet explorer and
486
+ # probably some other browsers as well. IE for example is
487
+ # uploading files with "C:\foo\bar.txt" as filename
488
+ value = value[1:-1]
489
+
490
+ # if this is a filename and the starting characters look like
491
+ # a UNC path, then just return the value without quotes. Using the
492
+ # replace sequence below on a UNC path has the effect of turning
493
+ # the leading double slash into a single slash and then
494
+ # _fix_ie_filename() doesn't work correctly. See #458.
495
+ if not is_filename or value[:2] != "\\\\":
496
+ return value.replace("\\\\", "\\").replace('\\"', '"')
497
+ return value
498
+
499
+
500
+ def dict_from_cookiejar(cj: CookieJar) -> dict[str, str | None]:
501
+ """Returns a key/value dictionary from a CookieJar.
502
+
503
+ :param cj: CookieJar object to extract cookies from.
504
+ :rtype: dict
505
+ """
506
+
507
+ cookie_dict = {cookie.name: cookie.value for cookie in cj}
508
+ return cookie_dict
509
+
510
+
511
+ def add_dict_to_cookiejar(cj: CookieJar, cookie_dict: dict[str, str]) -> CookieJar:
512
+ """Returns a CookieJar from a key/value dictionary.
513
+
514
+ :param cj: CookieJar to insert cookies into.
515
+ :param cookie_dict: Dict of key/values to insert into CookieJar.
516
+ :rtype: CookieJar
517
+ """
518
+
519
+ return cookiejar_from_dict(cookie_dict, cj)
520
+
521
+
522
+ def get_encodings_from_content(content: str) -> list[str]:
523
+ """Returns encodings from given content string.
524
+
525
+ :param content: bytestring to extract encodings from.
526
+ """
527
+ warnings.warn(
528
+ (
529
+ "In requests 3.0, get_encodings_from_content will be removed. For "
530
+ "more information, please see the discussion on issue #2266. (This"
531
+ " warning should only appear once.)"
532
+ ),
533
+ DeprecationWarning,
534
+ )
535
+
536
+ charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
537
+ pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)
538
+ xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')
539
+
540
+ return (
541
+ charset_re.findall(content)
542
+ + pragma_re.findall(content)
543
+ + xml_re.findall(content)
544
+ )
545
+
546
+
547
+ def _parse_content_type_header(header: str) -> tuple[str, dict[str, Any]]:
548
+ """Returns content type and parameters from given header.
549
+
550
+ :param header: string
551
+ :return: tuple containing content type and dictionary of
552
+ parameters.
553
+ """
554
+
555
+ tokens = header.split(";")
556
+ content_type, params = tokens[0].strip(), tokens[1:]
557
+ params_dict: dict[str, str | bool] = {}
558
+ strip_chars = "\"' "
559
+
560
+ for param in params:
561
+ param = param.strip()
562
+ if param and (idx := param.find("=")) != -1:
563
+ key = param[:idx].strip(strip_chars)
564
+ value = param[idx + 1 :].strip(strip_chars)
565
+ params_dict[key.lower()] = value
566
+ return content_type, params_dict
567
+
568
+
569
+ def get_encoding_from_headers(headers: CaseInsensitiveDict[str]) -> str | None:
570
+ """Returns encodings from given HTTP Header Dict.
571
+
572
+ :param headers: dictionary to extract encoding from.
573
+ :rtype: str
574
+ """
575
+
576
+ content_type = headers.get("content-type")
577
+
578
+ if not content_type:
579
+ return None
580
+
581
+ content_type, params = _parse_content_type_header(content_type)
582
+
583
+ if "charset" in params:
584
+ return params["charset"].strip("'\"")
585
+
586
+ if "text" in content_type:
587
+ return "ISO-8859-1"
588
+
589
+ if "application/json" in content_type:
590
+ # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset
591
+ return "utf-8"
592
+
593
+
594
+ def stream_decode_response_unicode(
595
+ iterator: Iterable[bytes], r: Response
596
+ ) -> Generator[str | bytes, None, None]:
597
+ """Stream decodes an iterator."""
598
+
599
+ if r.encoding is None:
600
+ yield from iterator
601
+ return
602
+
603
+ decoder = codecs.getincrementaldecoder(r.encoding)(errors="replace")
604
+ for chunk in iterator:
605
+ rv = decoder.decode(chunk)
606
+ if rv:
607
+ yield rv
608
+ rv = decoder.decode(b"", final=True)
609
+ if rv:
610
+ yield rv
611
+
612
+
613
+ @overload
614
+ def iter_slices(
615
+ string: bytes, slice_length: int | None
616
+ ) -> Generator[bytes, None, None]: ...
617
+ @overload
618
+ def iter_slices(
619
+ string: str, slice_length: int | None
620
+ ) -> Generator[str, None, None]: ...
621
+ def iter_slices(
622
+ string: bytes | str, slice_length: int | None
623
+ ) -> Generator[bytes | str, None, None]:
624
+ """Iterate over slices of a string."""
625
+ pos = 0
626
+ if slice_length is None or slice_length <= 0:
627
+ slice_length = len(string)
628
+ while pos < len(string):
629
+ yield string[pos : pos + slice_length]
630
+ pos += slice_length
631
+
632
+
633
+ def get_unicode_from_response(r: Response) -> str | bytes | None:
634
+ """Returns the requested content back in unicode.
635
+
636
+ :param r: Response object to get unicode content from.
637
+
638
+ Tried:
639
+
640
+ 1. charset from content-type
641
+ 2. fall back and replace all unicode characters
642
+
643
+ :rtype: str
644
+ """
645
+ warnings.warn(
646
+ (
647
+ "In requests 3.0, get_unicode_from_response will be removed. For "
648
+ "more information, please see the discussion on issue #2266. (This"
649
+ " warning should only appear once.)"
650
+ ),
651
+ DeprecationWarning,
652
+ )
653
+ if r.content is None: # type: ignore[reportUnnecessaryComparison]
654
+ return None
655
+
656
+ tried_encodings: list[str] = []
657
+
658
+ # Try charset from content-type
659
+ encoding = get_encoding_from_headers(r.headers)
660
+
661
+ if encoding:
662
+ try:
663
+ return str(r.content, encoding)
664
+ except UnicodeError:
665
+ tried_encodings.append(encoding)
666
+
667
+ # Fall back:
668
+ try:
669
+ return str(r.content, encoding or "utf-8", errors="replace")
670
+ except TypeError:
671
+ return r.content
672
+
673
+
674
+ # The unreserved URI characters (RFC 3986)
675
+ UNRESERVED_SET: Final = frozenset(
676
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~"
677
+ )
678
+
679
+
680
+ def unquote_unreserved(uri: str) -> str:
681
+ """Un-escape any percent-escape sequences in a URI that are unreserved
682
+ characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
683
+
684
+ :rtype: str
685
+ """
686
+ parts = uri.split("%")
687
+ for i in range(1, len(parts)):
688
+ h = parts[i][0:2]
689
+ if len(h) == 2 and h.isalnum():
690
+ try:
691
+ c = chr(int(h, 16))
692
+ except ValueError:
693
+ raise InvalidURL(f"Invalid percent-escape sequence: '{h}'")
694
+
695
+ if c in UNRESERVED_SET:
696
+ parts[i] = c + parts[i][2:]
697
+ else:
698
+ parts[i] = f"%{parts[i]}"
699
+ else:
700
+ parts[i] = f"%{parts[i]}"
701
+ return "".join(parts)
702
+
703
+
704
+ def requote_uri(uri: str) -> str:
705
+ """Re-quote the given URI.
706
+
707
+ This function passes the given URI through an unquote/quote cycle to
708
+ ensure that it is fully and consistently quoted.
709
+
710
+ :rtype: str
711
+ """
712
+ safe_with_percent = "!#$%&'()*+,/:;=?@[]~"
713
+ safe_without_percent = "!#$&'()*+,/:;=?@[]~"
714
+ try:
715
+ # Unquote only the unreserved characters
716
+ # Then quote only illegal characters (do not quote reserved,
717
+ # unreserved, or '%')
718
+ return quote(unquote_unreserved(uri), safe=safe_with_percent)
719
+ except InvalidURL:
720
+ # We couldn't unquote the given URI, so let's try quoting it, but
721
+ # there may be unquoted '%'s in the URI. We need to make sure they're
722
+ # properly quoted so they do not cause issues elsewhere.
723
+ return quote(uri, safe=safe_without_percent)
724
+
725
+
726
+ def address_in_network(ip: str, net: str) -> bool:
727
+ """This function allows you to check if an IP belongs to a network subnet
728
+
729
+ Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
730
+ returns False if ip = 192.168.1.1 and net = 192.168.100.0/24
731
+
732
+ :rtype: bool
733
+ """
734
+ ipaddr = struct.unpack("=L", socket.inet_aton(ip))[0]
735
+ netaddr, bits = net.split("/")
736
+ netmask = struct.unpack("=L", socket.inet_aton(dotted_netmask(int(bits))))[0]
737
+ network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask
738
+ return (ipaddr & netmask) == (network & netmask)
739
+
740
+
741
+ def dotted_netmask(mask: int) -> str:
742
+ """Converts mask from /xx format to xxx.xxx.xxx.xxx
743
+
744
+ Example: if mask is 24 function returns 255.255.255.0
745
+
746
+ :rtype: str
747
+ """
748
+ bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1
749
+ return socket.inet_ntoa(struct.pack(">I", bits))
750
+
751
+
752
+ def is_ipv4_address(string_ip: str) -> bool:
753
+ """
754
+ :rtype: bool
755
+ """
756
+ try:
757
+ socket.inet_aton(string_ip)
758
+ except OSError:
759
+ return False
760
+ return True
761
+
762
+
763
+ def is_valid_cidr(string_network: str) -> bool:
764
+ """
765
+ Very simple check of the cidr format in no_proxy variable.
766
+
767
+ :rtype: bool
768
+ """
769
+ if string_network.count("/") == 1:
770
+ try:
771
+ mask = int(string_network.split("/")[1])
772
+ except ValueError:
773
+ return False
774
+
775
+ if mask < 1 or mask > 32:
776
+ return False
777
+
778
+ try:
779
+ socket.inet_aton(string_network.split("/")[0])
780
+ except OSError:
781
+ return False
782
+ else:
783
+ return False
784
+ return True
785
+
786
+
787
+ @contextlib.contextmanager
788
+ def set_environ(env_name: str, value: str | None) -> Generator[None, None, None]:
789
+ """Set the environment variable 'env_name' to 'value'
790
+
791
+ Save previous value, yield, and then restore the previous value stored in
792
+ the environment variable 'env_name'.
793
+
794
+ If 'value' is None, do nothing"""
795
+ value_changed = value is not None
796
+ old_value: str | None = None
797
+ if value_changed:
798
+ old_value = os.environ.get(env_name)
799
+ os.environ[env_name] = value
800
+ try:
801
+ yield
802
+ finally:
803
+ if value_changed:
804
+ if old_value is None:
805
+ del os.environ[env_name]
806
+ else:
807
+ os.environ[env_name] = old_value
808
+
809
+
810
+ def should_bypass_proxies(url: str, no_proxy: str | None) -> bool:
811
+ """
812
+ Returns whether we should bypass proxies or not.
813
+
814
+ :rtype: bool
815
+ """
816
+
817
+ # Prioritize lowercase environment variables over uppercase
818
+ # to keep a consistent behaviour with other http projects (curl, wget).
819
+ def get_proxy(key: str) -> str | None:
820
+ return os.environ.get(key) or os.environ.get(key.upper())
821
+
822
+ # First check whether no_proxy is defined. If it is, check that the URL
823
+ # we're getting isn't in the no_proxy list.
824
+ no_proxy_arg = no_proxy
825
+ if no_proxy is None:
826
+ no_proxy = get_proxy("no_proxy")
827
+ parsed = urlparse(url)
828
+ hostname = parsed.hostname
829
+
830
+ if hostname is None:
831
+ # URLs don't always have hostnames, e.g. file:/// urls.
832
+ return True
833
+
834
+ if no_proxy:
835
+ # We need to check whether we match here. We need to see if we match
836
+ # the end of the hostname, both with and without the port.
837
+ no_proxy_hosts = (host for host in no_proxy.replace(" ", "").split(",") if host)
838
+
839
+ if is_ipv4_address(hostname):
840
+ for proxy_ip in no_proxy_hosts:
841
+ if is_valid_cidr(proxy_ip):
842
+ if address_in_network(hostname, proxy_ip):
843
+ return True
844
+ elif hostname == proxy_ip:
845
+ # If no_proxy ip was defined in plain IP notation instead of cidr notation &
846
+ # matches the IP of the index
847
+ return True
848
+ else:
849
+ host_with_port = hostname
850
+ if parsed.port:
851
+ host_with_port += f":{parsed.port}"
852
+
853
+ for host in no_proxy_hosts:
854
+ host = host.lstrip(".")
855
+ if hostname == host or host_with_port == host:
856
+ return True
857
+ host = "." + host
858
+ if hostname.endswith(host) or host_with_port.endswith(host):
859
+ return True
860
+
861
+ with set_environ("no_proxy", no_proxy_arg):
862
+ try:
863
+ bypass = proxy_bypass(hostname)
864
+ except (TypeError, socket.gaierror):
865
+ bypass = False
866
+
867
+ if bypass:
868
+ return True
869
+
870
+ return False
871
+
872
+
873
+ def get_environ_proxies(url: str, no_proxy: str | None = None) -> dict[str, str]:
874
+ """
875
+ Return a dict of environment proxies.
876
+
877
+ :rtype: dict
878
+ """
879
+ if should_bypass_proxies(url, no_proxy=no_proxy):
880
+ return {}
881
+ else:
882
+ return getproxies()
883
+
884
+
885
+ def select_proxy(url: str, proxies: dict[str, str] | None) -> str | None:
886
+ """Select a proxy for the url, if applicable.
887
+
888
+ :param url: The url being for the request
889
+ :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
890
+ """
891
+ proxies = proxies or {}
892
+ urlparts = urlparse(url)
893
+ if urlparts.hostname is None:
894
+ return proxies.get(urlparts.scheme, proxies.get("all"))
895
+
896
+ proxy_keys = [
897
+ urlparts.scheme + "://" + urlparts.hostname,
898
+ urlparts.scheme,
899
+ "all://" + urlparts.hostname,
900
+ "all",
901
+ ]
902
+ proxy = None
903
+ for proxy_key in proxy_keys:
904
+ if proxy_key in proxies:
905
+ proxy = proxies[proxy_key]
906
+ break
907
+
908
+ return proxy
909
+
910
+
911
+ def resolve_proxies(
912
+ request: Request | PreparedRequest,
913
+ proxies: dict[str, str] | None,
914
+ trust_env: bool = True,
915
+ ) -> dict[str, str]:
916
+ """This method takes proxy information from a request and configuration
917
+ input to resolve a mapping of target proxies. This will consider settings
918
+ such as NO_PROXY to strip proxy configurations.
919
+
920
+ :param request: Request or PreparedRequest
921
+ :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
922
+ :param trust_env: Boolean declaring whether to trust environment configs
923
+
924
+ :rtype: dict
925
+ """
926
+ proxies = proxies if proxies is not None else {}
927
+ url = cast(str, request.url)
928
+ scheme = urlparse(url).scheme
929
+ no_proxy = proxies.get("no_proxy")
930
+ new_proxies = proxies.copy()
931
+
932
+ if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy):
933
+ environ_proxies = get_environ_proxies(url, no_proxy=no_proxy)
934
+
935
+ proxy = environ_proxies.get(scheme, environ_proxies.get("all"))
936
+
937
+ if proxy:
938
+ new_proxies.setdefault(scheme, proxy)
939
+ return new_proxies
940
+
941
+
942
+ def default_user_agent(name: str = "python-requests") -> str:
943
+ """
944
+ Return a string representing the default user agent.
945
+
946
+ :rtype: str
947
+ """
948
+ return f"{name}/{__version__}"
949
+
950
+
951
+ def default_headers() -> CaseInsensitiveDict[str]:
952
+ """
953
+ :rtype: requests.structures.CaseInsensitiveDict
954
+ """
955
+ return CaseInsensitiveDict(
956
+ {
957
+ "User-Agent": default_user_agent(),
958
+ "Accept-Encoding": DEFAULT_ACCEPT_ENCODING,
959
+ "Accept": "*/*",
960
+ "Connection": "keep-alive",
961
+ }
962
+ )
963
+
964
+
965
+ def parse_header_links(value: str) -> list[dict[str, str]]:
966
+ """Return a list of parsed link headers proxies.
967
+
968
+ i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"
969
+
970
+ :rtype: list
971
+ """
972
+
973
+ links: list[dict[str, str]] = []
974
+
975
+ replace_chars = " '\""
976
+
977
+ value = value.strip(replace_chars)
978
+ if not value:
979
+ return links
980
+
981
+ for val in re.split(", *<", value):
982
+ try:
983
+ url, params = val.split(";", 1)
984
+ except ValueError:
985
+ url, params = val, ""
986
+
987
+ link: dict[str, str] = {"url": url.strip("<> '\"")}
988
+
989
+ for param in params.split(";"):
990
+ try:
991
+ key, value = param.split("=")
992
+ except ValueError:
993
+ break
994
+
995
+ link[key.strip(replace_chars)] = value.strip(replace_chars)
996
+
997
+ links.append(link)
998
+
999
+ return links
1000
+
1001
+
1002
+ # Null bytes; no need to recreate these on each call to guess_json_utf
1003
+ _null = "\x00".encode("ascii") # encoding to ASCII for Python 3
1004
+ _null2 = _null * 2
1005
+ _null3 = _null * 3
1006
+
1007
+
1008
+ def guess_json_utf(data: bytes) -> str | None:
1009
+ """
1010
+ :rtype: str
1011
+ """
1012
+ # JSON always starts with two ASCII characters, so detection is as
1013
+ # easy as counting the nulls and from their location and count
1014
+ # determine the encoding. Also detect a BOM, if present.
1015
+ sample = data[:4]
1016
+ if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):
1017
+ return "utf-32" # BOM included
1018
+ if sample[:3] == codecs.BOM_UTF8:
1019
+ return "utf-8-sig" # BOM included, MS style (discouraged)
1020
+ if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):
1021
+ return "utf-16" # BOM included
1022
+ nullcount = sample.count(_null)
1023
+ if nullcount == 0:
1024
+ return "utf-8"
1025
+ if nullcount == 2:
1026
+ if sample[::2] == _null2: # 1st and 3rd are null
1027
+ return "utf-16-be"
1028
+ if sample[1::2] == _null2: # 2nd and 4th are null
1029
+ return "utf-16-le"
1030
+ # Did not detect 2 valid UTF-16 ascii-range characters
1031
+ if nullcount == 3:
1032
+ if sample[:3] == _null3:
1033
+ return "utf-32-be"
1034
+ if sample[1:] == _null3:
1035
+ return "utf-32-le"
1036
+ # Did not detect a valid UTF-32 ascii-range character
1037
+ return None
1038
+
1039
+
1040
+ def prepend_scheme_if_needed(url: str, new_scheme: str) -> str:
1041
+ """Given a URL that may or may not have a scheme, prepend the given scheme.
1042
+ Does not replace a present scheme with the one provided as an argument.
1043
+
1044
+ :rtype: str
1045
+ """
1046
+ parsed = parse_url(url)
1047
+ scheme, auth, _host, _port, path, query, fragment = parsed
1048
+
1049
+ # A defect in urlparse determines that there isn't a netloc present in some
1050
+ # urls. We previously assumed parsing was overly cautious, and swapped the
1051
+ # netloc and path. Due to a lack of tests on the original defect, this is
1052
+ # maintained with parse_url for backwards compatibility.
1053
+ netloc = parsed.netloc
1054
+ if not netloc:
1055
+ netloc, path = path, netloc
1056
+
1057
+ if auth:
1058
+ # parse_url doesn't provide the netloc with auth
1059
+ # so we'll add it ourselves.
1060
+ netloc = cast(str, netloc)
1061
+ netloc = "@".join([auth, netloc])
1062
+ if scheme is None:
1063
+ scheme = new_scheme
1064
+ if path is None:
1065
+ path = ""
1066
+
1067
+ return urlunparse((scheme, netloc, path, "", query, fragment))
1068
+
1069
+
1070
+ def get_auth_from_url(url: str) -> tuple[str, str]:
1071
+ """Given a url with authentication components, extract them into a tuple of
1072
+ username,password.
1073
+
1074
+ :rtype: (str,str)
1075
+ """
1076
+ parsed = urlparse(url)
1077
+
1078
+ try:
1079
+ # except handles parsed.username/password being None
1080
+ auth = (unquote(parsed.username), unquote(parsed.password)) # type: ignore[arg-type]
1081
+ except (AttributeError, TypeError):
1082
+ auth = ("", "")
1083
+
1084
+ return auth
1085
+
1086
+
1087
+ def check_header_validity(header: tuple[str | bytes, str | bytes]) -> None:
1088
+ """Verifies that header parts don't contain leading whitespace
1089
+ reserved characters, or return characters.
1090
+
1091
+ :param header: tuple, in the format (name, value).
1092
+ """
1093
+ name, value = header
1094
+ _validate_header_part(header, name, 0)
1095
+ _validate_header_part(header, value, 1)
1096
+
1097
+
1098
+ def _validate_header_part(
1099
+ header: tuple[str | bytes, str | bytes],
1100
+ header_part: str | bytes,
1101
+ header_validator_index: int,
1102
+ ) -> None:
1103
+ if isinstance(header_part, str):
1104
+ validator = _HEADER_VALIDATORS_STR[header_validator_index]
1105
+ elif isinstance(header_part, bytes): # type: ignore[reportUnnecessaryIsInstance]
1106
+ # runtime guard for non-str/bytes input
1107
+ validator = _HEADER_VALIDATORS_BYTE[header_validator_index]
1108
+ else:
1109
+ raise InvalidHeader(
1110
+ f"Header part ({header_part!r}) from {header} "
1111
+ f"must be of type str or bytes, not {type(header_part)}"
1112
+ )
1113
+
1114
+ if not validator.match(header_part): # type: ignore[arg-type]
1115
+ header_kind = "name" if header_validator_index == 0 else "value"
1116
+ raise InvalidHeader(
1117
+ f"Invalid leading whitespace, reserved character(s), or return "
1118
+ f"character(s) in header {header_kind}: {header_part!r}"
1119
+ )
1120
+
1121
+
1122
+ def urldefragauth(url: str) -> str:
1123
+ """
1124
+ Given a url remove the fragment and the authentication part.
1125
+
1126
+ :rtype: str
1127
+ """
1128
+ scheme, netloc, path, params, query, _fragment = urlparse(url)
1129
+
1130
+ # see func:`prepend_scheme_if_needed`
1131
+ if not netloc:
1132
+ netloc, path = path, netloc
1133
+
1134
+ netloc = netloc.rsplit("@", 1)[-1]
1135
+
1136
+ return urlunparse((scheme, netloc, path, params, query, ""))
1137
+
1138
+
1139
+ def rewind_body(prepared_request: PreparedRequest) -> None:
1140
+ """Move file pointer back to its recorded starting position
1141
+ so it can be read again on redirect.
1142
+ """
1143
+ body_seek = getattr(prepared_request.body, "seek", None)
1144
+ if body_seek is not None and isinstance(
1145
+ prepared_request._body_position, # type: ignore[reportPrivateUsage]
1146
+ integer_types,
1147
+ ):
1148
+ try:
1149
+ body_seek(prepared_request._body_position) # type: ignore[reportPrivateUsage]
1150
+ except OSError:
1151
+ raise UnrewindableBodyError(
1152
+ "An error occurred when rewinding request body for redirect."
1153
+ )
1154
+ else:
1155
+ raise UnrewindableBodyError("Unable to rewind request body for redirect.")
data/diffusion/.venv/lib/python3.11/site-packages/setuptools-83.0.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ uv
data/diffusion/.venv/lib/python3.11/site-packages/setuptools-83.0.0.dist-info/METADATA ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: setuptools
3
+ Version: 83.0.0
4
+ Summary: Most extensible Python build backend with support for C/C++ extension modules
5
+ Author-email: Python Packaging Authority <distutils-sig@python.org>
6
+ License-Expression: MIT
7
+ Project-URL: Source, https://github.com/pypa/setuptools
8
+ Project-URL: Documentation, https://setuptools.pypa.io/
9
+ Project-URL: Changelog, https://setuptools.pypa.io/en/stable/history.html
10
+ Keywords: CPAN PyPI distutils eggs package management
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
16
+ Classifier: Topic :: System :: Archiving :: Packaging
17
+ Classifier: Topic :: System :: Systems Administration
18
+ Classifier: Topic :: Utilities
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/x-rst
21
+ License-File: LICENSE
22
+ Provides-Extra: test
23
+ Requires-Dist: pytest!=8.1.*,>=6; extra == "test"
24
+ Requires-Dist: virtualenv>=13.0.0; extra == "test"
25
+ Requires-Dist: wheel>=0.44.0; extra == "test"
26
+ Requires-Dist: pip>=19.1; extra == "test"
27
+ Requires-Dist: packaging>=24.2; extra == "test"
28
+ Requires-Dist: jaraco.envs>=2.2; extra == "test"
29
+ Requires-Dist: pytest-xdist>=3; extra == "test"
30
+ Requires-Dist: jaraco.path>=3.7.2; extra == "test"
31
+ Requires-Dist: build[virtualenv]>=1.0.3; extra == "test"
32
+ Requires-Dist: filelock>=3.4.0; extra == "test"
33
+ Requires-Dist: ini2toml[lite]>=0.14; extra == "test"
34
+ Requires-Dist: tomli-w>=1.0.0; extra == "test"
35
+ Requires-Dist: pytest-timeout; extra == "test"
36
+ Requires-Dist: pytest-perf; sys_platform != "cygwin" and extra == "test"
37
+ Requires-Dist: jaraco.develop>=7.21; (python_version >= "3.9" and sys_platform != "cygwin") and extra == "test"
38
+ Requires-Dist: pytest-home>=0.5; extra == "test"
39
+ Requires-Dist: pytest-subprocess; extra == "test"
40
+ Requires-Dist: pyproject-hooks!=1.1; extra == "test"
41
+ Requires-Dist: jaraco.test>=5.5; extra == "test"
42
+ Provides-Extra: doc
43
+ Requires-Dist: sphinx>=3.5; extra == "doc"
44
+ Requires-Dist: jaraco.packaging>=9.3; extra == "doc"
45
+ Requires-Dist: rst.linker>=1.9; extra == "doc"
46
+ Requires-Dist: furo; extra == "doc"
47
+ Requires-Dist: sphinx-lint; extra == "doc"
48
+ Requires-Dist: jaraco.tidelift>=1.4; extra == "doc"
49
+ Requires-Dist: pygments-github-lexers==0.0.5; extra == "doc"
50
+ Requires-Dist: sphinx-favicon; extra == "doc"
51
+ Requires-Dist: sphinx-inline-tabs; extra == "doc"
52
+ Requires-Dist: sphinx-reredirects; extra == "doc"
53
+ Requires-Dist: sphinxcontrib-towncrier; extra == "doc"
54
+ Requires-Dist: sphinx-notfound-page<2,>=1; extra == "doc"
55
+ Requires-Dist: pyproject-hooks!=1.1; extra == "doc"
56
+ Requires-Dist: towncrier<24.7; extra == "doc"
57
+ Provides-Extra: ssl
58
+ Provides-Extra: certs
59
+ Provides-Extra: core
60
+ Requires-Dist: packaging>=24.2; extra == "core"
61
+ Requires-Dist: more_itertools>=8.8; extra == "core"
62
+ Requires-Dist: jaraco.text>=3.7; extra == "core"
63
+ Requires-Dist: importlib_metadata>=6; python_version < "3.10" and extra == "core"
64
+ Requires-Dist: tomli>=2.0.1; python_version < "3.11" and extra == "core"
65
+ Requires-Dist: wheel>=0.43.0; extra == "core"
66
+ Requires-Dist: jaraco.functools>=4; extra == "core"
67
+ Requires-Dist: more_itertools; extra == "core"
68
+ Provides-Extra: check
69
+ Requires-Dist: pytest-checkdocs>=2.14; extra == "check"
70
+ Requires-Dist: pytest-ruff>=0.2.1; sys_platform != "cygwin" and extra == "check"
71
+ Requires-Dist: ruff>=0.13.0; sys_platform != "cygwin" and extra == "check"
72
+ Provides-Extra: cover
73
+ Requires-Dist: pytest-cov; extra == "cover"
74
+ Provides-Extra: enabler
75
+ Requires-Dist: pytest-enabler>=3.4; extra == "enabler"
76
+ Provides-Extra: type
77
+ Requires-Dist: pytest-mypy>=1.0.1; platform_python_implementation != "PyPy" and extra == "type"
78
+ Requires-Dist: mypy==1.18.*; extra == "type"
79
+ Requires-Dist: importlib_metadata>=7.0.2; python_version < "3.10" and extra == "type"
80
+ Requires-Dist: jaraco.develop>=7.21; sys_platform != "cygwin" and extra == "type"
81
+ Dynamic: license-file
82
+
83
+ .. |pypi-version| image:: https://img.shields.io/pypi/v/setuptools.svg
84
+ :target: https://pypi.org/project/setuptools
85
+
86
+ .. |py-version| image:: https://img.shields.io/pypi/pyversions/setuptools.svg
87
+
88
+ .. |test-badge| image:: https://github.com/pypa/setuptools/actions/workflows/main.yml/badge.svg
89
+ :target: https://github.com/pypa/setuptools/actions?query=workflow%3A%22tests%22
90
+ :alt: tests
91
+
92
+ .. |ruff-badge| image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json
93
+ :target: https://github.com/astral-sh/ruff
94
+ :alt: Ruff
95
+
96
+ .. |docs-badge| image:: https://img.shields.io/readthedocs/setuptools/latest.svg
97
+ :target: https://setuptools.pypa.io
98
+
99
+ .. |skeleton-badge| image:: https://img.shields.io/badge/skeleton-2026-informational
100
+ :target: https://blog.jaraco.com/skeleton
101
+
102
+ .. |codecov-badge| image:: https://img.shields.io/codecov/c/github/pypa/setuptools/master.svg?logo=codecov&logoColor=white
103
+ :target: https://codecov.io/gh/pypa/setuptools
104
+
105
+ .. |tidelift-badge| image:: https://tidelift.com/badges/github/pypa/setuptools?style=flat
106
+ :target: https://tidelift.com/subscription/pkg/pypi-setuptools?utm_source=pypi-setuptools&utm_medium=readme
107
+
108
+ .. |discord-badge| image:: https://img.shields.io/discord/803025117553754132
109
+ :target: https://discord.com/channels/803025117553754132/815945031150993468
110
+ :alt: Discord
111
+
112
+ |pypi-version| |py-version| |test-badge| |ruff-badge| |docs-badge| |skeleton-badge| |codecov-badge| |discord-badge|
113
+
114
+ See the `Quickstart <https://setuptools.pypa.io/en/latest/userguide/quickstart.html>`_
115
+ and the `User's Guide <https://setuptools.pypa.io/en/latest/userguide/>`_ for
116
+ instructions on how to use Setuptools.
117
+
118
+ Questions and comments should be directed to `GitHub Discussions
119
+ <https://github.com/pypa/setuptools/discussions>`_.
120
+ Bug reports and especially tested patches may be
121
+ submitted directly to the `bug tracker
122
+ <https://github.com/pypa/setuptools/issues>`_.
123
+
124
+
125
+ Code of Conduct
126
+ ===============
127
+
128
+ Everyone interacting in the setuptools project's codebases, issue trackers,
129
+ chat rooms, and fora is expected to follow the
130
+ `PSF Code of Conduct <https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md>`_.
131
+
132
+
133
+ For Enterprise
134
+ ==============
135
+
136
+ Available as part of the Tidelift Subscription.
137
+
138
+ Setuptools and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.
139
+
140
+ `Learn more <https://tidelift.com/subscription/pkg/pypi-setuptools?utm_source=pypi-setuptools&utm_medium=referral&utm_campaign=github>`_.
data/diffusion/.venv/lib/python3.11/site-packages/setuptools-83.0.0.dist-info/RECORD ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ _distutils_hack/__init__.py,sha256=34HmvLo07j45Uvd2VR-2aRQ7lJD91sTK6zJgn5fphbQ,6755
2
+ _distutils_hack/override.py,sha256=Eu_s-NF6VIZ4Cqd0tbbA5wtWky2IZPNd8et6GLt1mzo,44
3
+ distutils-precedence.pth,sha256=JjjOniUA5XKl4N5_rtZmHrVp0baW_LoHsN0iPaX10iQ,151
4
+ setuptools-83.0.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
5
+ setuptools-83.0.0.dist-info/METADATA,sha256=JuRekN52PGk42T0d8uzWeCoPFRTUHL0i6-9OCrZHV3E,6581
6
+ setuptools-83.0.0.dist-info/RECORD,,
7
+ setuptools-83.0.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ setuptools-83.0.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
9
+ setuptools-83.0.0.dist-info/entry_points.txt,sha256=zkgthpf_Fa9NVE9p6FKT3Xk9DR1faAcRU4coggsV7jA,2449
10
+ setuptools-83.0.0.dist-info/licenses/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023
11
+ setuptools-83.0.0.dist-info/top_level.txt,sha256=Wsln-wPBdc8NXLNXsnCRyTXUhGi0mUw_l0ZVThaim-I,27
12
+ setuptools/__init__.py,sha256=-UtTG9pdeEZkYiIFT69RckMCqxUdVILjj24g3qeJ_rc,9521
13
+ setuptools/_core_metadata.py,sha256=T7Tjp-WSoN881adev3R1wzXCPnkDHqbC2MgylN1yjS8,11978
14
+ setuptools/_discovery.py,sha256=HxEpgYQ8zUaLOOSp8JIA4y2Mdvn9ysVxspPT-ppfzM4,836
15
+ setuptools/_distutils/__init__.py,sha256=xGYuhWwLG07J0Q49BVnEjPy6wyDcd6veJMDJX7ljlyM,359
16
+ setuptools/_distutils/_log.py,sha256=i-lNTTcXS8TmWITJ6DODGvtW5z5tMattJQ76h8rZxQU,42
17
+ setuptools/_distutils/_macos_compat.py,sha256=JzUGhF4E5yIITHbUaPobZEWjGHdrrcNV63z86S4RjBc,239
18
+ setuptools/_distutils/_modified.py,sha256=rj--YOajClmXe2tVmc3Idl7RJflswHUazY2g4QSGEG0,3225
19
+ setuptools/_distutils/_msvccompiler.py,sha256=9PSfSHxvJnHnQL6Sqz4Xcz7iaBIT62p6BheQzGsSlwo,335
20
+ setuptools/_distutils/archive_util.py,sha256=dDZjw4BwhNIyt20hHlrIely4WSiN20HVTGdaPRKGI0o,8484
21
+ setuptools/_distutils/ccompiler.py,sha256=FKVjqzGJ7c-FtouNjhLiaMPm5LKMZHHAruXf8LU216c,524
22
+ setuptools/_distutils/cmd.py,sha256=lzqM-3rwYJNUhJiCYOv04aeUPenym2vyOndFPEOdZgo,21344
23
+ setuptools/_distutils/command/__init__.py,sha256=GfFAzbBqk1qxSH4BdaKioKS4hRRnD44BAmwEN85C4u8,386
24
+ setuptools/_distutils/command/_framework_compat.py,sha256=0iZdSJYzGRWCCvzRDKE-R0-_yaAYvFMd1ylXb2eYXug,1609
25
+ setuptools/_distutils/command/bdist.py,sha256=jWtk61R7fWNUUNxJV0thTZzU5n80L3Ay1waSiP9kiLA,5854
26
+ setuptools/_distutils/command/bdist_dumb.py,sha256=FF0FpuC3IgFpOjJ1ub3hGU5ERFMBnJOiUjrAI-u4auw,4609
27
+ setuptools/_distutils/command/bdist_rpm.py,sha256=WRRB3k65qubgZO6zwiRMpaEEuG391mju_iJDRJTPvT8,21672
28
+ setuptools/_distutils/command/build.py,sha256=uKrnZ4aY_J5uK9qx9HlF1ET-jQ9kg_7P0boh5q-GOwk,5955
29
+ setuptools/_distutils/command/build_clib.py,sha256=6u-R8qjmWr6FPECuzDoAyVl1xRBtuEmXJZ2cz2Zk2zg,7733
30
+ setuptools/_distutils/command/build_ext.py,sha256=fliT4b7g8-LHEdTf2DmG4Fy4Pb_-8iqJAuvZm9SImuk,32690
31
+ setuptools/_distutils/command/build_py.py,sha256=BAJI_X9QlfiTyokU3ZgfDnsy3Xn6aWdxl2T_lToagbk,16606
32
+ setuptools/_distutils/command/build_scripts.py,sha256=UKhGKyXLjGCAQoQVfP2t-DnlMaUVjcXWac6UCs6GWMI,4833
33
+ setuptools/_distutils/command/check.py,sha256=yoNe2MPY4JcTM7rwoIQdfZ75q5Ri058I2coi-Gq9CjM,4946
34
+ setuptools/_distutils/command/clean.py,sha256=UWkfAMmpOZGl0_PjiZJFdyLV2yzGnoimygF8fka907I,2551
35
+ setuptools/_distutils/command/config.py,sha256=zE7F8mSQavwiZwNZj8WtrF6T92lt-K1dUNq9rYIQpgc,12206
36
+ setuptools/_distutils/command/install.py,sha256=J2r3rmOTRrHqqcXnZCNaM8_IFwZdYLxf445wvQSLWmI,30164
37
+ setuptools/_distutils/command/install_data.py,sha256=GzBlUWWKubTYJlP-L0auUriq9cL-5RKOcoyHTttKj0Q,2875
38
+ setuptools/_distutils/command/install_egg_info.py,sha256=joDxOJuq03SdJLh8KDm8EM-yQ4sEqB8ywPZSbduFHp4,2809
39
+ setuptools/_distutils/command/install_headers.py,sha256=5ciKCj8c3XKsYNKdkdMvnypaUCKcoWCDeeZij3fD-Z4,1272
40
+ setuptools/_distutils/command/install_lib.py,sha256=3VQc5P06dv-1QVl8G-raVpTD-bMlPTj1c3NE7adJiyk,8512
41
+ setuptools/_distutils/command/install_scripts.py,sha256=CTzga_-kEjYWguL-Dg_GP83Jax6uw2VnFFwlR8XoAls,1877
42
+ setuptools/_distutils/command/sdist.py,sha256=XGEO5UMznLzPT-F3ftbryqkMsMWLKd15tjObiZJsm8k,19107
43
+ setuptools/_distutils/compat/__init__.py,sha256=J20aXGjJ86Rg41xFLIWlcWCgZ9edMdJ9vvdNEQ87vPQ,522
44
+ setuptools/_distutils/compat/numpy.py,sha256=UFgneZw9w97g4c-yGoAIOyLxUOWQ-fPRIhhfMs7_Ouc,167
45
+ setuptools/_distutils/compat/py39.py,sha256=NXgFEy_rymlIwu5_WeDLWkeNOxhQVopK1Mpu3CZDdRs,1978
46
+ setuptools/_distutils/compilers/C/base.py,sha256=UkeeKLSmn-y8K2duisw4ipYP3jUTE_fnuik2UOBMQwk,54534
47
+ setuptools/_distutils/compilers/C/cygwin.py,sha256=wH_vcKwAo2HNnR53XAP9UKzCx_dfMGkyHax2V8xMiLI,11874
48
+ setuptools/_distutils/compilers/C/errors.py,sha256=sKOVzJajMUmNdfywo9UM_QQGsKFcclDhtI5TlCiXMLc,573
49
+ setuptools/_distutils/compilers/C/msvc.py,sha256=rtvBT3nU0VGex_gUhbXmWXPyKDmAiYvoX1IO9eKjiBE,21403
50
+ setuptools/_distutils/compilers/C/py.typed,sha256=nrME4EaXuuTqS3HWNQLSNmx5zeTdr2sGKi3042dIvrg,97
51
+ setuptools/_distutils/compilers/C/tests/test_base.py,sha256=dU3cD_dHOWwarcK_VyreXez4TQbPXDaBS8SoSB6h0ic,2715
52
+ setuptools/_distutils/compilers/C/tests/test_cygwin.py,sha256=UgV2VgUXj3VulcbDc0UBWfEyJDx42tgSwS4LzHix3mY,2701
53
+ setuptools/_distutils/compilers/C/tests/test_mingw.py,sha256=hCmwyywISpRoyOySbFHBL4TprWRV0mUWDKmOLO8XBXE,1900
54
+ setuptools/_distutils/compilers/C/tests/test_msvc.py,sha256=DlGjmZ1mBSMXIgmlu80BKc7V-EJOZuYucwJwFh5dn28,4151
55
+ setuptools/_distutils/compilers/C/tests/test_unix.py,sha256=AyadWw1fR-UeDl2TvIbYBzOJVHkpE_oRRQ3JTJWqaEA,14642
56
+ setuptools/_distutils/compilers/C/unix.py,sha256=flWnxjaOTl6KNd9PyCIcXNkTxLzYwpUn1ISKs4p_KD0,16475
57
+ setuptools/_distutils/compilers/C/zos.py,sha256=WnGA_PR51_FP89wKbl85_2rcLA28BIKbeG5rPZ7JUig,6568
58
+ setuptools/_distutils/core.py,sha256=GEHKaFC48T3o-_SmH4864GvKyx1IgbVC6ISIPVlx7a4,9364
59
+ setuptools/_distutils/cygwinccompiler.py,sha256=mG_cU8SVZ4amD_VtF5vH6BXP0-kghGsDPbDSXrQ963c,594
60
+ setuptools/_distutils/debug.py,sha256=N6MrTAqK6l9SVk6tWweR108PM8Ol7qNlfyV-nHcLhsY,139
61
+ setuptools/_distutils/dep_util.py,sha256=xN75p6ZpHhMiHEc-rpL2XilJQynHnDNiafHteaZ4tjU,349
62
+ setuptools/_distutils/dir_util.py,sha256=1i-puqc3g8sTggEPX6NSuqNtGSNEdSy-Qw9qQfC3PSo,6864
63
+ setuptools/_distutils/dist.py,sha256=apNnfX7RivvWNKgipMe-U3iBP_CCZPXCTjAJ9uzaMqI,55688
64
+ setuptools/_distutils/errors.py,sha256=PPE2oDRh5y9Q1beKK9rhdvDaCzQhi4HCXs4KcqfqgZY,3092
65
+ setuptools/_distutils/extension.py,sha256=Foyu4gULcPqm1_U9zrYYHxNk4NqglXv1rbsOk_QrSds,11155
66
+ setuptools/_distutils/fancy_getopt.py,sha256=_3TETVjeO5wmV5r1U-cOwZsyxRo0LoTltyOkjyDcM4c,17908
67
+ setuptools/_distutils/file_util.py,sha256=O3hNtKxcs4jhCdOtGN23wIrLSvMwoRmMV2caEeXbvdU,7811
68
+ setuptools/_distutils/filelist.py,sha256=MBeSRJmPcKmDv8ooZgSU4BiQPZ0Khwv8l_jhD50XycI,15337
69
+ setuptools/_distutils/log.py,sha256=VyBs5j7z4-K6XTEEBThUc9HyMpoPLGtQpERqbz5ylww,1200
70
+ setuptools/_distutils/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
71
+ setuptools/_distutils/spawn.py,sha256=sPnZ3Q3gsBzNBB2zsbfFxzkHJ-AveB6lyK9YqBHQiIw,3963
72
+ setuptools/_distutils/sysconfig.py,sha256=KeI8OHbMuEzHJ8Q0cBez9KZny8iRy6Z6Y0AkMz1jlsU,19728
73
+ setuptools/_distutils/tests/__init__.py,sha256=j-IoPZEtQv3EOPuqNTwalr6GLyRjzCC-OOaNvZzmHsI,1485
74
+ setuptools/_distutils/tests/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
75
+ setuptools/_distutils/tests/compat/py39.py,sha256=saDvmdTwUXGSVTeZV3IZ_mMSaSOL3xH1sXUm4ZJXQAA,450
76
+ setuptools/_distutils/tests/support.py,sha256=tjsYsyxvpTK4NrkCseh2ujvDIGV0Mf_b5SI5fP2T0yM,4099
77
+ setuptools/_distutils/tests/test_archive_util.py,sha256=VaXLjV8kup-Z6rIVXCBW7u21pubcAH_R3hEtSmS81Xs,11441
78
+ setuptools/_distutils/tests/test_bdist.py,sha256=xNHxUsLlHsZQRwkzLb_iSD24s-9Mk-NX2ffBWwOyPyc,1396
79
+ setuptools/_distutils/tests/test_bdist_dumb.py,sha256=QF05MHNhPOdZyh88Xpw8KsO64s7pRFkl8KL-RoV4XK0,2247
80
+ setuptools/_distutils/tests/test_bdist_rpm.py,sha256=Hdm-pwWgyaoGdGbEcGZa8cRhGU45y8gHK8umOanTjik,3932
81
+ setuptools/_distutils/tests/test_build.py,sha256=JJY5XpOZco25ZY0pstxl-iI8mHsWP0ujf5o8aOtuZYY,1742
82
+ setuptools/_distutils/tests/test_build_clib.py,sha256=Mo1ZFb4C1VXBYOGvnallwN7YCnTtr24akLDO8Zi4CsY,4331
83
+ setuptools/_distutils/tests/test_build_ext.py,sha256=QFO9qYVhWWdJu17HXc4x9RMnLZlhk0lAHi9HVppbuX4,22545
84
+ setuptools/_distutils/tests/test_build_py.py,sha256=NsfmRrojOHBXNMqWR_mp5g4PLTgjhD7iZFUffGZFIdw,6882
85
+ setuptools/_distutils/tests/test_build_scripts.py,sha256=cD-FRy-oX55sXRX5Ez5xQCaeHrWajyKc4Xuwv2fe48w,2880
86
+ setuptools/_distutils/tests/test_check.py,sha256=p1Bx-MUmaoc4hp3lHUJRXPlIh-KdxKnz6RVbFAHgRe4,6628
87
+ setuptools/_distutils/tests/test_clean.py,sha256=hPH6jfIpGFUrvWbF1txkiNVSNaAxt2wq5XjV499zO4E,1240
88
+ setuptools/_distutils/tests/test_cmd.py,sha256=bgRB79mitoOKR1OiyZHnCogvGxt3pWkxeTqIC04lQWQ,3254
89
+ setuptools/_distutils/tests/test_config_cmd.py,sha256=Zs6WX0IfxDvmuC19XzuVNnYCnTr9Y-hl73TAmDSBN4Y,2664
90
+ setuptools/_distutils/tests/test_core.py,sha256=L7XKVAxa-MGoAZeANopnuK9fRKneYhkSQpgw8XQvcF8,3829
91
+ setuptools/_distutils/tests/test_dir_util.py,sha256=E84lC-k4riVUwURyWaQ0Jqx2ui2-io-0RuJa3M7qkJs,4500
92
+ setuptools/_distutils/tests/test_dist.py,sha256=a6wlc5fQJd5qQ6HOndzcupNhjTxvj6-_JLtpuYvaP1M,18793
93
+ setuptools/_distutils/tests/test_extension.py,sha256=-YejLgZCuycFrOBd64pVH0JvwMc9NwhzHvQxvvjXHqk,3670
94
+ setuptools/_distutils/tests/test_file_util.py,sha256=livjnl3FkilQlrB2rFdFQq9nvjEVZHynNya0bfzv_b4,3522
95
+ setuptools/_distutils/tests/test_filelist.py,sha256=fe0Ec5t4HfjW_FqvtgOHKVmr9Nllpq0H_ehN0g8_OYk,10924
96
+ setuptools/_distutils/tests/test_install.py,sha256=TfCB0ykhIxydIC2Q4SuTAZzSHvteMHgrBL9whoSgK9Q,8618
97
+ setuptools/_distutils/tests/test_install_data.py,sha256=vKq3K97k0hBAnOg38nmwEdf7cEDVr9rTVyCeJolgb4A,2464
98
+ setuptools/_distutils/tests/test_install_headers.py,sha256=PVAYpo_tYl980Qf64DPOmmSvyefIHdU06f7VsJeZykE,936
99
+ setuptools/_distutils/tests/test_install_lib.py,sha256=qri6Rl-maNTQrNDV8DbeXNl0hjsfRIKiI4rfZLrmWBI,3612
100
+ setuptools/_distutils/tests/test_install_scripts.py,sha256=KE3v0cDkFW-90IOID-OmZZGM2mhy-ZkEuuW7UXS2SHw,1600
101
+ setuptools/_distutils/tests/test_log.py,sha256=isFtOufloCyEdZaQOV7cVUr46GwtdVMj43mGBB5XH7k,323
102
+ setuptools/_distutils/tests/test_modified.py,sha256=h1--bOWmtJo1bpVV6uRhdnS9br71CBiNDM1MDwSGpug,4221
103
+ setuptools/_distutils/tests/test_sdist.py,sha256=cfzUhlCA418-1vH9ta3IBs26c_jUBbkJoFOK5GnAyNk,15062
104
+ setuptools/_distutils/tests/test_spawn.py,sha256=eS8w9D7bTxyFLSyRahJWeuh8Kc1F8RWWiY_dSG5B5Bc,4803
105
+ setuptools/_distutils/tests/test_sysconfig.py,sha256=lxM8LsUi1TomjDV4HoYK8u5nUoBkeNL60Uq8PY1DcwU,11986
106
+ setuptools/_distutils/tests/test_text_file.py,sha256=WQWSB5AfdBDZaMA8BFgipJPnsJb_2SKMfL90fSkRVtw,3460
107
+ setuptools/_distutils/tests/test_util.py,sha256=okCAahog4q_sMib9GV07znGwk2PD_gU_mfsrFzsdCw4,7629
108
+ setuptools/_distutils/tests/test_version.py,sha256=ahfg_mP8wRy1sgwY-_Px5hrjgf6_upTIpnCgpR4yWRk,2750
109
+ setuptools/_distutils/tests/test_versionpredicate.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
110
+ setuptools/_distutils/tests/unix_compat.py,sha256=z-op6C2iVdX1aq5BIBR7cqOxijKE97alNwJqHNdLpoI,386
111
+ setuptools/_distutils/text_file.py,sha256=z4dkOJBr9Bo2LG0TNqm8sD63LEEaKSSP0J0bWBrFG3c,12101
112
+ setuptools/_distutils/unixccompiler.py,sha256=1bXJWH4fiu_A2WfriHzf88xjllQTXnnjUkZdRKs9cWU,212
113
+ setuptools/_distutils/util.py,sha256=G7IsTNqFR5dCA7xyTTglEOml1P6KN3kqIK8tgQ-aNQM,17542
114
+ setuptools/_distutils/version.py,sha256=vImT5-ECXkQ21oKL0XYFiTqK6NyM09cpzBNoA_34CQU,12619
115
+ setuptools/_distutils/versionpredicate.py,sha256=qBWQ6wTj12ODytoTmIydefIY2jb4uY1sdbgbuLn-IJM,5205
116
+ setuptools/_distutils/zosccompiler.py,sha256=svdiXZ2kdcwKrJKfhUhib03y8gz7aGZKukXH3I7YkBc,58
117
+ setuptools/_entry_points.py,sha256=10TjbzfGdqWGH06lQuPPGDDci-OnXoIzrfpIWba5AZw,2468
118
+ setuptools/_imp.py,sha256=YY1EjZEN-0zYci1cxO10B_adAEOr7i8eK8JoCc9Ierc,2435
119
+ setuptools/_importlib.py,sha256=DOAUqm9_giDPg-DsX4ygXbfdApZ7nScTpGgGVxruN5A,106
120
+ setuptools/_itertools.py,sha256=jWRfsIrpC7myooz3hDURj9GtvpswZeKXg2HakmEhNjo,657
121
+ setuptools/_normalization.py,sha256=1H0YXdCuVkUcNX2zQqDyqa-4eWC8VI5vWjGGsbj7n8I,5798
122
+ setuptools/_path.py,sha256=Bf5RHbgPAlbVaROVLwNTDH4alt1c7PROfl2HLuOjR2c,2946
123
+ setuptools/_reqs.py,sha256=R_jXOpJXkoJ_bGT0gKhjCf4stu2Kc3qkz9UxujEplDM,1356
124
+ setuptools/_scripts.py,sha256=5TrIWDVOuO3cRcfzcZAUBKPRH7K4svQRdQLZKKiD1bQ,11247
125
+ setuptools/_shutil.py,sha256=SgCqBkj0JWBGl3E8OLcL7mSZf0ajOARha1pQtssknl8,1605
126
+ setuptools/_static.py,sha256=GTR79gESF1_JaK4trLkpDrEuCeEtPlwQW0MRv7VNQX4,4855
127
+ setuptools/_vendor/.lock,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
128
+ setuptools/_vendor/autocommand-2.2.2.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
129
+ setuptools/_vendor/autocommand-2.2.2.dist-info/LICENSE,sha256=reeNBJgtaZctREqOFKlPh6IzTdOFXMgDSOqOJAqg3y0,7634
130
+ setuptools/_vendor/autocommand-2.2.2.dist-info/METADATA,sha256=OADZuR3O6iBlpu1ieTgzYul6w4uOVrk0P0BO5TGGAJk,15006
131
+ setuptools/_vendor/autocommand-2.2.2.dist-info/RECORD,sha256=K-5gcsvOxjkMVxB8jfywQikYqY7NtaLMNiGH8T1C6W8,1072
132
+ setuptools/_vendor/autocommand-2.2.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
133
+ setuptools/_vendor/autocommand-2.2.2.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92
134
+ setuptools/_vendor/autocommand-2.2.2.dist-info/top_level.txt,sha256=AzfhgKKS8EdAwWUTSF8mgeVQbXOY9kokHB6kSqwwqu0,12
135
+ setuptools/_vendor/autocommand/__init__.py,sha256=zko5Rnvolvb-UXjCx_2ArPTGBWwUK5QY4LIQIKYR7As,1037
136
+ setuptools/_vendor/autocommand/autoasync.py,sha256=AMdyrxNS4pqWJfP_xuoOcImOHWD-qT7x06wmKN1Vp-U,5680
137
+ setuptools/_vendor/autocommand/autocommand.py,sha256=hmkEmQ72HtL55gnURVjDOnsfYlGd5lLXbvT4KG496Qw,2505
138
+ setuptools/_vendor/autocommand/automain.py,sha256=A2b8i754Mxc_DjU9WFr6vqYDWlhz0cn8miu8d8EsxV8,2076
139
+ setuptools/_vendor/autocommand/autoparse.py,sha256=WVWmZJPcbzUKXP40raQw_0HD8qPJ2V9VG1eFFmmnFxw,11642
140
+ setuptools/_vendor/autocommand/errors.py,sha256=7aa3roh9Herd6nIKpQHNWEslWE8oq7GiHYVUuRqORnA,886
141
+ setuptools/_vendor/backports.tarfile-1.2.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
142
+ setuptools/_vendor/backports.tarfile-1.2.0.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023
143
+ setuptools/_vendor/backports.tarfile-1.2.0.dist-info/METADATA,sha256=ghXFTq132dxaEIolxr3HK1mZqm9iyUmaRANZQSr6WlE,2020
144
+ setuptools/_vendor/backports.tarfile-1.2.0.dist-info/RECORD,sha256=D2nbcZtUIg1qSt_4v7BKyYr_6j3ItUBUoaeHoXVn9NE,1056
145
+ setuptools/_vendor/backports.tarfile-1.2.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
146
+ setuptools/_vendor/backports.tarfile-1.2.0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
147
+ setuptools/_vendor/backports.tarfile-1.2.0.dist-info/top_level.txt,sha256=cGjaLMOoBR1FK0ApojtzWVmViTtJ7JGIK_HwXiEsvtU,10
148
+ setuptools/_vendor/backports/__init__.py,sha256=iOEMwnlORWezdO8-2vxBIPSR37D7JGjluZ8f55vzxls,81
149
+ setuptools/_vendor/backports/tarfile/__init__.py,sha256=Pwf2qUIfB0SolJPCKcx3vz3UEu_aids4g4sAfxy94qg,108491
150
+ setuptools/_vendor/backports/tarfile/__main__.py,sha256=Yw2oGT1afrz2eBskzdPYL8ReB_3liApmhFkN2EbDmc4,59
151
+ setuptools/_vendor/backports/tarfile/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
152
+ setuptools/_vendor/backports/tarfile/compat/py38.py,sha256=iYkyt_gvWjLzGUTJD9TuTfMMjOk-ersXZmRlvQYN2qE,568
153
+ setuptools/_vendor/importlib_metadata-8.7.1.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
154
+ setuptools/_vendor/importlib_metadata-8.7.1.dist-info/METADATA,sha256=o-OLnuQyYonUhkcE8w4pnudp4jCc6fSnXw3hpQrQo1Y,4670
155
+ setuptools/_vendor/importlib_metadata-8.7.1.dist-info/RECORD,sha256=Uqa47g3hXPf9mWJfQ7l80uOUKshvFgVOqQ3kjmbyk1U,1868
156
+ setuptools/_vendor/importlib_metadata-8.7.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
157
+ setuptools/_vendor/importlib_metadata-8.7.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
158
+ setuptools/_vendor/importlib_metadata-8.7.1.dist-info/licenses/LICENSE,sha256=RYUC4S2Xu_ZEOGBqIARKqF6wX7CoqAe7NdvsJT_R_AQ,10278
159
+ setuptools/_vendor/importlib_metadata-8.7.1.dist-info/top_level.txt,sha256=CO3fD9yylANiXkrMo4qHLV_mqXL2sC5JFKgt1yWAT-A,19
160
+ setuptools/_vendor/importlib_metadata/__init__.py,sha256=u7Ew4-UkpzNY-ka6k-WRkDhQZS1akkLMfWs2eEnUmGo,37734
161
+ setuptools/_vendor/importlib_metadata/_adapters.py,sha256=r5i8XLrKT6xmrpoREZhZrfczOYDmrVZeJBW5u0HzIGU,3797
162
+ setuptools/_vendor/importlib_metadata/_collections.py,sha256=CxAhzlF3g1rwu_fMiB53JtRQiUFh0RgiMpoOvmK_ocg,760
163
+ setuptools/_vendor/importlib_metadata/_compat.py,sha256=VC5ZDLlT-BcshauCShdFJvMNLntJJfZzNK1meGa-enw,1313
164
+ setuptools/_vendor/importlib_metadata/_functools.py,sha256=0pA2OoiVK6wnsGq8HvVIzgdkvLiZ0nfnfw7IsndjoHk,3510
165
+ setuptools/_vendor/importlib_metadata/_itertools.py,sha256=nMvp9SfHAQ_JYwK4L2i64lr3GRXGlYlikGTVzWbys_E,5351
166
+ setuptools/_vendor/importlib_metadata/_meta.py,sha256=EtHyiJ5kGzWFDfKyQ2XQp6Vu113CeadKW1Vf6aGc1B4,1765
167
+ setuptools/_vendor/importlib_metadata/_text.py,sha256=HCsFksZpJLeTP3NEk_ngrAeXVRRtTrtyh9eOABoRP4A,2166
168
+ setuptools/_vendor/importlib_metadata/_typing.py,sha256=EQKhhsEgz_Sa-FnePI-faC72rNOOQwopjA1i5pG8FDU,367
169
+ setuptools/_vendor/importlib_metadata/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
170
+ setuptools/_vendor/importlib_metadata/compat/py311.py,sha256=uqm-K-uohyj1042TH4a9Er_I5o7667DvulcD-gC_fSA,608
171
+ setuptools/_vendor/importlib_metadata/compat/py39.py,sha256=J3W7PUVRPNYMmcvT12RF8ndBU9e8_T0Ac4U87Bsrq70,1187
172
+ setuptools/_vendor/importlib_metadata/diagnose.py,sha256=nkSRMiowlmkhLYhKhvCg9glmt_11Cox-EmLzEbqYTa8,379
173
+ setuptools/_vendor/importlib_metadata/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
174
+ setuptools/_vendor/jaraco.text-4.0.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
175
+ setuptools/_vendor/jaraco.text-4.0.0.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023
176
+ setuptools/_vendor/jaraco.text-4.0.0.dist-info/METADATA,sha256=XC_QkBLJVPE5sQYkl41TNaZUw0AUzQb29GbKaD28nFY,3731
177
+ setuptools/_vendor/jaraco.text-4.0.0.dist-info/RECORD,sha256=Y7k2wwjQ_L4TkOgkVnzAB1NsMqhJrbAieOlfHUxzbDE,1157
178
+ setuptools/_vendor/jaraco.text-4.0.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
179
+ setuptools/_vendor/jaraco.text-4.0.0.dist-info/WHEEL,sha256=Wyh-_nZ0DJYolHNn1_hMa4lM7uDedD_RGVwbmTjyItk,91
180
+ setuptools/_vendor/jaraco.text-4.0.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7
181
+ setuptools/_vendor/jaraco/context/__init__.py,sha256=br1ydYGo1Xr_Pu1anuEdd-QrjUiz_EY5L_5E4C03L4w,9809
182
+ setuptools/_vendor/jaraco/context/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
183
+ setuptools/_vendor/jaraco/functools/__init__.py,sha256=ZJx9cMs2Nvk2xGUl8OjVGkpjdOaNlSzJrN4dGglgX2g,18599
184
+ setuptools/_vendor/jaraco/functools/__init__.pyi,sha256=K4DcbnYIHE5QlMxqf9-cVp-WhycrhuTao4J7O7TMq4Y,3907
185
+ setuptools/_vendor/jaraco/functools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
186
+ setuptools/_vendor/jaraco/text/Lorem ipsum.txt,sha256=N_7c_79zxOufBY9HZ3yzMgOkNv-TkOTTio4BydrSjgs,1335
187
+ setuptools/_vendor/jaraco/text/__init__.py,sha256=lazNYXo8IhOR1bFigLAyGiiQao6jtO3KGWh8bZZPx3c,16762
188
+ setuptools/_vendor/jaraco/text/layouts.py,sha256=HTC8aSTLZ7uXipyOXapRMC158juecjK6RVwitfmZ9_w,643
189
+ setuptools/_vendor/jaraco/text/show-newlines.py,sha256=jT0vp4gLhG20hX2lTB-zKo_i3NgKzj79yRAdz4eMzIM,903
190
+ setuptools/_vendor/jaraco/text/strip-prefix.py,sha256=NfVXV8JVNo6nqcuYASfMV7_y4Eo8zMQqlCOGvAnRIVw,412
191
+ setuptools/_vendor/jaraco/text/to-dvorak.py,sha256=36nPPsiifwv6RfpAb--3zpgbIx8ohnnI1aR29IJTO9s,118
192
+ setuptools/_vendor/jaraco/text/to-qwerty.py,sha256=IQoFY9v7vLTEybcput4KBYm_5GR35pmtgZ_xyrmdTgI,118
193
+ setuptools/_vendor/jaraco_context-6.1.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
194
+ setuptools/_vendor/jaraco_context-6.1.0.dist-info/METADATA,sha256=BDXr_FIFXFqZdO0gwXG2RUOD6vnbsVCIFLp62XxZ1xI,4270
195
+ setuptools/_vendor/jaraco_context-6.1.0.dist-info/RECORD,sha256=RZnYds60K37vA6o54jXE6-q2rqJAnb5jRJaFI5PR-Dc,777
196
+ setuptools/_vendor/jaraco_context-6.1.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
197
+ setuptools/_vendor/jaraco_context-6.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
198
+ setuptools/_vendor/jaraco_context-6.1.0.dist-info/licenses/LICENSE,sha256=l1WhhRlmbl8PTK49qtPXASvK5IpgCzEjfXXp_hNOZoM,1076
199
+ setuptools/_vendor/jaraco_context-6.1.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7
200
+ setuptools/_vendor/jaraco_functools-4.4.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
201
+ setuptools/_vendor/jaraco_functools-4.4.0.dist-info/METADATA,sha256=LnnajcNGmSSr46yLIqP-tWkqeb-fR7vIa2U11hhkGEk,2960
202
+ setuptools/_vendor/jaraco_functools-4.4.0.dist-info/RECORD,sha256=uq_S1tlMG95FPkyAWsBVEdxTmG4KY7AvZ07w94i-wUY,882
203
+ setuptools/_vendor/jaraco_functools-4.4.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
204
+ setuptools/_vendor/jaraco_functools-4.4.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
205
+ setuptools/_vendor/jaraco_functools-4.4.0.dist-info/licenses/LICENSE,sha256=WlfLTbheKi3YjCkGKJCK3VfjRRRJ4KmnH9-zh3b9dZ0,1076
206
+ setuptools/_vendor/jaraco_functools-4.4.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7
207
+ setuptools/_vendor/more_itertools-10.8.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
208
+ setuptools/_vendor/more_itertools-10.8.0.dist-info/METADATA,sha256=arNRUUWr5YsGfwh8hnYxz0z11lP-2BuWQu4SCGw5BLg,39413
209
+ setuptools/_vendor/more_itertools-10.8.0.dist-info/RECORD,sha256=ntGxNMCqg3IvNumfORiqlhDOOgpRTXk7u3SjaNRBoB0,1095
210
+ setuptools/_vendor/more_itertools-10.8.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
211
+ setuptools/_vendor/more_itertools-10.8.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
212
+ setuptools/_vendor/more_itertools-10.8.0.dist-info/licenses/LICENSE,sha256=CfHIyelBrz5YTVlkHqm4fYPAyw_QB-te85Gn4mQ8GkY,1053
213
+ setuptools/_vendor/more_itertools/__init__.py,sha256=5F7E_zpoGcEBW_T_3WE0WYYt8j-gJodIuiBcOJxrOv8,149
214
+ setuptools/_vendor/more_itertools/__init__.pyi,sha256=5B3eTzON1BBuOLob1vCflyEb2lSd6usXQQ-Cv-hXkeA,43
215
+ setuptools/_vendor/more_itertools/more.py,sha256=mNPKKu5UI7lRL460vgm0QTCWFiGMVCMosSPxVSdibos,163690
216
+ setuptools/_vendor/more_itertools/more.pyi,sha256=fpEgNX3O66wY5cnT-s5VYDKNUpAcaCyU3iP84It3OOM,27119
217
+ setuptools/_vendor/more_itertools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
218
+ setuptools/_vendor/more_itertools/recipes.py,sha256=Ma-kuBNZDFhaQDbIJgRmnrG86WzaupbOyUV3v8je3xw,41811
219
+ setuptools/_vendor/more_itertools/recipes.pyi,sha256=LNRwN-OL3nkMfQAqx-PPc1fBaetUObb_Z6mdePyzh1c,6226
220
+ setuptools/_vendor/packaging-26.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
221
+ setuptools/_vendor/packaging-26.0.dist-info/METADATA,sha256=M2K7fWom2iliuo2qpHhc0LrKwhq6kIoRlcyPWVgKJlo,3309
222
+ setuptools/_vendor/packaging-26.0.dist-info/RECORD,sha256=9QUDMzqulReAfS-02B_CfLYKpkRmb1AXaBJibWIkzl0,2113
223
+ setuptools/_vendor/packaging-26.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
224
+ setuptools/_vendor/packaging-26.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
225
+ setuptools/_vendor/packaging-26.0.dist-info/licenses/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197
226
+ setuptools/_vendor/packaging-26.0.dist-info/licenses/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174
227
+ setuptools/_vendor/packaging-26.0.dist-info/licenses/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344
228
+ setuptools/_vendor/packaging/__init__.py,sha256=y4lVbpeBzCGk-IPDw5BGBZ_b0P3ukEEJZAbGYc6Ey8c,494
229
+ setuptools/_vendor/packaging/_elffile.py,sha256=-sKkptYqzYw2-x3QByJa5mB4rfPWu1pxkZHRx1WAFCY,3211
230
+ setuptools/_vendor/packaging/_manylinux.py,sha256=Hf6nB0cOrayEs96-p3oIXAgGnFquv20DO5l-o2_Xnv0,9559
231
+ setuptools/_vendor/packaging/_musllinux.py,sha256=Z6swjH3MA7XS3qXnmMN7QPhqP3fnoYI0eQ18e9-HgAE,2707
232
+ setuptools/_vendor/packaging/_parser.py,sha256=U_DajsEx2VoC_F46fSVV3hDKNCWoQYkPkasO3dld0ig,10518
233
+ setuptools/_vendor/packaging/_structures.py,sha256=Hn49Ta8zV9Wo8GiCL8Nl2ARZY983Un3pruZGVNldPwE,1514
234
+ setuptools/_vendor/packaging/_tokenizer.py,sha256=M8EwNIdXeL9NMFuFrQtiOKwjka_xFx8KjRQnfE8O_z8,5421
235
+ setuptools/_vendor/packaging/licenses/__init__.py,sha256=TwXLHZCXwSgdFwRLPxW602T6mSieunSFHM6fp8pgW78,5819
236
+ setuptools/_vendor/packaging/licenses/_spdx.py,sha256=WW7DXiyg68up_YND_wpRYlr1SHhiV4FfJLQffghhMxQ,51122
237
+ setuptools/_vendor/packaging/markers.py,sha256=ZX-cLvW1S3cZcEc0fHI4z7zSx5U2T19yMpDP_mE-CYw,12771
238
+ setuptools/_vendor/packaging/metadata.py,sha256=CWVZpN_HfoYMSSDuCP7igOvGgqA9AOmpW8f3qTisfnc,39360
239
+ setuptools/_vendor/packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
240
+ setuptools/_vendor/packaging/pylock.py,sha256=-R1uNfJ4PaLto7Mg62YsGOHgvskuiIEqPwxOywl42Jk,22537
241
+ setuptools/_vendor/packaging/requirements.py,sha256=PMCAWD8aNMnVD-6uZMedhBuAVX2573eZ4yPBLXmz04I,2870
242
+ setuptools/_vendor/packaging/specifiers.py,sha256=EPNPimY_zFivthv1vdjZYz5IqkKGsnKR2yKh-EVyvZw,40797
243
+ setuptools/_vendor/packaging/tags.py,sha256=cXLV1pJD3UtJlDg7Wz3zrfdQhRZqr8jumSAKKAAd2xE,22856
244
+ setuptools/_vendor/packaging/utils.py,sha256=N4c6oZzFJy6klTZ3AnkNz7sSkJesuFWPp68LA3B5dAo,5040
245
+ setuptools/_vendor/packaging/version.py,sha256=7XWlL2IDYLwDYC0ht6cFEhapLwLWbmyo4rb7sEFj0x8,23272
246
+ setuptools/_vendor/platformdirs-4.4.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
247
+ setuptools/_vendor/platformdirs-4.4.0.dist-info/METADATA,sha256=u8UhbV9Md7-8VyJyZNUuZrzN5xzPeedeGmBG0CnTAiM,12831
248
+ setuptools/_vendor/platformdirs-4.4.0.dist-info/RECORD,sha256=PQ0vHMAYWTxNi6ojlbrwscHGRbvYwYzQZPSctOTJXqA,1218
249
+ setuptools/_vendor/platformdirs-4.4.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
250
+ setuptools/_vendor/platformdirs-4.4.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
251
+ setuptools/_vendor/platformdirs-4.4.0.dist-info/licenses/LICENSE,sha256=KeD9YukphQ6G6yjD_czwzv30-pSHkBHP-z0NS-1tTbY,1089
252
+ setuptools/_vendor/platformdirs/__init__.py,sha256=iORRy6_lZ9tXLvO0W6fJPn8QV7F532ivl-f2WGmabBc,22284
253
+ setuptools/_vendor/platformdirs/__main__.py,sha256=HnsUQHpiBaiTxwcmwVw-nFaPdVNZtQIdi1eWDtI-MzI,1493
254
+ setuptools/_vendor/platformdirs/android.py,sha256=r0DshVBf-RO1jXJGX8C4Til7F1XWt-bkdWMgmvEiaYg,9013
255
+ setuptools/_vendor/platformdirs/api.py,sha256=wPHOlwOsfz2oqQZ6A2FcCu5kEAj-JondzoNOHYFQ0h8,9281
256
+ setuptools/_vendor/platformdirs/macos.py,sha256=0XoOgin1NK7Qki7iskD-oS8xKxw6bXgoKEgdqpCRAFQ,6322
257
+ setuptools/_vendor/platformdirs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
258
+ setuptools/_vendor/platformdirs/unix.py,sha256=WZmkUA--L3JNRGmz32s35YfoD3ica6xKIPdCV_HhLcs,10458
259
+ setuptools/_vendor/platformdirs/version.py,sha256=i31fi3nNO19D2FdSx8aldD7IFLSqm2YrAo6SmkV0FLM,704
260
+ setuptools/_vendor/platformdirs/windows.py,sha256=IFpiohUBwxPtCzlyKwNtxyW4Jk8haa6W8o59mfrDXVo,10125
261
+ setuptools/_vendor/tomli-2.4.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
262
+ setuptools/_vendor/tomli-2.4.0.dist-info/METADATA,sha256=9awKH4-6kItGRs1lUwnpGq2Wm2eHYWrFccpGKjgy_84,10567
263
+ setuptools/_vendor/tomli-2.4.0.dist-info/RECORD,sha256=IlQwzpVkDo1Pzbk82uL8ONaFrsAW0OKT1fuZppWIb-0,822
264
+ setuptools/_vendor/tomli-2.4.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
265
+ setuptools/_vendor/tomli-2.4.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
266
+ setuptools/_vendor/tomli-2.4.0.dist-info/licenses/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072
267
+ setuptools/_vendor/tomli/__init__.py,sha256=ahtDjGJA2M_wWVvGpzx4YJtWxrWBx6qE-GH5-UYoECA,314
268
+ setuptools/_vendor/tomli/_parser.py,sha256=txeATLE3zHyZ-ushXtYfrZ3LoIs7JzQF2W2KL1gwJPg,25958
269
+ setuptools/_vendor/tomli/_re.py,sha256=oSNZ_ilFI6chEuQ01YRSoUydBQr_okF_mSdHTkFmv90,3396
270
+ setuptools/_vendor/tomli/_types.py,sha256=-GTG2VUqkpxwMqzmVO4F7ybKddIbAnuAHXfmWQcTi3Q,254
271
+ setuptools/_vendor/tomli/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26
272
+ setuptools/_vendor/wheel-0.46.3.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
273
+ setuptools/_vendor/wheel-0.46.3.dist-info/METADATA,sha256=IpEKqXyonLzCCgGeJ_4xNgt5KaS9ZsoNMQ-ZpE9szTU,2410
274
+ setuptools/_vendor/wheel-0.46.3.dist-info/RECORD,sha256=sCl8OtoXuHJ-Fd3W0eOMipCpl_d5_Pl4mW9v7GLstwI,1734
275
+ setuptools/_vendor/wheel-0.46.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
276
+ setuptools/_vendor/wheel-0.46.3.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
277
+ setuptools/_vendor/wheel-0.46.3.dist-info/entry_points.txt,sha256=JJdtSAGTvMLbIkTVZUAMvGKO39FtWfCVF8mp_NH6e4g,110
278
+ setuptools/_vendor/wheel-0.46.3.dist-info/licenses/LICENSE.txt,sha256=MMI2GGeRCPPo6h0qZYx8pBe9_IkcmO8aifpP8MmChlQ,1107
279
+ setuptools/_vendor/wheel/__init__.py,sha256=UweKvhe4SyP7zFyDoYo8BOuwTA6q3-_WpMmY2NNO54c,59
280
+ setuptools/_vendor/wheel/__main__.py,sha256=_83wl9tyGU2cHiqfudpubGHdRL5uonPXnzeznznkxzs,512
281
+ setuptools/_vendor/wheel/_bdist_wheel.py,sha256=bpmNa7_s-CYFkVgXf9ENAYTiJ01XBhRW4pxH1T8XYsI,21729
282
+ setuptools/_vendor/wheel/_commands/__init__.py,sha256=fCRAQZNDyj2JLrufdgPsBlaRS_t_j_aBUMpXj09KZ4E,4432
283
+ setuptools/_vendor/wheel/_commands/convert.py,sha256=0wSJMU0m-6LY16Om8Wmmloy-hJWFZeOmI8hT-2Z7Qms,12743
284
+ setuptools/_vendor/wheel/_commands/pack.py,sha256=o3iwjfRHl7N9ul-M2kHbewLJZnqBLAWf0tzUCwoiTMw,3078
285
+ setuptools/_vendor/wheel/_commands/tags.py,sha256=Rv2ySVb8-qX3osKp3uJgxcIMXkjt43XUD0-zvC6KvnY,4775
286
+ setuptools/_vendor/wheel/_commands/unpack.py,sha256=AjDSS23XYyCSFfifnMutinrpPv-DK_2wbNHkKAUFwgM,1016
287
+ setuptools/_vendor/wheel/_metadata.py,sha256=BP5jC9uC1hyicp7nL4FJ2LYixNFpEJIV_uMDY1KBZBg,6188
288
+ setuptools/_vendor/wheel/_setuptools_logging.py,sha256=-5KC-lne0ilOUWIDfOkqapUWGMFZhuKYDIavIZiB5kM,781
289
+ setuptools/_vendor/wheel/bdist_wheel.py,sha256=HrzYiSzMkh5ohAAhlQnYBS1p8qbr85X6F59xqxd9kBg,1102
290
+ setuptools/_vendor/wheel/macosx_libfile.py,sha256=pL0wm88jRMl_4ASgGlNg_mz69Zmv5xm8JSkjLdwyvIQ,16712
291
+ setuptools/_vendor/wheel/metadata.py,sha256=GknOO7JJiZMlcEe_fiD7nqnDTTLd0sX_-IgipM4L3-4,757
292
+ setuptools/_vendor/wheel/wheelfile.py,sha256=m_g_7TNsEp-j-xnvSr5yDLEFb1nhyObueq9Q5_1_lBA,8720
293
+ setuptools/_vendor/zipp-3.23.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
294
+ setuptools/_vendor/zipp-3.23.0.dist-info/METADATA,sha256=vdZ9TRbPC_O4k-fRjNPS13StuC837Zhbx3cMYHIms1s,3563
295
+ setuptools/_vendor/zipp-3.23.0.dist-info/RECORD,sha256=O_q2YKJHBPhCKOS7HOHw4_qf-A5cgGNSpiay9GDq2DY,1078
296
+ setuptools/_vendor/zipp-3.23.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
297
+ setuptools/_vendor/zipp-3.23.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
298
+ setuptools/_vendor/zipp-3.23.0.dist-info/licenses/LICENSE,sha256=WlfLTbheKi3YjCkGKJCK3VfjRRRJ4KmnH9-zh3b9dZ0,1076
299
+ setuptools/_vendor/zipp-3.23.0.dist-info/top_level.txt,sha256=iAbdoSHfaGqBfVb2XuR9JqSQHCoOsOtG6y9C_LSpqFw,5
300
+ setuptools/_vendor/zipp/__init__.py,sha256=ieXh9GIMdABjKRX_JUJtP9k5wdBLK4Mt5X4nszSkmYE,11976
301
+ setuptools/_vendor/zipp/_functools.py,sha256=f6Kt9LxZ4TE-cY1lJVdXSId3memSXmH9IdgMbU-_x2k,575
302
+ setuptools/_vendor/zipp/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
303
+ setuptools/_vendor/zipp/compat/overlay.py,sha256=oEIGAnbr8yGjuKTrVSO2ByewPui71uppbX18BLnYTKE,783
304
+ setuptools/_vendor/zipp/compat/py310.py,sha256=S7i6N9mToEn3asNb2ILyjnzvITOXrATD_J4emjyBbDU,256
305
+ setuptools/_vendor/zipp/compat/py313.py,sha256=RndvDNtuY7H2D9ecnnzcPBMZ8mZc42gmXD_IwQAXXAE,654
306
+ setuptools/_vendor/zipp/glob.py,sha256=DLV9LBsDxA6YVW82e3-tkoNrus1h4R-j3BR6VqS0AzE,3382
307
+ setuptools/archive_util.py,sha256=Tl_64hSTtc4y8x7xa98rFVUbG24oArpjzLAYGYP2_sI,7356
308
+ setuptools/build_meta.py,sha256=wacrbTeKTEaBOFyw1XEEEvAEwfcJBUaXq8tGC_3kOzI,20205
309
+ setuptools/cli-32.exe,sha256=MqzBvFQxFsviz_EMuGd3LfLyVP8mNMhwrvC0bEtpb9s,11776
310
+ setuptools/cli-64.exe,sha256=u7PeVwdinmpgoMI4zUd7KPB_AGaYL9qVP6b87DkHOko,14336
311
+ setuptools/cli-arm64.exe,sha256=uafQjaiA36yLz1SOuksG-1m28JsX0zFIoPZhgyiSbGE,13824
312
+ setuptools/cli.exe,sha256=MqzBvFQxFsviz_EMuGd3LfLyVP8mNMhwrvC0bEtpb9s,11776
313
+ setuptools/command/__init__.py,sha256=wdSrlNR0P6nCz9_oFtCAiAkeFJMsZa1jPcpXT53f0SM,803
314
+ setuptools/command/_requirestxt.py,sha256=ItYMTJGh_i5TlQstX_nFopqEhkC4PJFadBL2Zd3V670,4228
315
+ setuptools/command/alias.py,sha256=vVxEYVEFMTZznxuXLg-62Y07VV2U-rfhVqmqhTc62Cg,2366
316
+ setuptools/command/bdist_egg.py,sha256=u4yK_I5hOFfxiXtJlorbC9QnzrU3Vu-JpCw_tBhsMpc,16822
317
+ setuptools/command/bdist_rpm.py,sha256=LyqI49w48SKk0FmuHsE9MLzX1SuXjL7YMNbZMFZqFII,1435
318
+ setuptools/command/bdist_wheel.py,sha256=2TMl21f7WWeH3m0NhJLVZPVOSWE0w-wZcG2pFseP8Qw,22210
319
+ setuptools/command/build.py,sha256=eI7STMERGGZEpzk1tvJN8p9IOjAAXMcGLzljv2mwI3M,6052
320
+ setuptools/command/build_clib.py,sha256=AbgpPIF_3qL8fZr3JIebI-WHTMTBiMfrFkVQz8K40G4,4528
321
+ setuptools/command/build_ext.py,sha256=SaurTvvtJuOSOD8cm_6Wj1T0DFiyl5Nazv4GYINAgWA,18270
322
+ setuptools/command/build_py.py,sha256=eHhfo9z7Qf79vSzrCnq-oEXayQC0R_nx3hWaTgWGv5M,15826
323
+ setuptools/command/develop.py,sha256=TYKWIzfv3c3wjAYhH5UD8tW6S6ozZi_fpF6IJILm8Kg,1751
324
+ setuptools/command/dist_info.py,sha256=HU752iLLmmYMHbsDBgz2ubRjkgJobugOp8H71LzzDys,3450
325
+ setuptools/command/easy_install.py,sha256=XrN5cV51mfzbCDoapZ6iT8nCzaLpumdwJYRKeMHEjCQ,780
326
+ setuptools/command/editable_wheel.py,sha256=xJOPl_0s5DbwpeLw-SNh75mvEnmwE7OFpnpChlOaNgg,34862
327
+ setuptools/command/egg_info.py,sha256=df3nMX9wvt_nqyrFlqoW_HnoaeBNxCnW7jY3dFnvHd0,26744
328
+ setuptools/command/install.py,sha256=4x2hiNgBGQrFEXKuPBQMrb8ecSwIfYF4TYHZQLjPVAg,5066
329
+ setuptools/command/install_egg_info.py,sha256=gYOkfDM-G0agy2aMCE8HzreIi4LzUy6acZ6Ka-rKahQ,2020
330
+ setuptools/command/install_lib.py,sha256=9n1_U83eHcERL_a_rv_LhHCkhXlLdqyZ4SdBow-9qcE,4319
331
+ setuptools/command/install_scripts.py,sha256=ZYfF_-viovV5HSLsRzBlNQv5pHv2H0t2ZnL5qzZ4xfM,2445
332
+ setuptools/command/rotate.py,sha256=PywuJoufmiO_5JykOg-oatrYsBnZfA0pG1HJy7Bsb9Q,2134
333
+ setuptools/command/saveopts.py,sha256=k9hiQ_wOKweXWgBWV548PISmFKfYJkV2XHhi92ejz5o,678
334
+ setuptools/command/sdist.py,sha256=nS2xogcTfQZwbZH1AQ5WYh13KCvNda9xwUT57sVxTec,7426
335
+ setuptools/command/setopt.py,sha256=MCM9SM92LwGUC-E2nnvQxX8Yf2ukMj1YAa6KCRlqt_8,5047
336
+ setuptools/command/test.py,sha256=x9z3DDCQi-_3-TRf8yNeQ9QH-G6yR1au7kX0ijedKqU,1400
337
+ setuptools/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
338
+ setuptools/compat/py310.py,sha256=JwjQZ3cNTizfpDLNl9GLsUGzBr-tVlMPxmMYVDTlhiI,344
339
+ setuptools/compat/py311.py,sha256=B0QTTHf5sjz-mI0J4yhRIZy_VBlHxKSQVVZltXNa-4A,807
340
+ setuptools/compat/py312.py,sha256=vYKVtdrdOTsO_R90dJkEXsFwfMJFuIFJflhIgHrjJ-Y,366
341
+ setuptools/compat/py39.py,sha256=BJMtnkfcqyTfccqjYQxfoRtU2nTnWaEESBVkshTiXqY,493
342
+ setuptools/config/NOTICE,sha256=Ld3wiBgpejuJ1D2V_2WdjahXQRCMkTbfo6TYVsBiO9g,493
343
+ setuptools/config/__init__.py,sha256=BgOaoEnoG9D3w5R5k_HGQEakrPdq-hfi4pL5Ki5MUvU,1526
344
+ setuptools/config/_apply_pyprojecttoml.py,sha256=td-pqp6E2cCuCD857H4RPvbi6wPP9eNG5eJNDaUbGFM,19412
345
+ setuptools/config/_validate_pyproject/NOTICE,sha256=Ccm86pXKCG-Lxb7RdOQLyDWyl9QPtfhru7Vw_gpVgac,18737
346
+ setuptools/config/_validate_pyproject/__init__.py,sha256=dnp6T7ePP1R5z4OuC7Fd2dkFlIrtIfizUfvpGJP6nz0,1042
347
+ setuptools/config/_validate_pyproject/error_reporting.py,sha256=5jGbcg7zQCEiEA8fAilSkaXnEfXyD7fq5CG-OkmFZmk,11803
348
+ setuptools/config/_validate_pyproject/extra_validations.py,sha256=lQnu5wASBL8iDToODpw5sX21kev01_PjUIGldu1proY,5066
349
+ setuptools/config/_validate_pyproject/fastjsonschema_exceptions.py,sha256=w749JgqKi8clBFcObdcbZVqsmF4oJ_QByhZ1SGbUFNw,1612
350
+ setuptools/config/_validate_pyproject/fastjsonschema_validations.py,sha256=XjMh9s9ezEzqM9yoZ4KoUQ7jCoHAqsRl-KSf30Rlgxo,365819
351
+ setuptools/config/_validate_pyproject/formats.py,sha256=LNRajleuZtyP8BWhMcbuA92APppdiItpEpEeqCjA54Q,15373
352
+ setuptools/config/distutils.schema.json,sha256=Tcp32kRnhwORGw_9p6GEi08lj2h15tQRzOYBbzGmcBU,972
353
+ setuptools/config/expand.py,sha256=GMJHHMiWfoXbhyMSfu1803pSBNPNQWijmkNPLcaq9Gs,16064
354
+ setuptools/config/pyprojecttoml.py,sha256=B5wqp_l54_x168v26yg4Y6Y1pqFLUgpFNiaQ_1EORcQ,18786
355
+ setuptools/config/setupcfg.py,sha256=E0X40FEfZQ3rrJKhQB-ayCAZR9ej-FVN_q6gybDGwK4,26684
356
+ setuptools/config/setuptools.schema.json,sha256=Bp6tTwRvSy96_dCd5OqKTifuIcTWOd5wDGRCrwYBzjQ,16047
357
+ setuptools/depends.py,sha256=jKYfjmt_2ZQYVghb8L9bU7LJ6erHJ5ze-K_fKV1BMXk,5965
358
+ setuptools/discovery.py,sha256=XYIeFN20WEsEtssmpzCFlnda-Qxilj8KlLYKaJphAto,21286
359
+ setuptools/dist.py,sha256=y43JCeqDGEQh1d099ZJF6E7znE4u9au7mj446WJWWhM,45155
360
+ setuptools/errors.py,sha256=gY2x2PIaIgy01yRANRC-zcCwxDCqCScgJoCOZFe0yio,3024
361
+ setuptools/extension.py,sha256=GbCxJ9rRk2rZcXS4qgmnzWNG36HlhLfUEvNwB-OKGk8,6818
362
+ setuptools/glob.py,sha256=AC_B33DY8g-CHELxDsJrtwFrpiucSAZsakPFdSOQzhc,6062
363
+ setuptools/gui-32.exe,sha256=hdrh6V13hF8stZvKw9Sv50u-TJGpvMW_SnHNQxBNvnw,11776
364
+ setuptools/gui-64.exe,sha256=NHG2FA6txkEid9u-_j_vjDRaDxpZd2CGuAo2GMOoPjs,14336
365
+ setuptools/gui-arm64.exe,sha256=5pT0dDQFyLWSb_RX22_n8aEt7HwWqcOGR4TT9OB64Jc,13824
366
+ setuptools/gui.exe,sha256=hdrh6V13hF8stZvKw9Sv50u-TJGpvMW_SnHNQxBNvnw,11776
367
+ setuptools/installer.py,sha256=Wy_hG1g1r-45E6IWh7lvQ0Pk0QHNl6JJbu3hQmr1_Ek,5184
368
+ setuptools/launch.py,sha256=IBb5lEv69CyuZ9ewIrmKlXh154kdLmP29LKfTMkximE,820
369
+ setuptools/launcher manifest.xml,sha256=xlLbjWrB01tKC0-hlVkOKkiSPbzMml2eOPtJ_ucCnbE,628
370
+ setuptools/logging.py,sha256=W16iHJ1HcCXYQ0RxyrEfJ83FT4175tCtoYg-E6uSpVI,1261
371
+ setuptools/modified.py,sha256=ZwbfBfCFP88ltvbv_dJDz-t1LsQjnM-JUpgZnnQZjjM,568
372
+ setuptools/monkey.py,sha256=nOD5vgLG7IpKAs7LrnpJxGPaCW54Rzj-onJmm91otoY,3733
373
+ setuptools/msvc.py,sha256=IdCsRhdJLeyZG3gyDrGx2DqZymoay3ndBXC77taHHCA,42909
374
+ setuptools/namespaces.py,sha256=eE1hI5X86TNWvY5u5BC1WiGiOrrJyGOv0pp9vycCmK0,3045
375
+ setuptools/script (dev).tmpl,sha256=RUzQzCQUaXtwdLtYHWYbIQmOaES5Brqq1FvUA_tu-5I,218
376
+ setuptools/script.tmpl,sha256=WGTt5piezO27c-Dbx6l5Q4T3Ff20A5z7872hv3aAhYY,138
377
+ setuptools/tests/__init__.py,sha256=AnBfls2iJbTDQzmMKeLRt-9lxhaOHUVOZEgXv89Uwvs,335
378
+ setuptools/tests/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
379
+ setuptools/tests/compat/py39.py,sha256=eUy7_F-6KRTOIKl-veshUu6I0EdTSdBZMh0EV0lZ1-g,135
380
+ setuptools/tests/config/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
381
+ setuptools/tests/config/downloads/__init__.py,sha256=9ixnDEdyL_arKbUzfuiJftAj9bGxKz8M9alOFZMjx9Y,1827
382
+ setuptools/tests/config/downloads/preload.py,sha256=sIGGZpY3cmMpMwiJYYYYHG2ifZJkvJgEotRFtiulV1I,450
383
+ setuptools/tests/config/setupcfg_examples.txt,sha256=cAbVvCbkFZuTUL6xRRzRgqyB0rLvJTfvw3D30glo2OE,1912
384
+ setuptools/tests/config/test_apply_pyprojecttoml.py,sha256=qBOXnCwZVQ7wTYfwq83zAAtsGGooJgFh_H9L2avrv4Y,29609
385
+ setuptools/tests/config/test_expand.py,sha256=S0oT6JvgA_oujR4YS4RUuf5gmOt1CTQV66RQDzV8xd4,8933
386
+ setuptools/tests/config/test_pyprojecttoml.py,sha256=tP7iaVmpnv3wAY2eplDLFXzfHGuvxT71SQX9O9Jrwl0,13182
387
+ setuptools/tests/config/test_pyprojecttoml_dynamic_deps.py,sha256=1MRtzcxZag-ElRwVGt0kUk4KPRA-RSwKkibO8-Vy51w,3265
388
+ setuptools/tests/config/test_setupcfg.py,sha256=iwViCQFLGVWZLgCDrBv8HKBBCj-Onr8aNdioD9_lBEo,33712
389
+ setuptools/tests/contexts.py,sha256=Ozdfc2KydF9x9wODUsdun800myLuP27uxoeT06Gbk7M,3166
390
+ setuptools/tests/environment.py,sha256=95_UtTaRiuvwYC9eXKEHbn02kDtZysvZq3UZJmPUj1I,3102
391
+ setuptools/tests/fixtures.py,sha256=jE7pIFQt91dZIUc6Btsffi8OdBqmY_7DNeWI1Stv7i8,12224
392
+ setuptools/tests/indexes/test_links_priority/external.html,sha256=eL9euOuE93JKZdqlXxBOlHbKwIuNuIdq7GBRpsaPMcU,92
393
+ setuptools/tests/indexes/test_links_priority/simple/foobar/index.html,sha256=DD-TKr7UU4zAjHHz4VexYDNSAzR27levSh1c-k3ZdLE,174
394
+ setuptools/tests/integration/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
395
+ setuptools/tests/integration/helpers.py,sha256=ieQtGuIohqNI_RHMH0yxE602Uz4E8wysUj7XaXYH30Y,2688
396
+ setuptools/tests/integration/test_pbr.py,sha256=2eKuklFNmpnBgA_eEhYPBr6rLLG2Xm4MY6PlcmzZgGU,432
397
+ setuptools/tests/integration/test_pip_install_sdist.py,sha256=SFbvuYF_hDzt6OtsQ5GjFNnxmoJ_eElfvpYsiyyGJ-g,8256
398
+ setuptools/tests/mod_with_constant.py,sha256=X_Kj80M55w1tmQ4f7uZY91ZTALo4hKVT6EHxgYocUMQ,22
399
+ setuptools/tests/namespaces.py,sha256=HPcI3nR5MCFWXpaADIJ1fwKxymcQgBkuw87Ic5PUSAQ,2774
400
+ setuptools/tests/script-with-bom.py,sha256=hRRgIizEULGiG_ZTNoMY46HhKhxpWfy5FGcD6Qbh5fc,18
401
+ setuptools/tests/test_archive_util.py,sha256=buuKdY8XkW26Pe3IKAoBRGHG0MDumnuNoPg2WsAQzIg,845
402
+ setuptools/tests/test_bdist_deprecations.py,sha256=75Xq3gYn79LIIyusEltbHan0bEgAt2e_CaL7KLS8-KQ,775
403
+ setuptools/tests/test_bdist_egg.py,sha256=6PaYN1F3JDbIh1uK0urv7yJFcx98z5dn9SOJ8Mv91l8,1957
404
+ setuptools/tests/test_bdist_wheel.py,sha256=xGHVaggiYobkOuGwkLK2bNejcSh8z2Fiuq-ge_S-yKo,23091
405
+ setuptools/tests/test_build.py,sha256=wJgMz2hwHADcLFg-nXrwRVhus7hjmAeEGgrpIQwCGnA,798
406
+ setuptools/tests/test_build_clib.py,sha256=bX51XRAf4uO7IuHFpjePnoK8mE74N2gsoeEqF-ofgws,3123
407
+ setuptools/tests/test_build_ext.py,sha256=e4ZSxsYPB5zq1KSqGEuATZ0t0PJQzMhjjkKJ-hIjcgc,10099
408
+ setuptools/tests/test_build_meta.py,sha256=_FYYwMTusWVRIaXOiolpAW5T8wQsB5QY0Wgf9Otr_oQ,33347
409
+ setuptools/tests/test_build_py.py,sha256=SIcHFX3YNErcVkWjf0eDRuKmsO9kTymKjfK-PkOi9M0,14201
410
+ setuptools/tests/test_config_discovery.py,sha256=X5x3CRLUouIZHqHyAggbboiPVfqlkLI-QWPAZWtCQx4,22527
411
+ setuptools/tests/test_core_metadata.py,sha256=p8mW920afKVdL8sC_Fce8zpmfWDCRylBa3dd39Y-qWo,18038
412
+ setuptools/tests/test_depends.py,sha256=yQBXoQbNQlJit6mbRVoz6Bb553f3sNrq02lZimNz5XY,424
413
+ setuptools/tests/test_develop.py,sha256=k-agNgB8DIGR8zlaYMBILu8KOPrL2plorNCexxzNm-s,3136
414
+ setuptools/tests/test_dist.py,sha256=M4FikA-vL0_lZdA_5wry2Z9CBuSugr0Pj54dBZ3peBM,8951
415
+ setuptools/tests/test_dist_info.py,sha256=EihdrU9UZkPV7d19G-K_OtOByp64GvGnf4or-f8Iq54,5005
416
+ setuptools/tests/test_distutils_adoption.py,sha256=_eynrOfyEqXFEmjUJhzpe8GXPyTUPvNSObs4qAAmBy8,5987
417
+ setuptools/tests/test_editable_install.py,sha256=o4DkoytkiL-_rzES8p1q8XYRa9-ha_m6uhrm-EWzdwI,42498
418
+ setuptools/tests/test_egg_info.py,sha256=R7nT27YhVz9oSuDyimAGerWglkbRWiMSPBs5FzcSnBM,44941
419
+ setuptools/tests/test_extern.py,sha256=rpKU6oCcksumLwf5TeKlDluFQ0TUfbPwTLQbpxcFrCU,296
420
+ setuptools/tests/test_find_packages.py,sha256=CTLAcTzWGWBLCcd2aAsUVkvO3ibrlqexFBdDKOWPoq8,7819
421
+ setuptools/tests/test_find_py_modules.py,sha256=zQjuhIG5TQN2SJPix9ARo4DL_w84Ln8QsHDUjjbrtAQ,2404
422
+ setuptools/tests/test_glob.py,sha256=P3JvpH-kXQ4BZ3zvRF-zKxOgwyWzwIaQIz0WHdxS0kk,887
423
+ setuptools/tests/test_install_scripts.py,sha256=scIrJ6a_ssKqg4vIBNaUjmAKHEYLUUZ9WKnPeKnE6gc,3433
424
+ setuptools/tests/test_logging.py,sha256=czGLLdGxUBZKXbea3A0HnSW9lf-3K_CUwaI0gDkVbOM,2096
425
+ setuptools/tests/test_manifest.py,sha256=wKvTPxqrTJAJjjt4eJ03rXiIZTKA7xXogxaj5uFmhoo,20407
426
+ setuptools/tests/test_namespaces.py,sha256=e84seD5g6KIPVSDpawE9Ihc25Je7shooybV1flUsW20,2508
427
+ setuptools/tests/test_scripts.py,sha256=_ra506yQF7n72ROUDcz2r3CTsGsawO1m-1oqA9EQCfw,379
428
+ setuptools/tests/test_sdist.py,sha256=oKMgvBrkfTsPH5jqsrhFxRMbtUDoOy4vKfwll3kGCg0,32808
429
+ setuptools/tests/test_setopt.py,sha256=3VxxM4ATfP-P4AGnDjoWCnHr5-i9CSEQTFYU1-FTnvI,1365
430
+ setuptools/tests/test_setuptools.py,sha256=WqrZ8qbv9uJh2xzRn-wXam-YGzmG8od2spru3L3sMbg,9323
431
+ setuptools/tests/test_shutil_wrapper.py,sha256=g15E11PtZxG-InB2BWNFyH-svObXx2XcMhgMLJPuFnc,641
432
+ setuptools/tests/test_unicode_utils.py,sha256=xWfEEl8jkQCt9othUTXJfFmdyATAFggJs2tTxjbumbw,316
433
+ setuptools/tests/test_virtualenv.py,sha256=g-njC_9JTAs1YVx_1dGJ_Q6RlInO4qKVu9-XAgNb6TY,3730
434
+ setuptools/tests/test_warnings.py,sha256=zwR2zcnCeCeDqILZlJOPAcuyPHoDvGu1OtOVYiLMk74,3347
435
+ setuptools/tests/test_wheel.py,sha256=iMfVTNixu4puf6xvRYjQDw4Zg_OHVCQjSy7SztvVYqE,18722
436
+ setuptools/tests/test_windows_wrappers.py,sha256=wBjXN3iGldkzRGTgKTrx99xqUqwPJ0V-ldyiB1pWD-g,7868
437
+ setuptools/tests/text.py,sha256=a12197pMVTvB6FAWQ0ujT8fIQiLIWJlFAl1UCaDUDfg,123
438
+ setuptools/tests/textwrap.py,sha256=FNNNq_MiaEJx88PnsbJQIRxmj1qmgcAOCXXRsODPJN4,98
439
+ setuptools/unicode_utils.py,sha256=DkAGeONCVPH36O8pqFUVRz6d-YaZ6k1DFAmO5BRyHVI,3831
440
+ setuptools/version.py,sha256=WJCeUuyq74Aok2TeK9-OexZOu8XrlQy7-y0BEuWNovQ,161
441
+ setuptools/warnings.py,sha256=VKUJQBkbTZ3PPO52daOB1L1IerzeRdHGE0OtHm_fPa4,3785
442
+ setuptools/wheel.py,sha256=iI-LSDrgHMlJIzQMALVlJRq3Qesgbj7xa6hWZYJyZl4,9532
443
+ setuptools/windows_support.py,sha256=wW4IYLM1Bv7Z1MaauP2xmPjyy-wkmQnXdyvXscAf9fw,726
data/diffusion/.venv/lib/python3.11/site-packages/setuptools-83.0.0.dist-info/REQUESTED ADDED
File without changes
data/diffusion/.venv/lib/python3.11/site-packages/setuptools-83.0.0.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
data/diffusion/.venv/lib/python3.11/site-packages/setuptools-83.0.0.dist-info/entry_points.txt ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [distutils.commands]
2
+ alias = setuptools.command.alias:alias
3
+ bdist_egg = setuptools.command.bdist_egg:bdist_egg
4
+ bdist_rpm = setuptools.command.bdist_rpm:bdist_rpm
5
+ bdist_wheel = setuptools.command.bdist_wheel:bdist_wheel
6
+ build = setuptools.command.build:build
7
+ build_clib = setuptools.command.build_clib:build_clib
8
+ build_ext = setuptools.command.build_ext:build_ext
9
+ build_py = setuptools.command.build_py:build_py
10
+ develop = setuptools.command.develop:develop
11
+ dist_info = setuptools.command.dist_info:dist_info
12
+ easy_install = setuptools.command.easy_install:easy_install
13
+ editable_wheel = setuptools.command.editable_wheel:editable_wheel
14
+ egg_info = setuptools.command.egg_info:egg_info
15
+ install = setuptools.command.install:install
16
+ install_egg_info = setuptools.command.install_egg_info:install_egg_info
17
+ install_lib = setuptools.command.install_lib:install_lib
18
+ install_scripts = setuptools.command.install_scripts:install_scripts
19
+ rotate = setuptools.command.rotate:rotate
20
+ saveopts = setuptools.command.saveopts:saveopts
21
+ sdist = setuptools.command.sdist:sdist
22
+ setopt = setuptools.command.setopt:setopt
23
+
24
+ [distutils.setup_keywords]
25
+ dependency_links = setuptools.dist:assert_string_list
26
+ eager_resources = setuptools.dist:assert_string_list
27
+ entry_points = setuptools.dist:check_entry_points
28
+ exclude_package_data = setuptools.dist:check_package_data
29
+ extras_require = setuptools.dist:check_extras
30
+ include_package_data = setuptools.dist:assert_bool
31
+ install_requires = setuptools.dist:check_requirements
32
+ namespace_packages = setuptools.dist:check_nsp
33
+ package_data = setuptools.dist:check_package_data
34
+ packages = setuptools.dist:check_packages
35
+ python_requires = setuptools.dist:check_specifier
36
+ setup_requires = setuptools.dist:check_requirements
37
+ use_2to3 = setuptools.dist:invalid_unless_false
38
+ zip_safe = setuptools.dist:assert_bool
39
+
40
+ [egg_info.writers]
41
+ PKG-INFO = setuptools.command.egg_info:write_pkg_info
42
+ dependency_links.txt = setuptools.command.egg_info:overwrite_arg
43
+ eager_resources.txt = setuptools.command.egg_info:overwrite_arg
44
+ entry_points.txt = setuptools.command.egg_info:write_entries
45
+ namespace_packages.txt = setuptools.command.egg_info:overwrite_arg
46
+ requires.txt = setuptools.command.egg_info:write_requirements
47
+ top_level.txt = setuptools.command.egg_info:write_toplevel_names
48
+
49
+ [setuptools.finalize_distribution_options]
50
+ keywords = setuptools.dist:Distribution._finalize_setup_keywords
51
+ parent_finalize = setuptools.dist:_Distribution.finalize_options
data/diffusion/.venv/lib/python3.11/site-packages/setuptools-83.0.0.dist-info/top_level.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ _distutils_hack
2
+ setuptools
data/diffusion/.venv/lib/python3.11/site-packages/setuptools/__init__.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Extensions to the 'distutils' for large or complex distributions"""
2
+ # mypy: disable_error_code=override
3
+ # Command.reinitialize_command has an extra **kw param that distutils doesn't have
4
+ # Can't disable on the exact line because distutils doesn't exists on Python 3.12
5
+ # and mypy isn't aware of distutils_hack, causing distutils.core.Command to be Any,
6
+ # and a [unused-ignore] to be raised on 3.12+
7
+
8
+ from __future__ import annotations
9
+
10
+ import functools
11
+ import os
12
+ import sys
13
+ from abc import abstractmethod
14
+ from collections.abc import Mapping
15
+ from typing import TYPE_CHECKING, TypeVar, overload
16
+
17
+ sys.path.extend(((vendor_path := os.path.join(os.path.dirname(os.path.dirname(__file__)), 'setuptools', '_vendor')) not in sys.path) * [vendor_path]) # fmt: skip
18
+ # workaround for #4476
19
+ sys.modules.pop('backports', None)
20
+
21
+ import _distutils_hack.override # noqa: F401
22
+
23
+ from . import logging, monkey
24
+ from .depends import Require
25
+ from .discovery import PackageFinder, PEP420PackageFinder
26
+ from .dist import Distribution
27
+ from .extension import Extension
28
+ from .version import __version__ as __version__
29
+ from .warnings import SetuptoolsDeprecationWarning
30
+
31
+ import distutils.core
32
+
33
+ __all__ = [
34
+ 'setup',
35
+ 'Distribution',
36
+ 'Command',
37
+ 'Extension',
38
+ 'Require',
39
+ 'SetuptoolsDeprecationWarning',
40
+ 'find_packages',
41
+ 'find_namespace_packages',
42
+ ]
43
+
44
+ _CommandT = TypeVar("_CommandT", bound="_Command")
45
+
46
+ bootstrap_install_from = None
47
+
48
+ find_packages = PackageFinder.find
49
+ find_namespace_packages = PEP420PackageFinder.find
50
+
51
+
52
+ def _install_setup_requires(attrs):
53
+ # Note: do not use `setuptools.Distribution` directly, as
54
+ # our PEP 517 backend patch `distutils.core.Distribution`.
55
+ class MinimalDistribution(distutils.core.Distribution):
56
+ """
57
+ A minimal version of a distribution for supporting the
58
+ fetch_build_eggs interface.
59
+ """
60
+
61
+ def __init__(self, attrs: Mapping[str, object]) -> None:
62
+ _incl = 'dependency_links', 'setup_requires'
63
+ filtered = {k: attrs[k] for k in set(_incl) & set(attrs)}
64
+ super().__init__(filtered)
65
+ # Prevent accidentally triggering discovery with incomplete set of attrs
66
+ self.set_defaults._disable()
67
+
68
+ def _get_project_config_files(self, filenames=None):
69
+ """Ignore ``pyproject.toml``, they are not related to setup_requires"""
70
+ try:
71
+ cfg, _toml = super()._split_standard_project_metadata(filenames)
72
+ except Exception:
73
+ return filenames, ()
74
+ return cfg, ()
75
+
76
+ def finalize_options(self):
77
+ """
78
+ Disable finalize_options to avoid building the working set.
79
+ Ref #2158.
80
+ """
81
+
82
+ dist = MinimalDistribution(attrs)
83
+
84
+ # Honor setup.cfg's options.
85
+ dist.parse_config_files(ignore_option_errors=True)
86
+ if dist.setup_requires:
87
+ _fetch_build_eggs(dist)
88
+
89
+
90
+ def _fetch_build_eggs(dist: Distribution):
91
+ try:
92
+ dist.fetch_build_eggs(dist.setup_requires)
93
+ except Exception as ex:
94
+ msg = """
95
+ It is possible a package already installed in your system
96
+ contains an version that is invalid according to PEP 440.
97
+ You can try `pip install --use-pep517` as a workaround for this problem,
98
+ or rely on a new virtual environment.
99
+
100
+ If the problem refers to a package that is not installed yet,
101
+ please contact that package's maintainers or distributors.
102
+ """
103
+ if "InvalidVersion" in ex.__class__.__name__:
104
+ if hasattr(ex, "add_note"):
105
+ ex.add_note(msg) # PEP 678
106
+ else:
107
+ dist.announce(f"\n{msg}\n")
108
+ raise
109
+
110
+
111
+ def setup(**attrs) -> Distribution:
112
+ logging.configure()
113
+ # Make sure we have any requirements needed to interpret 'attrs'.
114
+ _install_setup_requires(attrs)
115
+ # Override return type of distutils.core.Distribution with setuptools.dist.Distribution
116
+ # (implicitly implemented via `setuptools.monkey.patch_all`).
117
+ return distutils.core.setup(**attrs) # type: ignore[return-value]
118
+
119
+
120
+ setup.__doc__ = distutils.core.setup.__doc__
121
+
122
+ if TYPE_CHECKING:
123
+ # Work around a mypy issue where type[T] can't be used as a base: https://github.com/python/mypy/issues/10962
124
+ from distutils.core import Command as _Command
125
+ else:
126
+ _Command = monkey.get_unpatched(distutils.core.Command)
127
+
128
+
129
+ class Command(_Command):
130
+ """
131
+ Setuptools internal actions are organized using a *command design pattern*.
132
+ This means that each action (or group of closely related actions) executed during
133
+ the build should be implemented as a ``Command`` subclass.
134
+
135
+ These commands are abstractions and do not necessarily correspond to a command that
136
+ can (or should) be executed via a terminal, in a CLI fashion (although historically
137
+ they would).
138
+
139
+ When creating a new command from scratch, custom defined classes **SHOULD** inherit
140
+ from ``setuptools.Command`` and implement a few mandatory methods.
141
+ Between these mandatory methods, are listed:
142
+ :meth:`initialize_options`, :meth:`finalize_options` and :meth:`run`.
143
+
144
+ A useful analogy for command classes is to think of them as subroutines with local
145
+ variables called "options". The options are "declared" in :meth:`initialize_options`
146
+ and "defined" (given their final values, aka "finalized") in :meth:`finalize_options`,
147
+ both of which must be defined by every command class. The "body" of the subroutine,
148
+ (where it does all the work) is the :meth:`run` method.
149
+ Between :meth:`initialize_options` and :meth:`finalize_options`, ``setuptools`` may set
150
+ the values for options/attributes based on user's input (or circumstance),
151
+ which means that the implementation should be careful to not overwrite values in
152
+ :meth:`finalize_options` unless necessary.
153
+
154
+ Please note that other commands (or other parts of setuptools) may also overwrite
155
+ the values of the command's options/attributes multiple times during the build
156
+ process.
157
+ Therefore it is important to consistently implement :meth:`initialize_options` and
158
+ :meth:`finalize_options`. For example, all derived attributes (or attributes that
159
+ depend on the value of other attributes) **SHOULD** be recomputed in
160
+ :meth:`finalize_options`.
161
+
162
+ When overwriting existing commands, custom defined classes **MUST** abide by the
163
+ same APIs implemented by the original class. They also **SHOULD** inherit from the
164
+ original class.
165
+ """
166
+
167
+ command_consumes_arguments = False
168
+ distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution
169
+
170
+ dry_run = False # type: ignore[assignment] # pyright: ignore[reportAssignmentType] (until #4689; see #4872)
171
+ """
172
+ For compatibility with vendored bdist_wheel.
173
+ https://github.com/pypa/setuptools/pull/4872/files#r1986395142
174
+ """
175
+
176
+ def __init__(self, dist: Distribution, **kw) -> None:
177
+ """
178
+ Construct the command for dist, updating
179
+ vars(self) with any keyword parameters.
180
+ """
181
+ super().__init__(dist)
182
+ vars(self).update(kw)
183
+
184
+ @overload
185
+ def reinitialize_command(
186
+ self, command: str, reinit_subcommands: bool = False, **kw
187
+ ) -> Command: ... # override distutils.cmd.Command with setuptools.Command
188
+ @overload
189
+ def reinitialize_command(
190
+ self, command: _CommandT, reinit_subcommands: bool = False, **kw
191
+ ) -> _CommandT: ...
192
+ def reinitialize_command(
193
+ self, command: str | _Command, reinit_subcommands: bool = False, **kw
194
+ ) -> Command | _Command:
195
+ cmd = _Command.reinitialize_command(self, command, reinit_subcommands)
196
+ vars(cmd).update(kw)
197
+ return cmd # pyright: ignore[reportReturnType] # pypa/distutils#307
198
+
199
+ @abstractmethod
200
+ def initialize_options(self) -> None:
201
+ """
202
+ Set or (reset) all options/attributes/caches used by the command
203
+ to their default values. Note that these values may be overwritten during
204
+ the build.
205
+ """
206
+ raise NotImplementedError
207
+
208
+ @abstractmethod
209
+ def finalize_options(self) -> None:
210
+ """
211
+ Set final values for all options/attributes used by the command.
212
+ Most of the time, each option/attribute/cache should only be set if it does not
213
+ have any value yet (e.g. ``if self.attr is None: self.attr = val``).
214
+ """
215
+ raise NotImplementedError
216
+
217
+ @abstractmethod
218
+ def run(self) -> None:
219
+ """
220
+ Execute the actions intended by the command.
221
+ (Side effects **SHOULD** only take place when :meth:`run` is executed,
222
+ for example, creating new files or writing to the terminal output).
223
+ """
224
+ raise NotImplementedError
225
+
226
+
227
+ def _find_all_simple(path):
228
+ """
229
+ Find all files under 'path'
230
+ """
231
+ results = (
232
+ os.path.join(base, file)
233
+ for base, dirs, files in os.walk(path, followlinks=True)
234
+ for file in files
235
+ )
236
+ return filter(os.path.isfile, results)
237
+
238
+
239
+ def findall(dir=os.curdir):
240
+ """
241
+ Find all files under 'dir' and return the list of full filenames.
242
+ Unless dir is '.', return full filenames with dir prepended.
243
+ """
244
+ files = _find_all_simple(dir)
245
+ if dir == os.curdir:
246
+ make_rel = functools.partial(os.path.relpath, start=dir)
247
+ files = map(make_rel, files)
248
+ return list(files)
249
+
250
+
251
+ class sic(str):
252
+ """Treat this string as-is (https://en.wikipedia.org/wiki/Sic)"""
253
+
254
+
255
+ # Apply monkey patches
256
+ monkey.patch_all()
data/diffusion/.venv/lib/python3.11/site-packages/setuptools/_discovery.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import operator
3
+
4
+ import packaging.requirements
5
+
6
+
7
+ # from coherent.build.discovery
8
+ def extras_from_dep(dep):
9
+ try:
10
+ markers = packaging.requirements.Requirement(dep).marker._markers
11
+ except AttributeError:
12
+ markers = ()
13
+ return set(
14
+ marker[2].value
15
+ for marker in markers
16
+ if isinstance(marker, tuple) and marker[0].value == 'extra'
17
+ )
18
+
19
+
20
+ def extras_from_deps(deps):
21
+ """
22
+ >>> extras_from_deps(['requests'])
23
+ set()
24
+ >>> extras_from_deps(['pytest; extra == "test"'])
25
+ {'test'}
26
+ >>> sorted(extras_from_deps([
27
+ ... 'requests',
28
+ ... 'pytest; extra == "test"',
29
+ ... 'pytest-cov; extra == "test"',
30
+ ... 'sphinx; extra=="doc"']))
31
+ ['doc', 'test']
32
+ """
33
+ return functools.reduce(operator.or_, map(extras_from_dep, deps), set())
data/diffusion/.venv/lib/python3.11/site-packages/setuptools/_entry_points.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import itertools
3
+ import operator
4
+
5
+ from jaraco.functools import pass_none
6
+ from jaraco.text import yield_lines
7
+ from more_itertools import consume
8
+
9
+ from ._importlib import metadata
10
+ from ._itertools import ensure_unique
11
+ from .errors import OptionError
12
+
13
+
14
+ def ensure_valid(ep):
15
+ """
16
+ Exercise one of the dynamic properties to trigger
17
+ the pattern match.
18
+
19
+ This function is deprecated in favor of importlib_metadata 8.7 and
20
+ Python 3.14 importlib.metadata, which validates entry points on
21
+ construction.
22
+ """
23
+ try:
24
+ ep.extras
25
+ except (AttributeError, AssertionError) as ex:
26
+ # Why both? See https://github.com/python/importlib_metadata/issues/488
27
+ msg = (
28
+ f"Problems to parse {ep}.\nPlease ensure entry-point follows the spec: "
29
+ "https://packaging.python.org/en/latest/specifications/entry-points/"
30
+ )
31
+ raise OptionError(msg) from ex
32
+
33
+
34
+ def load_group(value, group):
35
+ """
36
+ Given a value of an entry point or series of entry points,
37
+ return each as an EntryPoint.
38
+ """
39
+ # normalize to a single sequence of lines
40
+ lines = yield_lines(value)
41
+ text = f'[{group}]\n' + '\n'.join(lines)
42
+ return metadata.EntryPoints._from_text(text)
43
+
44
+
45
+ def by_group_and_name(ep):
46
+ return ep.group, ep.name
47
+
48
+
49
+ def validate(eps: metadata.EntryPoints):
50
+ """
51
+ Ensure entry points are unique by group and name and validate each.
52
+ """
53
+ consume(map(ensure_valid, ensure_unique(eps, key=by_group_and_name)))
54
+ return eps
55
+
56
+
57
+ @functools.singledispatch
58
+ def load(eps):
59
+ """
60
+ Given a Distribution.entry_points, produce EntryPoints.
61
+ """
62
+ groups = itertools.chain.from_iterable(
63
+ load_group(value, group) for group, value in eps.items()
64
+ )
65
+ return validate(metadata.EntryPoints(groups))
66
+
67
+
68
+ @load.register(str)
69
+ def _(eps):
70
+ r"""
71
+ >>> ep, = load('[console_scripts]\nfoo=bar')
72
+ >>> ep.group
73
+ 'console_scripts'
74
+ >>> ep.name
75
+ 'foo'
76
+ >>> ep.value
77
+ 'bar'
78
+ """
79
+ return validate(metadata.EntryPoints(metadata.EntryPoints._from_text(eps)))
80
+
81
+
82
+ load.register(type(None), lambda x: x)
83
+
84
+
85
+ @pass_none
86
+ def render(eps: metadata.EntryPoints):
87
+ by_group = operator.attrgetter('group')
88
+ groups = itertools.groupby(sorted(eps, key=by_group), by_group)
89
+
90
+ return '\n'.join(f'[{group}]\n{render_items(items)}\n' for group, items in groups)
91
+
92
+
93
+ def render_items(eps):
94
+ return '\n'.join(f'{ep.name} = {ep.value}' for ep in sorted(eps))
data/diffusion/.venv/lib/python3.11/site-packages/setuptools/_importlib.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ import importlib.metadata as metadata # noqa: F401
2
+ import importlib.resources as resources # noqa: F401
data/diffusion/.venv/lib/python3.11/site-packages/setuptools/_itertools.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from more_itertools import consume # noqa: F401
2
+
3
+
4
+ # copied from jaraco.itertools 6.1
5
+ def ensure_unique(iterable, key=lambda x: x):
6
+ """
7
+ Wrap an iterable to raise a ValueError if non-unique values are encountered.
8
+
9
+ >>> list(ensure_unique('abc'))
10
+ ['a', 'b', 'c']
11
+ >>> consume(ensure_unique('abca'))
12
+ Traceback (most recent call last):
13
+ ...
14
+ ValueError: Duplicate element 'a' encountered.
15
+ """
16
+ seen = set()
17
+ seen_add = seen.add
18
+ for element in iterable:
19
+ k = key(element)
20
+ if k in seen:
21
+ raise ValueError(f"Duplicate element {element!r} encountered.")
22
+ seen_add(k)
23
+ yield element