assassinlike commited on
Commit
c348a38
·
verified ·
1 Parent(s): 26c6196

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/miniconda3/lib/python3.13/site-packages/_distutils_hack/__init__.py +239 -0
  2. data/miniconda3/lib/python3.13/site-packages/_distutils_hack/override.py +1 -0
  3. data/miniconda3/lib/python3.13/site-packages/anthropic/__init__.py +121 -0
  4. data/miniconda3/lib/python3.13/site-packages/anthropic/_base_client.py +2271 -0
  5. data/miniconda3/lib/python3.13/site-packages/anthropic/_client.py +659 -0
  6. data/miniconda3/lib/python3.13/site-packages/anthropic/_compat.py +232 -0
  7. data/miniconda3/lib/python3.13/site-packages/anthropic/_constants.py +29 -0
  8. data/miniconda3/lib/python3.13/site-packages/anthropic/_exceptions.py +140 -0
  9. data/miniconda3/lib/python3.13/site-packages/anthropic/_files.py +123 -0
  10. data/miniconda3/lib/python3.13/site-packages/anthropic/_legacy_response.py +514 -0
  11. data/miniconda3/lib/python3.13/site-packages/anthropic/_models.py +918 -0
  12. data/miniconda3/lib/python3.13/site-packages/anthropic/_qs.py +153 -0
  13. data/miniconda3/lib/python3.13/site-packages/anthropic/_resource.py +41 -0
  14. data/miniconda3/lib/python3.13/site-packages/anthropic/_response.py +875 -0
  15. data/miniconda3/lib/python3.13/site-packages/anthropic/_streaming.py +450 -0
  16. data/miniconda3/lib/python3.13/site-packages/anthropic/_types.py +272 -0
  17. data/miniconda3/lib/python3.13/site-packages/anthropic/_version.py +4 -0
  18. data/miniconda3/lib/python3.13/site-packages/anthropic/pagination.py +182 -0
  19. data/miniconda3/lib/python3.13/site-packages/anthropic/py.typed +0 -0
  20. data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/INSTALLER +1 -0
  21. data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/METADATA +105 -0
  22. data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/RECORD +92 -0
  23. data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/WHEEL +5 -0
  24. data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/entry_points.txt +2 -0
  25. data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/top_level.txt +1 -0
  26. data/miniconda3/lib/python3.13/site-packages/charset_normalizer/__init__.py +48 -0
  27. data/miniconda3/lib/python3.13/site-packages/charset_normalizer/__main__.py +6 -0
  28. data/miniconda3/lib/python3.13/site-packages/charset_normalizer/api.py +669 -0
  29. data/miniconda3/lib/python3.13/site-packages/charset_normalizer/cd.py +395 -0
  30. data/miniconda3/lib/python3.13/site-packages/charset_normalizer/constant.py +2015 -0
  31. data/miniconda3/lib/python3.13/site-packages/charset_normalizer/legacy.py +80 -0
  32. data/miniconda3/lib/python3.13/site-packages/charset_normalizer/md.py +635 -0
  33. data/miniconda3/lib/python3.13/site-packages/charset_normalizer/models.py +360 -0
  34. data/miniconda3/lib/python3.13/site-packages/charset_normalizer/py.typed +0 -0
  35. data/miniconda3/lib/python3.13/site-packages/charset_normalizer/utils.py +414 -0
  36. data/miniconda3/lib/python3.13/site-packages/charset_normalizer/version.py +8 -0
  37. data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/INSTALLER +1 -0
  38. data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/METADATA +85 -0
  39. data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/RECORD +37 -0
  40. data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/REQUESTED +0 -0
  41. data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/WHEEL +4 -0
  42. data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/direct_url.json +1 -0
  43. data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/entry_points.txt +2 -0
  44. data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/__init__.py +1 -0
  45. data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/create.py +191 -0
  46. data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/exceptions.py +19 -0
  47. data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/extract.py +93 -0
  48. data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/lazy_wheel.py +331 -0
  49. data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/package_streaming.py +154 -0
  50. data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/s3.py +83 -0
data/miniconda3/lib/python3.13/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/miniconda3/lib/python3.13/site-packages/_distutils_hack/override.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __import__('_distutils_hack').do_override()
data/miniconda3/lib/python3.13/site-packages/anthropic/__init__.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ import typing as _t
4
+
5
+ from . import types
6
+ from ._types import NOT_GIVEN, Omit, NoneType, NotGiven, Transport, ProxiesTypes, omit, not_given
7
+ from ._utils import file_from_path
8
+ from ._client import (
9
+ Client,
10
+ Stream,
11
+ Timeout,
12
+ Anthropic,
13
+ Transport,
14
+ AsyncClient,
15
+ AsyncStream,
16
+ AsyncAnthropic,
17
+ RequestOptions,
18
+ )
19
+ from ._models import BaseModel
20
+ from ._version import __title__, __version__
21
+ from ._response import APIResponse as APIResponse, AsyncAPIResponse as AsyncAPIResponse
22
+ from ._constants import (
23
+ AI_PROMPT as AI_PROMPT,
24
+ HUMAN_PROMPT as HUMAN_PROMPT,
25
+ DEFAULT_TIMEOUT,
26
+ DEFAULT_MAX_RETRIES,
27
+ DEFAULT_CONNECTION_LIMITS,
28
+ )
29
+ from ._exceptions import (
30
+ APIError,
31
+ ConflictError,
32
+ NotFoundError,
33
+ AnthropicError,
34
+ APIStatusError,
35
+ RateLimitError,
36
+ APITimeoutError,
37
+ BadRequestError,
38
+ APIConnectionError,
39
+ AuthenticationError,
40
+ InternalServerError,
41
+ PermissionDeniedError,
42
+ UnprocessableEntityError,
43
+ APIResponseValidationError,
44
+ )
45
+ from ._base_client import DefaultHttpxClient, DefaultAioHttpClient, DefaultAsyncHttpxClient
46
+ from ._utils._logs import setup_logging as _setup_logging
47
+ from .lib._parse._transform import transform_schema
48
+
49
+ __all__ = [
50
+ "types",
51
+ "__version__",
52
+ "__title__",
53
+ "NoneType",
54
+ "Transport",
55
+ "ProxiesTypes",
56
+ "NotGiven",
57
+ "NOT_GIVEN",
58
+ "not_given",
59
+ "Omit",
60
+ "omit",
61
+ "AnthropicError",
62
+ "APIError",
63
+ "APIStatusError",
64
+ "APITimeoutError",
65
+ "APIConnectionError",
66
+ "APIResponseValidationError",
67
+ "BadRequestError",
68
+ "AuthenticationError",
69
+ "PermissionDeniedError",
70
+ "NotFoundError",
71
+ "ConflictError",
72
+ "UnprocessableEntityError",
73
+ "RateLimitError",
74
+ "InternalServerError",
75
+ "Timeout",
76
+ "RequestOptions",
77
+ "Client",
78
+ "AsyncClient",
79
+ "Stream",
80
+ "AsyncStream",
81
+ "Anthropic",
82
+ "AsyncAnthropic",
83
+ "file_from_path",
84
+ "BaseModel",
85
+ "DEFAULT_TIMEOUT",
86
+ "DEFAULT_MAX_RETRIES",
87
+ "DEFAULT_CONNECTION_LIMITS",
88
+ "DefaultHttpxClient",
89
+ "DefaultAsyncHttpxClient",
90
+ "DefaultAioHttpClient",
91
+ "HUMAN_PROMPT",
92
+ "AI_PROMPT",
93
+ "beta_tool",
94
+ "beta_async_tool",
95
+ "transform_schema",
96
+ ]
97
+
98
+ if not _t.TYPE_CHECKING:
99
+ from ._utils._resources_proxy import resources as resources
100
+
101
+ from .lib.aws import AnthropicAWS as AnthropicAWS, AsyncAnthropicAWS as AsyncAnthropicAWS
102
+ from .lib.tools import beta_tool, beta_async_tool
103
+ from .lib.vertex import *
104
+ from .lib.bedrock import *
105
+ from .lib.foundry import AnthropicFoundry as AnthropicFoundry, AsyncAnthropicFoundry as AsyncAnthropicFoundry
106
+ from .lib.streaming import *
107
+
108
+ _setup_logging()
109
+
110
+ # Update the __module__ attribute for exported symbols so that
111
+ # error messages point to this module instead of the module
112
+ # it was originally defined in, e.g.
113
+ # anthropic._exceptions.NotFoundError -> anthropic.NotFoundError
114
+ __locals = locals()
115
+ for __name in __all__:
116
+ if not __name.startswith("__"):
117
+ try:
118
+ __locals[__name].__module__ = "anthropic"
119
+ except (TypeError, AttributeError):
120
+ # Some of our exported symbols are builtins which we can't set attributes for.
121
+ pass
data/miniconda3/lib/python3.13/site-packages/anthropic/_base_client.py ADDED
@@ -0,0 +1,2271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ import json
5
+ import time
6
+ import uuid
7
+ import email
8
+ import socket
9
+ import asyncio
10
+ import inspect
11
+ import logging
12
+ import platform
13
+ import warnings
14
+ import email.utils
15
+ from types import TracebackType
16
+ from random import random
17
+ from typing import (
18
+ TYPE_CHECKING,
19
+ Any,
20
+ Dict,
21
+ List,
22
+ Type,
23
+ Tuple,
24
+ Union,
25
+ Generic,
26
+ Mapping,
27
+ TypeVar,
28
+ Iterable,
29
+ Iterator,
30
+ Optional,
31
+ Generator,
32
+ AsyncIterator,
33
+ cast,
34
+ overload,
35
+ )
36
+ from typing_extensions import Literal, override, get_origin
37
+
38
+ import anyio
39
+ import httpx
40
+ import distro
41
+ import pydantic
42
+ from httpx import URL, Proxy, HTTPTransport, AsyncHTTPTransport
43
+ from pydantic import PrivateAttr
44
+
45
+ from . import _exceptions
46
+ from ._qs import Querystring
47
+ from ._files import to_httpx_files, async_to_httpx_files
48
+ from ._types import (
49
+ Body,
50
+ Omit,
51
+ Query,
52
+ Headers,
53
+ Timeout,
54
+ NotGiven,
55
+ ResponseT,
56
+ AnyMapping,
57
+ PostParser,
58
+ BinaryTypes,
59
+ RequestFiles,
60
+ HttpxSendArgs,
61
+ RequestOptions,
62
+ AsyncBinaryTypes,
63
+ HttpxRequestFiles,
64
+ ModelBuilderProtocol,
65
+ not_given,
66
+ )
67
+ from ._utils import is_dict, is_list, asyncify, is_given, lru_cache, is_mapping
68
+ from ._compat import PYDANTIC_V1, model_copy, model_dump
69
+ from ._models import GenericModel, FinalRequestOptions, validate_type, construct_type
70
+ from ._response import (
71
+ APIResponse,
72
+ BaseAPIResponse,
73
+ AsyncAPIResponse,
74
+ extract_response_type,
75
+ )
76
+ from ._constants import (
77
+ DEFAULT_TIMEOUT,
78
+ MAX_RETRY_DELAY,
79
+ DEFAULT_MAX_RETRIES,
80
+ INITIAL_RETRY_DELAY,
81
+ RAW_RESPONSE_HEADER,
82
+ OVERRIDE_CAST_TO_HEADER,
83
+ DEFAULT_CONNECTION_LIMITS,
84
+ )
85
+ from ._streaming import Stream, SSEDecoder, AsyncStream, SSEBytesDecoder
86
+ from ._exceptions import (
87
+ APIStatusError,
88
+ APITimeoutError,
89
+ APIConnectionError,
90
+ APIResponseValidationError,
91
+ )
92
+ from ._utils._json import openapi_dumps
93
+ from ._utils._httpx import get_environment_proxies
94
+ from ._legacy_response import LegacyAPIResponse
95
+
96
+ log: logging.Logger = logging.getLogger(__name__)
97
+
98
+ # TODO: make base page type vars covariant
99
+ SyncPageT = TypeVar("SyncPageT", bound="BaseSyncPage[Any]")
100
+ AsyncPageT = TypeVar("AsyncPageT", bound="BaseAsyncPage[Any]")
101
+
102
+
103
+ _T = TypeVar("_T")
104
+ _T_co = TypeVar("_T_co", covariant=True)
105
+
106
+ _StreamT = TypeVar("_StreamT", bound=Stream[Any])
107
+ _AsyncStreamT = TypeVar("_AsyncStreamT", bound=AsyncStream[Any])
108
+
109
+ if TYPE_CHECKING:
110
+ from httpx._config import (
111
+ DEFAULT_TIMEOUT_CONFIG, # pyright: ignore[reportPrivateImportUsage]
112
+ )
113
+
114
+ HTTPX_DEFAULT_TIMEOUT = DEFAULT_TIMEOUT_CONFIG
115
+ else:
116
+ try:
117
+ from httpx._config import DEFAULT_TIMEOUT_CONFIG as HTTPX_DEFAULT_TIMEOUT
118
+ except ImportError:
119
+ # taken from https://github.com/encode/httpx/blob/3ba5fe0d7ac70222590e759c31442b1cab263791/httpx/_config.py#L366
120
+ HTTPX_DEFAULT_TIMEOUT = Timeout(5.0)
121
+
122
+
123
+ class PageInfo:
124
+ """Stores the necessary information to build the request to retrieve the next page.
125
+
126
+ Either `url` or `params` must be set.
127
+ """
128
+
129
+ url: URL | NotGiven
130
+ params: Query | NotGiven
131
+ json: Body | NotGiven
132
+
133
+ @overload
134
+ def __init__(
135
+ self,
136
+ *,
137
+ url: URL,
138
+ ) -> None: ...
139
+
140
+ @overload
141
+ def __init__(
142
+ self,
143
+ *,
144
+ params: Query,
145
+ ) -> None: ...
146
+
147
+ @overload
148
+ def __init__(
149
+ self,
150
+ *,
151
+ json: Body,
152
+ ) -> None: ...
153
+
154
+ def __init__(
155
+ self,
156
+ *,
157
+ url: URL | NotGiven = not_given,
158
+ json: Body | NotGiven = not_given,
159
+ params: Query | NotGiven = not_given,
160
+ ) -> None:
161
+ self.url = url
162
+ self.json = json
163
+ self.params = params
164
+
165
+ @override
166
+ def __repr__(self) -> str:
167
+ if self.url:
168
+ return f"{self.__class__.__name__}(url={self.url})"
169
+ if self.json:
170
+ return f"{self.__class__.__name__}(json={self.json})"
171
+ return f"{self.__class__.__name__}(params={self.params})"
172
+
173
+
174
+ class BasePage(GenericModel, Generic[_T]):
175
+ """
176
+ Defines the core interface for pagination.
177
+
178
+ Type Args:
179
+ ModelT: The pydantic model that represents an item in the response.
180
+
181
+ Methods:
182
+ has_next_page(): Check if there is another page available
183
+ next_page_info(): Get the necessary information to make a request for the next page
184
+ """
185
+
186
+ _options: FinalRequestOptions = PrivateAttr()
187
+ _model: Type[_T] = PrivateAttr()
188
+
189
+ def has_next_page(self) -> bool:
190
+ items = self._get_page_items()
191
+ if not items:
192
+ return False
193
+ return self.next_page_info() is not None
194
+
195
+ def next_page_info(self) -> Optional[PageInfo]: ...
196
+
197
+ def _get_page_items(self) -> Iterable[_T]: # type: ignore[empty-body]
198
+ ...
199
+
200
+ def _params_from_url(self, url: URL) -> httpx.QueryParams:
201
+ # TODO: do we have to preprocess params here?
202
+ return httpx.QueryParams(cast(Any, self._options.params)).merge(url.params)
203
+
204
+ def _info_to_options(self, info: PageInfo) -> FinalRequestOptions:
205
+ options = model_copy(self._options)
206
+ options._strip_raw_response_header()
207
+
208
+ if not isinstance(info.params, NotGiven):
209
+ options.params = {**options.params, **info.params}
210
+ return options
211
+
212
+ if not isinstance(info.url, NotGiven):
213
+ params = self._params_from_url(info.url)
214
+ url = info.url.copy_with(params=params)
215
+ options.params = dict(url.params)
216
+ options.url = str(url)
217
+ return options
218
+
219
+ if not isinstance(info.json, NotGiven):
220
+ if not is_mapping(info.json):
221
+ raise TypeError("Pagination is only supported with mappings")
222
+
223
+ if not options.json_data:
224
+ options.json_data = {**info.json}
225
+ else:
226
+ if not is_mapping(options.json_data):
227
+ raise TypeError("Pagination is only supported with mappings")
228
+
229
+ options.json_data = {**options.json_data, **info.json}
230
+ return options
231
+
232
+ raise ValueError("Unexpected PageInfo state")
233
+
234
+
235
+ class BaseSyncPage(BasePage[_T], Generic[_T]):
236
+ _client: SyncAPIClient = pydantic.PrivateAttr()
237
+
238
+ def _set_private_attributes(
239
+ self,
240
+ client: SyncAPIClient,
241
+ model: Type[_T],
242
+ options: FinalRequestOptions,
243
+ ) -> None:
244
+ if (not PYDANTIC_V1) and getattr(self, "__pydantic_private__", None) is None:
245
+ self.__pydantic_private__ = {}
246
+
247
+ self._model = model
248
+ self._client = client
249
+ self._options = options
250
+
251
+ # Pydantic uses a custom `__iter__` method to support casting BaseModels
252
+ # to dictionaries. e.g. dict(model).
253
+ # As we want to support `for item in page`, this is inherently incompatible
254
+ # with the default pydantic behaviour. It is not possible to support both
255
+ # use cases at once. Fortunately, this is not a big deal as all other pydantic
256
+ # methods should continue to work as expected as there is an alternative method
257
+ # to cast a model to a dictionary, model.dict(), which is used internally
258
+ # by pydantic.
259
+ def __iter__(self) -> Iterator[_T]: # type: ignore
260
+ for page in self.iter_pages():
261
+ for item in page._get_page_items():
262
+ yield item
263
+
264
+ def iter_pages(self: SyncPageT) -> Iterator[SyncPageT]:
265
+ page = self
266
+ while True:
267
+ yield page
268
+ if page.has_next_page():
269
+ page = page.get_next_page()
270
+ else:
271
+ return
272
+
273
+ def get_next_page(self: SyncPageT) -> SyncPageT:
274
+ info = self.next_page_info()
275
+ if not info:
276
+ raise RuntimeError(
277
+ "No next page expected; please check `.has_next_page()` before calling `.get_next_page()`."
278
+ )
279
+
280
+ options = self._info_to_options(info)
281
+ return self._client._request_api_list(self._model, page=self.__class__, options=options)
282
+
283
+
284
+ class AsyncPaginator(Generic[_T, AsyncPageT]):
285
+ def __init__(
286
+ self,
287
+ client: AsyncAPIClient,
288
+ options: FinalRequestOptions,
289
+ page_cls: Type[AsyncPageT],
290
+ model: Type[_T],
291
+ ) -> None:
292
+ self._model = model
293
+ self._client = client
294
+ self._options = options
295
+ self._page_cls = page_cls
296
+
297
+ def __await__(self) -> Generator[Any, None, AsyncPageT]:
298
+ return self._get_page().__await__()
299
+
300
+ async def _get_page(self) -> AsyncPageT:
301
+ def _parser(resp: AsyncPageT) -> AsyncPageT:
302
+ resp._set_private_attributes(
303
+ model=self._model,
304
+ options=self._options,
305
+ client=self._client,
306
+ )
307
+ return resp
308
+
309
+ self._options.post_parser = _parser
310
+
311
+ return await self._client.request(self._page_cls, self._options)
312
+
313
+ async def __aiter__(self) -> AsyncIterator[_T]:
314
+ # https://github.com/microsoft/pyright/issues/3464
315
+ page = cast(
316
+ AsyncPageT,
317
+ await self, # type: ignore
318
+ )
319
+ async for item in page:
320
+ yield item
321
+
322
+
323
+ class BaseAsyncPage(BasePage[_T], Generic[_T]):
324
+ _client: AsyncAPIClient = pydantic.PrivateAttr()
325
+
326
+ def _set_private_attributes(
327
+ self,
328
+ model: Type[_T],
329
+ client: AsyncAPIClient,
330
+ options: FinalRequestOptions,
331
+ ) -> None:
332
+ if (not PYDANTIC_V1) and getattr(self, "__pydantic_private__", None) is None:
333
+ self.__pydantic_private__ = {}
334
+
335
+ self._model = model
336
+ self._client = client
337
+ self._options = options
338
+
339
+ async def __aiter__(self) -> AsyncIterator[_T]:
340
+ async for page in self.iter_pages():
341
+ for item in page._get_page_items():
342
+ yield item
343
+
344
+ async def iter_pages(self: AsyncPageT) -> AsyncIterator[AsyncPageT]:
345
+ page = self
346
+ while True:
347
+ yield page
348
+ if page.has_next_page():
349
+ page = await page.get_next_page()
350
+ else:
351
+ return
352
+
353
+ async def get_next_page(self: AsyncPageT) -> AsyncPageT:
354
+ info = self.next_page_info()
355
+ if not info:
356
+ raise RuntimeError(
357
+ "No next page expected; please check `.has_next_page()` before calling `.get_next_page()`."
358
+ )
359
+
360
+ options = self._info_to_options(info)
361
+ return await self._client._request_api_list(self._model, page=self.__class__, options=options)
362
+
363
+
364
+ _HttpxClientT = TypeVar("_HttpxClientT", bound=Union[httpx.Client, httpx.AsyncClient])
365
+ _DefaultStreamT = TypeVar("_DefaultStreamT", bound=Union[Stream[Any], AsyncStream[Any]])
366
+
367
+
368
+ class BaseClient(Generic[_HttpxClientT, _DefaultStreamT]):
369
+ _client: _HttpxClientT
370
+ _version: str
371
+ _base_url: URL
372
+ max_retries: int
373
+ timeout: Union[float, Timeout, None]
374
+ _strict_response_validation: bool
375
+ _idempotency_header: str | None
376
+ _default_stream_cls: type[_DefaultStreamT] | None = None
377
+
378
+ def __init__(
379
+ self,
380
+ *,
381
+ version: str,
382
+ base_url: str | URL,
383
+ _strict_response_validation: bool,
384
+ max_retries: int = DEFAULT_MAX_RETRIES,
385
+ timeout: float | Timeout | None = DEFAULT_TIMEOUT,
386
+ custom_headers: Mapping[str, str] | None = None,
387
+ custom_query: Mapping[str, object] | None = None,
388
+ ) -> None:
389
+ self._version = version
390
+ self._base_url = self._enforce_trailing_slash(URL(base_url))
391
+ self.max_retries = max_retries
392
+ self.timeout = timeout
393
+ self._custom_headers = custom_headers or {}
394
+ self._custom_query = custom_query or {}
395
+ self._strict_response_validation = _strict_response_validation
396
+ self._idempotency_header = None
397
+ self._platform: Platform | None = None
398
+
399
+ if max_retries is None: # pyright: ignore[reportUnnecessaryComparison]
400
+ raise TypeError(
401
+ "max_retries cannot be None. If you want to disable retries, pass `0`; if you want unlimited retries, pass `math.inf` or a very high number; if you want the default behavior, pass `anthropic.DEFAULT_MAX_RETRIES`"
402
+ )
403
+
404
+ def _enforce_trailing_slash(self, url: URL) -> URL:
405
+ if url.raw_path.endswith(b"/"):
406
+ return url
407
+ return url.copy_with(raw_path=url.raw_path + b"/")
408
+
409
+ def _make_status_error_from_response(
410
+ self,
411
+ response: httpx.Response,
412
+ ) -> APIStatusError:
413
+ if response.is_closed and not response.is_stream_consumed:
414
+ # We can't read the response body as it has been closed
415
+ # before it was read. This can happen if an event hook
416
+ # raises a status error.
417
+ body = None
418
+ err_msg = f"Error code: {response.status_code}"
419
+ else:
420
+ err_text = response.text.strip()
421
+ body = err_text
422
+
423
+ try:
424
+ body = json.loads(err_text)
425
+ err_msg = f"Error code: {response.status_code} - {body}"
426
+ except Exception:
427
+ err_msg = err_text or f"Error code: {response.status_code}"
428
+
429
+ return self._make_status_error(err_msg, body=body, response=response)
430
+
431
+ def _make_status_error(
432
+ self,
433
+ err_msg: str,
434
+ *,
435
+ body: object,
436
+ response: httpx.Response,
437
+ ) -> _exceptions.APIStatusError:
438
+ raise NotImplementedError()
439
+
440
+ def _build_headers(self, options: FinalRequestOptions, *, retries_taken: int = 0) -> httpx.Headers:
441
+ custom_headers = options.headers or {}
442
+ headers_dict = _merge_mappings(
443
+ {
444
+ "x-stainless-timeout": str(options.timeout.read)
445
+ if isinstance(options.timeout, Timeout)
446
+ else str(options.timeout),
447
+ **self.default_headers,
448
+ },
449
+ custom_headers,
450
+ )
451
+ self._validate_headers(headers_dict, custom_headers)
452
+
453
+ # headers are case-insensitive while dictionaries are not.
454
+ headers = httpx.Headers(headers_dict)
455
+
456
+ idempotency_header = self._idempotency_header
457
+ if idempotency_header and options.idempotency_key and idempotency_header not in headers:
458
+ headers[idempotency_header] = options.idempotency_key
459
+
460
+ # Don't set these headers if they were already set or removed by the caller. We check
461
+ # `custom_headers`, which can contain `Omit()`, instead of `headers` to account for the removal case.
462
+ lower_custom_headers = [header.lower() for header in custom_headers]
463
+ if "x-stainless-retry-count" not in lower_custom_headers:
464
+ headers["x-stainless-retry-count"] = str(retries_taken)
465
+ if "x-stainless-read-timeout" not in lower_custom_headers:
466
+ timeout = self.timeout if isinstance(options.timeout, NotGiven) else options.timeout
467
+ if isinstance(timeout, Timeout):
468
+ timeout = timeout.read
469
+ if timeout is not None:
470
+ headers["x-stainless-read-timeout"] = str(timeout)
471
+
472
+ return headers
473
+
474
+ def _prepare_url(self, url: str) -> URL:
475
+ """
476
+ Merge a URL argument together with any 'base_url' on the client,
477
+ to create the URL used for the outgoing request.
478
+ """
479
+ # Copied from httpx's `_merge_url` method.
480
+ merge_url = URL(url)
481
+ if merge_url.is_relative_url:
482
+ merge_raw_path = self.base_url.raw_path + merge_url.raw_path.lstrip(b"/")
483
+ return self.base_url.copy_with(raw_path=merge_raw_path)
484
+
485
+ return merge_url
486
+
487
+ def _make_sse_decoder(self) -> SSEDecoder | SSEBytesDecoder:
488
+ return SSEDecoder()
489
+
490
+ def _build_request(
491
+ self,
492
+ options: FinalRequestOptions,
493
+ *,
494
+ retries_taken: int = 0,
495
+ ) -> httpx.Request:
496
+ if log.isEnabledFor(logging.DEBUG):
497
+ log.debug(
498
+ "Request options: %s",
499
+ model_dump(
500
+ options,
501
+ exclude_unset=True,
502
+ # Pydantic v1 can't dump every type we support in content, so we exclude it for now.
503
+ exclude={
504
+ "content",
505
+ }
506
+ if PYDANTIC_V1
507
+ else {},
508
+ ),
509
+ )
510
+ kwargs: dict[str, Any] = {}
511
+
512
+ json_data = options.json_data
513
+ if options.extra_json is not None:
514
+ if json_data is None:
515
+ json_data = cast(Body, options.extra_json)
516
+ elif is_mapping(json_data):
517
+ json_data = _merge_mappings(json_data, options.extra_json)
518
+ else:
519
+ raise RuntimeError(f"Unexpected JSON data type, {type(json_data)}, cannot merge with `extra_body`")
520
+
521
+ headers = self._build_headers(options, retries_taken=retries_taken)
522
+ params = _merge_mappings(self.default_query, options.params)
523
+ content_type = headers.get("Content-Type")
524
+ files = options.files
525
+
526
+ # If the given Content-Type header is multipart/form-data then it
527
+ # has to be removed so that httpx can generate the header with
528
+ # additional information for us as it has to be in this form
529
+ # for the server to be able to correctly parse the request:
530
+ # multipart/form-data; boundary=---abc--
531
+ if content_type is not None and content_type.startswith("multipart/form-data"):
532
+ if "boundary" not in content_type:
533
+ # only remove the header if the boundary hasn't been explicitly set
534
+ # as the caller doesn't want httpx to come up with their own boundary
535
+ headers.pop("Content-Type")
536
+
537
+ # As we are now sending multipart/form-data instead of application/json
538
+ # we need to tell httpx to use it, https://www.python-httpx.org/advanced/clients/#multipart-file-encoding
539
+ if json_data:
540
+ if not is_dict(json_data):
541
+ raise TypeError(
542
+ f"Expected query input to be a dictionary for multipart requests but got {type(json_data)} instead."
543
+ )
544
+ kwargs["data"] = self._serialize_multipartform(json_data)
545
+
546
+ # httpx determines whether or not to send a "multipart/form-data"
547
+ # request based on the truthiness of the "files" argument.
548
+ # This gets around that issue by generating a dict value that
549
+ # evaluates to true.
550
+ #
551
+ # https://github.com/encode/httpx/discussions/2399#discussioncomment-3814186
552
+ if not files:
553
+ files = cast(HttpxRequestFiles, ForceMultipartDict())
554
+
555
+ prepared_url = self._prepare_url(options.url)
556
+ # preserve hard-coded query params from the url
557
+ if params and prepared_url.query:
558
+ params = {**dict(prepared_url.params.items()), **params}
559
+ prepared_url = prepared_url.copy_with(raw_path=prepared_url.raw_path.split(b"?", 1)[0])
560
+ if "_" in prepared_url.host:
561
+ # work around https://github.com/encode/httpx/discussions/2880
562
+ kwargs["extensions"] = {"sni_hostname": prepared_url.host.replace("_", "-")}
563
+
564
+ is_body_allowed = options.method.lower() != "get"
565
+
566
+ if is_body_allowed:
567
+ if options.content is not None and json_data is not None:
568
+ raise TypeError("Passing both `content` and `json_data` is not supported")
569
+ if options.content is not None and files is not None:
570
+ raise TypeError("Passing both `content` and `files` is not supported")
571
+ if options.content is not None:
572
+ kwargs["content"] = options.content
573
+ elif isinstance(json_data, bytes):
574
+ kwargs["content"] = json_data
575
+ elif not files:
576
+ # Don't set content when JSON is sent as multipart/form-data,
577
+ # since httpx's content param overrides other body arguments
578
+ kwargs["content"] = openapi_dumps(json_data) if is_given(json_data) and json_data is not None else None
579
+ kwargs["files"] = files
580
+ else:
581
+ headers.pop("Content-Type", None)
582
+ kwargs.pop("data", None)
583
+
584
+ # TODO: report this error to httpx
585
+ return self._client.build_request( # pyright: ignore[reportUnknownMemberType]
586
+ headers=headers,
587
+ timeout=self.timeout if isinstance(options.timeout, NotGiven) else options.timeout,
588
+ method=options.method,
589
+ url=prepared_url,
590
+ # the `Query` type that we use is incompatible with qs'
591
+ # `Params` type as it needs to be typed as `Mapping[str, object]`
592
+ # so that passing a `TypedDict` doesn't cause an error.
593
+ # https://github.com/microsoft/pyright/issues/3526#event-6715453066
594
+ params=self.qs.stringify(cast(Mapping[str, Any], params)) if params else None,
595
+ **kwargs,
596
+ )
597
+
598
+ def _serialize_multipartform(self, data: Mapping[object, object]) -> dict[str, object]:
599
+ items = self.qs.stringify_items(
600
+ # TODO: type ignore is required as stringify_items is well typed but we can't be
601
+ # well typed without heavy validation.
602
+ data, # type: ignore
603
+ array_format="brackets",
604
+ )
605
+ serialized: dict[str, object] = {}
606
+ for key, value in items:
607
+ existing = serialized.get(key)
608
+
609
+ if not existing:
610
+ serialized[key] = value
611
+ continue
612
+
613
+ # If a value has already been set for this key then that
614
+ # means we're sending data like `array[]=[1, 2, 3]` and we
615
+ # need to tell httpx that we want to send multiple values with
616
+ # the same key which is done by using a list or a tuple.
617
+ #
618
+ # Note: 2d arrays should never result in the same key at both
619
+ # levels so it's safe to assume that if the value is a list,
620
+ # it was because we changed it to be a list.
621
+ if is_list(existing):
622
+ existing.append(value)
623
+ else:
624
+ serialized[key] = [existing, value]
625
+
626
+ return serialized
627
+
628
+ def _maybe_override_cast_to(self, cast_to: type[ResponseT], options: FinalRequestOptions) -> type[ResponseT]:
629
+ if not is_given(options.headers):
630
+ return cast_to
631
+
632
+ # make a copy of the headers so we don't mutate user-input
633
+ headers = dict(options.headers)
634
+
635
+ # we internally support defining a temporary header to override the
636
+ # default `cast_to` type for use with `.with_raw_response` and `.with_streaming_response`
637
+ # see _response.py for implementation details
638
+ override_cast_to = headers.pop(OVERRIDE_CAST_TO_HEADER, not_given)
639
+ if is_given(override_cast_to):
640
+ options.headers = headers
641
+ return cast(Type[ResponseT], override_cast_to)
642
+
643
+ return cast_to
644
+
645
+ def _should_stream_response_body(self, request: httpx.Request) -> bool:
646
+ return request.headers.get(RAW_RESPONSE_HEADER) == "stream" # type: ignore[no-any-return]
647
+
648
+ def _process_response_data(
649
+ self,
650
+ *,
651
+ data: object,
652
+ cast_to: type[ResponseT],
653
+ response: httpx.Response,
654
+ ) -> ResponseT:
655
+ if data is None:
656
+ return cast(ResponseT, None)
657
+
658
+ if cast_to is object:
659
+ return cast(ResponseT, data)
660
+
661
+ try:
662
+ if inspect.isclass(cast_to) and issubclass(cast_to, ModelBuilderProtocol):
663
+ return cast(ResponseT, cast_to.build(response=response, data=data))
664
+
665
+ if self._strict_response_validation:
666
+ return cast(ResponseT, validate_type(type_=cast_to, value=data))
667
+
668
+ return cast(ResponseT, construct_type(type_=cast_to, value=data))
669
+ except pydantic.ValidationError as err:
670
+ raise APIResponseValidationError(response=response, body=data) from err
671
+
672
+ @property
673
+ def qs(self) -> Querystring:
674
+ return Querystring()
675
+
676
+ @property
677
+ def custom_auth(self) -> httpx.Auth | None:
678
+ return None
679
+
680
+ @property
681
+ def auth_headers(self) -> dict[str, str]:
682
+ return {}
683
+
684
+ @property
685
+ def default_headers(self) -> dict[str, str | Omit]:
686
+ return {
687
+ "Accept": "application/json",
688
+ "Content-Type": "application/json",
689
+ "User-Agent": self.user_agent,
690
+ **self.platform_headers(),
691
+ **self.auth_headers,
692
+ **self._custom_headers,
693
+ }
694
+
695
+ @property
696
+ def default_query(self) -> dict[str, object]:
697
+ return {
698
+ **self._custom_query,
699
+ }
700
+
701
+ def _validate_headers(
702
+ self,
703
+ headers: Headers, # noqa: ARG002
704
+ custom_headers: Headers, # noqa: ARG002
705
+ ) -> None:
706
+ """Validate the given default headers and custom headers.
707
+
708
+ Does nothing by default.
709
+ """
710
+ return
711
+
712
+ @property
713
+ def user_agent(self) -> str:
714
+ return f"{self.__class__.__name__}/Python {self._version}"
715
+
716
+ @property
717
+ def base_url(self) -> URL:
718
+ return self._base_url
719
+
720
+ @base_url.setter
721
+ def base_url(self, url: URL | str) -> None:
722
+ self._base_url = self._enforce_trailing_slash(url if isinstance(url, URL) else URL(url))
723
+
724
+ def platform_headers(self) -> Dict[str, str]:
725
+ # the actual implementation is in a separate `lru_cache` decorated
726
+ # function because adding `lru_cache` to methods will leak memory
727
+ # https://github.com/python/cpython/issues/88476
728
+ return platform_headers(self._version, platform=self._platform)
729
+
730
+ def _calculate_nonstreaming_timeout(self, max_tokens: int, max_nonstreaming_tokens: int | None) -> Timeout:
731
+ maximum_time = 60 * 60
732
+ default_time = 60 * 10
733
+
734
+ expected_time = maximum_time * max_tokens / 128_000
735
+ if expected_time > default_time or (max_nonstreaming_tokens and max_tokens > max_nonstreaming_tokens):
736
+ raise ValueError(
737
+ "Streaming is required for operations that may take longer than 10 minutes. "
738
+ + "See https://github.com/anthropics/anthropic-sdk-python#long-requests for more details",
739
+ )
740
+ return Timeout(
741
+ default_time,
742
+ connect=5.0,
743
+ )
744
+
745
+ def _parse_retry_after_header(self, response_headers: Optional[httpx.Headers] = None) -> float | None:
746
+ """Returns a float of the number of seconds (not milliseconds) to wait after retrying, or None if unspecified.
747
+
748
+ About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
749
+ See also https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#syntax
750
+ """
751
+ if response_headers is None:
752
+ return None
753
+
754
+ # First, try the non-standard `retry-after-ms` header for milliseconds,
755
+ # which is more precise than integer-seconds `retry-after`
756
+ try:
757
+ retry_ms_header = response_headers.get("retry-after-ms", None)
758
+ return float(retry_ms_header) / 1000
759
+ except (TypeError, ValueError):
760
+ pass
761
+
762
+ # Next, try parsing `retry-after` header as seconds (allowing nonstandard floats).
763
+ retry_header = response_headers.get("retry-after")
764
+ try:
765
+ # note: the spec indicates that this should only ever be an integer
766
+ # but if someone sends a float there's no reason for us to not respect it
767
+ return float(retry_header)
768
+ except (TypeError, ValueError):
769
+ pass
770
+
771
+ # Last, try parsing `retry-after` as a date.
772
+ retry_date_tuple = email.utils.parsedate_tz(retry_header)
773
+ if retry_date_tuple is None:
774
+ return None
775
+
776
+ retry_date = email.utils.mktime_tz(retry_date_tuple)
777
+ return float(retry_date - time.time())
778
+
779
+ def _calculate_retry_timeout(
780
+ self,
781
+ remaining_retries: int,
782
+ options: FinalRequestOptions,
783
+ response_headers: Optional[httpx.Headers] = None,
784
+ ) -> float:
785
+ max_retries = options.get_max_retries(self.max_retries)
786
+
787
+ # If the API asks us to wait a certain amount of time (and it's a reasonable amount), just do what it says.
788
+ retry_after = self._parse_retry_after_header(response_headers)
789
+ if retry_after is not None and 0 < retry_after <= 60:
790
+ return retry_after
791
+
792
+ # Also cap retry count to 1000 to avoid any potential overflows with `pow`
793
+ nb_retries = min(max_retries - remaining_retries, 1000)
794
+
795
+ # Apply exponential backoff, but not more than the max.
796
+ sleep_seconds = min(INITIAL_RETRY_DELAY * pow(2.0, nb_retries), MAX_RETRY_DELAY)
797
+
798
+ # Apply some jitter, plus-or-minus half a second.
799
+ jitter = 1 - 0.25 * random()
800
+ timeout = sleep_seconds * jitter
801
+ return timeout if timeout >= 0 else 0
802
+
803
+ def _should_retry(self, response: httpx.Response) -> bool:
804
+ # Note: this is not a standard header
805
+ should_retry_header = response.headers.get("x-should-retry")
806
+
807
+ # If the server explicitly says whether or not to retry, obey.
808
+ if should_retry_header == "true":
809
+ log.debug("Retrying as header `x-should-retry` is set to `true`")
810
+ return True
811
+ if should_retry_header == "false":
812
+ log.debug("Not retrying as header `x-should-retry` is set to `false`")
813
+ return False
814
+
815
+ # Retry on request timeouts.
816
+ if response.status_code == 408:
817
+ log.debug("Retrying due to status code %i", response.status_code)
818
+ return True
819
+
820
+ # Retry on lock timeouts.
821
+ if response.status_code == 409:
822
+ log.debug("Retrying due to status code %i", response.status_code)
823
+ return True
824
+
825
+ # Retry on rate limits.
826
+ if response.status_code == 429:
827
+ log.debug("Retrying due to status code %i", response.status_code)
828
+ return True
829
+
830
+ # Retry internal errors.
831
+ if response.status_code >= 500:
832
+ log.debug("Retrying due to status code %i", response.status_code)
833
+ return True
834
+
835
+ log.debug("Not retrying")
836
+ return False
837
+
838
+ def _idempotency_key(self) -> str:
839
+ return f"stainless-python-retry-{uuid.uuid4()}"
840
+
841
+
842
+ class _DefaultHttpxClient(httpx.Client):
843
+ def __init__(self, **kwargs: Any) -> None:
844
+ kwargs.setdefault("timeout", DEFAULT_TIMEOUT)
845
+ kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS)
846
+ kwargs.setdefault("follow_redirects", True)
847
+
848
+ if "transport" not in kwargs:
849
+ socket_options: List[Tuple[int, int, Union[int, bool]]] = [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, True)]
850
+
851
+ TCP_KEEPINTVL = getattr(socket, "TCP_KEEPINTVL", None)
852
+
853
+ if TCP_KEEPINTVL is not None:
854
+ socket_options.append((socket.IPPROTO_TCP, TCP_KEEPINTVL, 60))
855
+ elif sys.platform == "darwin":
856
+ TCP_KEEPALIVE = getattr(socket, "TCP_KEEPALIVE", 0x10)
857
+ socket_options.append((socket.IPPROTO_TCP, TCP_KEEPALIVE, 60))
858
+
859
+ TCP_KEEPCNT = getattr(socket, "TCP_KEEPCNT", None)
860
+ if TCP_KEEPCNT is not None:
861
+ socket_options.append((socket.IPPROTO_TCP, TCP_KEEPCNT, 5))
862
+
863
+ TCP_KEEPIDLE = getattr(socket, "TCP_KEEPIDLE", None)
864
+ if TCP_KEEPIDLE is not None:
865
+ socket_options.append((socket.IPPROTO_TCP, TCP_KEEPIDLE, 60))
866
+
867
+ proxy_map = {key: None if url is None else Proxy(url=url) for key, url in get_environment_proxies().items()}
868
+
869
+ transport_kwargs = {
870
+ arg: kwargs[arg] for arg in ("verify", "cert", "trust_env", "http1", "http2", "limits") if arg in kwargs
871
+ }
872
+
873
+ transport_kwargs["socket_options"] = socket_options
874
+
875
+ proxy_mounts = {
876
+ key: None if proxy is None else HTTPTransport(proxy=proxy, **transport_kwargs)
877
+ for key, proxy in proxy_map.items()
878
+ }
879
+ default_transport = HTTPTransport(**transport_kwargs)
880
+
881
+ # Prioritize the mounts set by the user over the environment variables.
882
+ proxy_mounts.update(kwargs.get("mounts", {}))
883
+ kwargs["mounts"] = proxy_mounts
884
+
885
+ # Sets the default transport so that HTTPX won't automatically configure proxies.
886
+ kwargs["transport"] = default_transport
887
+
888
+ super().__init__(**kwargs)
889
+
890
+
891
+ if TYPE_CHECKING:
892
+ DefaultHttpxClient = httpx.Client
893
+ """An alias to `httpx.Client` that provides the same defaults that this SDK
894
+ uses internally.
895
+
896
+ This is useful because overriding the `http_client` with your own instance of
897
+ `httpx.Client` will result in httpx's defaults being used, not ours.
898
+ """
899
+ else:
900
+ DefaultHttpxClient = _DefaultHttpxClient
901
+
902
+
903
+ class SyncHttpxClientWrapper(DefaultHttpxClient):
904
+ def __del__(self) -> None:
905
+ if self.is_closed:
906
+ return
907
+
908
+ try:
909
+ self.close()
910
+ except Exception:
911
+ pass
912
+
913
+
914
+ class SyncAPIClient(BaseClient[httpx.Client, Stream[Any]]):
915
+ _client: httpx.Client
916
+ _default_stream_cls: type[Stream[Any]] | None = None
917
+
918
+ def __init__(
919
+ self,
920
+ *,
921
+ version: str,
922
+ base_url: str | URL,
923
+ max_retries: int = DEFAULT_MAX_RETRIES,
924
+ timeout: float | Timeout | None | NotGiven = not_given,
925
+ http_client: httpx.Client | None = None,
926
+ custom_headers: Mapping[str, str] | None = None,
927
+ custom_query: Mapping[str, object] | None = None,
928
+ _strict_response_validation: bool,
929
+ ) -> None:
930
+ if not is_given(timeout):
931
+ # if the user passed in a custom http client with a non-default
932
+ # timeout set then we use that timeout.
933
+ #
934
+ # note: there is an edge case here where the user passes in a client
935
+ # where they've explicitly set the timeout to match the default timeout
936
+ # as this check is structural, meaning that we'll think they didn't
937
+ # pass in a timeout and will ignore it
938
+ if http_client and http_client.timeout != HTTPX_DEFAULT_TIMEOUT:
939
+ timeout = http_client.timeout
940
+ else:
941
+ timeout = DEFAULT_TIMEOUT
942
+
943
+ if http_client is not None and not isinstance(http_client, httpx.Client): # pyright: ignore[reportUnnecessaryIsInstance]
944
+ raise TypeError(
945
+ f"Invalid `http_client` argument; Expected an instance of `httpx.Client` but got {type(http_client)}"
946
+ )
947
+
948
+ super().__init__(
949
+ version=version,
950
+ # cast to a valid type because mypy doesn't understand our type narrowing
951
+ timeout=cast(Timeout, timeout),
952
+ base_url=base_url,
953
+ max_retries=max_retries,
954
+ custom_query=custom_query,
955
+ custom_headers=custom_headers,
956
+ _strict_response_validation=_strict_response_validation,
957
+ )
958
+ self._client = http_client or SyncHttpxClientWrapper(
959
+ base_url=base_url,
960
+ # cast to a valid type because mypy doesn't understand our type narrowing
961
+ timeout=cast(Timeout, timeout),
962
+ )
963
+
964
+ def is_closed(self) -> bool:
965
+ return self._client.is_closed
966
+
967
+ def close(self) -> None:
968
+ """Close the underlying HTTPX client.
969
+
970
+ The client will *not* be usable after this.
971
+ """
972
+ # If an error is thrown while constructing a client, self._client
973
+ # may not be present
974
+ if hasattr(self, "_client"):
975
+ self._client.close()
976
+
977
+ def __enter__(self: _T) -> _T:
978
+ return self
979
+
980
+ def __exit__(
981
+ self,
982
+ exc_type: type[BaseException] | None,
983
+ exc: BaseException | None,
984
+ exc_tb: TracebackType | None,
985
+ ) -> None:
986
+ self.close()
987
+
988
+ def _prepare_options(
989
+ self,
990
+ options: FinalRequestOptions, # noqa: ARG002
991
+ ) -> FinalRequestOptions:
992
+ """Hook for mutating the given options"""
993
+ return options
994
+
995
+ def _prepare_request(
996
+ self,
997
+ request: httpx.Request, # noqa: ARG002
998
+ ) -> None:
999
+ """This method is used as a callback for mutating the `Request` object
1000
+ after it has been constructed.
1001
+ This is useful for cases where you want to add certain headers based off of
1002
+ the request properties, e.g. `url`, `method` etc.
1003
+ """
1004
+ return None
1005
+
1006
+ @overload
1007
+ def request(
1008
+ self,
1009
+ cast_to: Type[ResponseT],
1010
+ options: FinalRequestOptions,
1011
+ *,
1012
+ stream: Literal[True],
1013
+ stream_cls: Type[_StreamT],
1014
+ ) -> _StreamT: ...
1015
+
1016
+ @overload
1017
+ def request(
1018
+ self,
1019
+ cast_to: Type[ResponseT],
1020
+ options: FinalRequestOptions,
1021
+ *,
1022
+ stream: Literal[False] = False,
1023
+ ) -> ResponseT: ...
1024
+
1025
+ @overload
1026
+ def request(
1027
+ self,
1028
+ cast_to: Type[ResponseT],
1029
+ options: FinalRequestOptions,
1030
+ *,
1031
+ stream: bool = False,
1032
+ stream_cls: Type[_StreamT] | None = None,
1033
+ ) -> ResponseT | _StreamT: ...
1034
+
1035
+ def request(
1036
+ self,
1037
+ cast_to: Type[ResponseT],
1038
+ options: FinalRequestOptions,
1039
+ *,
1040
+ stream: bool = False,
1041
+ stream_cls: type[_StreamT] | None = None,
1042
+ ) -> ResponseT | _StreamT:
1043
+ cast_to = self._maybe_override_cast_to(cast_to, options)
1044
+
1045
+ # create a copy of the options we were given so that if the
1046
+ # options are mutated later & we then retry, the retries are
1047
+ # given the original options
1048
+ input_options = model_copy(options)
1049
+ if input_options.idempotency_key is None and input_options.method.lower() != "get":
1050
+ # ensure the idempotency key is reused between requests
1051
+ input_options.idempotency_key = self._idempotency_key()
1052
+
1053
+ response: httpx.Response | None = None
1054
+ max_retries = input_options.get_max_retries(self.max_retries)
1055
+
1056
+ retries_taken = 0
1057
+ for retries_taken in range(max_retries + 1):
1058
+ options = model_copy(input_options)
1059
+ options = self._prepare_options(options)
1060
+
1061
+ remaining_retries = max_retries - retries_taken
1062
+ request = self._build_request(options, retries_taken=retries_taken)
1063
+ self._prepare_request(request)
1064
+
1065
+ kwargs: HttpxSendArgs = {}
1066
+ if self.custom_auth is not None:
1067
+ kwargs["auth"] = self.custom_auth
1068
+
1069
+ if options.follow_redirects is not None:
1070
+ kwargs["follow_redirects"] = options.follow_redirects
1071
+
1072
+ log.debug("Sending HTTP Request: %s %s", request.method, request.url)
1073
+
1074
+ response = None
1075
+ try:
1076
+ response = self._client.send(
1077
+ request,
1078
+ stream=stream or self._should_stream_response_body(request=request),
1079
+ **kwargs,
1080
+ )
1081
+ except httpx.TimeoutException as err:
1082
+ log.debug("Encountered httpx.TimeoutException", exc_info=True)
1083
+
1084
+ if remaining_retries > 0:
1085
+ self._sleep_for_retry(
1086
+ retries_taken=retries_taken,
1087
+ max_retries=max_retries,
1088
+ options=input_options,
1089
+ response=None,
1090
+ )
1091
+ continue
1092
+
1093
+ log.debug("Raising timeout error")
1094
+ raise APITimeoutError(request=request) from err
1095
+ except Exception as err:
1096
+ log.debug("Encountered Exception", exc_info=True)
1097
+
1098
+ if remaining_retries > 0:
1099
+ self._sleep_for_retry(
1100
+ retries_taken=retries_taken,
1101
+ max_retries=max_retries,
1102
+ options=input_options,
1103
+ response=None,
1104
+ )
1105
+ continue
1106
+
1107
+ log.debug("Raising connection error")
1108
+ raise APIConnectionError(request=request) from err
1109
+
1110
+ log.debug(
1111
+ 'HTTP Response: %s %s "%i %s" %s',
1112
+ request.method,
1113
+ request.url,
1114
+ response.status_code,
1115
+ response.reason_phrase,
1116
+ response.headers,
1117
+ )
1118
+ log.debug("request_id: %s", response.headers.get("request-id"))
1119
+
1120
+ try:
1121
+ response.raise_for_status()
1122
+ except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code
1123
+ log.debug("Encountered httpx.HTTPStatusError", exc_info=True)
1124
+
1125
+ if remaining_retries > 0 and self._should_retry(err.response):
1126
+ err.response.close()
1127
+ self._sleep_for_retry(
1128
+ retries_taken=retries_taken,
1129
+ max_retries=max_retries,
1130
+ options=input_options,
1131
+ response=response,
1132
+ )
1133
+ continue
1134
+
1135
+ # If the response is streamed then we need to explicitly read the response
1136
+ # to completion before attempting to access the response text.
1137
+ if not err.response.is_closed:
1138
+ err.response.read()
1139
+
1140
+ log.debug("Re-raising status error")
1141
+ raise self._make_status_error_from_response(err.response) from None
1142
+
1143
+ break
1144
+
1145
+ assert response is not None, "could not resolve response (should never happen)"
1146
+ return self._process_response(
1147
+ cast_to=cast_to,
1148
+ options=options,
1149
+ response=response,
1150
+ stream=stream,
1151
+ stream_cls=stream_cls,
1152
+ retries_taken=retries_taken,
1153
+ )
1154
+
1155
+ def _sleep_for_retry(
1156
+ self, *, retries_taken: int, max_retries: int, options: FinalRequestOptions, response: httpx.Response | None
1157
+ ) -> None:
1158
+ remaining_retries = max_retries - retries_taken
1159
+ if remaining_retries == 1:
1160
+ log.debug("1 retry left")
1161
+ else:
1162
+ log.debug("%i retries left", remaining_retries)
1163
+
1164
+ timeout = self._calculate_retry_timeout(remaining_retries, options, response.headers if response else None)
1165
+ log.info("Retrying request to %s in %f seconds", options.url, timeout)
1166
+
1167
+ time.sleep(timeout)
1168
+
1169
+ def _process_response(
1170
+ self,
1171
+ *,
1172
+ cast_to: Type[ResponseT],
1173
+ options: FinalRequestOptions,
1174
+ response: httpx.Response,
1175
+ stream: bool,
1176
+ stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None,
1177
+ retries_taken: int = 0,
1178
+ ) -> ResponseT:
1179
+ if response.request.headers.get(RAW_RESPONSE_HEADER) == "true":
1180
+ return cast(
1181
+ ResponseT,
1182
+ LegacyAPIResponse(
1183
+ raw=response,
1184
+ client=self,
1185
+ cast_to=cast_to,
1186
+ stream=stream,
1187
+ stream_cls=stream_cls,
1188
+ options=options,
1189
+ retries_taken=retries_taken,
1190
+ ),
1191
+ )
1192
+
1193
+ origin = get_origin(cast_to) or cast_to
1194
+
1195
+ if (
1196
+ inspect.isclass(origin)
1197
+ and issubclass(origin, BaseAPIResponse)
1198
+ # we only want to actually return the custom BaseAPIResponse class if we're
1199
+ # returning the raw response, or if we're not streaming SSE, as if we're streaming
1200
+ # SSE then `cast_to` doesn't actively reflect the type we need to parse into
1201
+ and (not stream or bool(response.request.headers.get(RAW_RESPONSE_HEADER)))
1202
+ ):
1203
+ if not issubclass(origin, APIResponse):
1204
+ raise TypeError(f"API Response types must subclass {APIResponse}; Received {origin}")
1205
+
1206
+ response_cls = cast("type[BaseAPIResponse[Any]]", cast_to)
1207
+ return cast(
1208
+ ResponseT,
1209
+ response_cls(
1210
+ raw=response,
1211
+ client=self,
1212
+ cast_to=extract_response_type(response_cls),
1213
+ stream=stream,
1214
+ stream_cls=stream_cls,
1215
+ options=options,
1216
+ retries_taken=retries_taken,
1217
+ ),
1218
+ )
1219
+
1220
+ if cast_to == httpx.Response:
1221
+ return cast(ResponseT, response)
1222
+
1223
+ api_response = APIResponse(
1224
+ raw=response,
1225
+ client=self,
1226
+ cast_to=cast("type[ResponseT]", cast_to), # pyright: ignore[reportUnnecessaryCast]
1227
+ stream=stream,
1228
+ stream_cls=stream_cls,
1229
+ options=options,
1230
+ retries_taken=retries_taken,
1231
+ )
1232
+ if bool(response.request.headers.get(RAW_RESPONSE_HEADER)):
1233
+ return cast(ResponseT, api_response)
1234
+
1235
+ return api_response.parse()
1236
+
1237
+ def _request_api_list(
1238
+ self,
1239
+ model: Type[object],
1240
+ page: Type[SyncPageT],
1241
+ options: FinalRequestOptions,
1242
+ ) -> SyncPageT:
1243
+ def _parser(resp: SyncPageT) -> SyncPageT:
1244
+ resp._set_private_attributes(
1245
+ client=self,
1246
+ model=model,
1247
+ options=options,
1248
+ )
1249
+ return resp
1250
+
1251
+ options.post_parser = _parser
1252
+
1253
+ return self.request(page, options, stream=False)
1254
+
1255
+ @overload
1256
+ def get(
1257
+ self,
1258
+ path: str,
1259
+ *,
1260
+ cast_to: Type[ResponseT],
1261
+ options: RequestOptions = {},
1262
+ stream: Literal[False] = False,
1263
+ ) -> ResponseT: ...
1264
+
1265
+ @overload
1266
+ def get(
1267
+ self,
1268
+ path: str,
1269
+ *,
1270
+ cast_to: Type[ResponseT],
1271
+ options: RequestOptions = {},
1272
+ stream: Literal[True],
1273
+ stream_cls: type[_StreamT],
1274
+ ) -> _StreamT: ...
1275
+
1276
+ @overload
1277
+ def get(
1278
+ self,
1279
+ path: str,
1280
+ *,
1281
+ cast_to: Type[ResponseT],
1282
+ options: RequestOptions = {},
1283
+ stream: bool,
1284
+ stream_cls: type[_StreamT] | None = None,
1285
+ ) -> ResponseT | _StreamT: ...
1286
+
1287
+ def get(
1288
+ self,
1289
+ path: str,
1290
+ *,
1291
+ cast_to: Type[ResponseT],
1292
+ options: RequestOptions = {},
1293
+ stream: bool = False,
1294
+ stream_cls: type[_StreamT] | None = None,
1295
+ ) -> ResponseT | _StreamT:
1296
+ opts = FinalRequestOptions.construct(method="get", url=path, **options)
1297
+ # cast is required because mypy complains about returning Any even though
1298
+ # it understands the type variables
1299
+ return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls))
1300
+
1301
+ @overload
1302
+ def post(
1303
+ self,
1304
+ path: str,
1305
+ *,
1306
+ cast_to: Type[ResponseT],
1307
+ body: Body | None = None,
1308
+ content: BinaryTypes | None = None,
1309
+ options: RequestOptions = {},
1310
+ files: RequestFiles | None = None,
1311
+ stream: Literal[False] = False,
1312
+ ) -> ResponseT: ...
1313
+
1314
+ @overload
1315
+ def post(
1316
+ self,
1317
+ path: str,
1318
+ *,
1319
+ cast_to: Type[ResponseT],
1320
+ body: Body | None = None,
1321
+ content: BinaryTypes | None = None,
1322
+ options: RequestOptions = {},
1323
+ files: RequestFiles | None = None,
1324
+ stream: Literal[True],
1325
+ stream_cls: type[_StreamT],
1326
+ ) -> _StreamT: ...
1327
+
1328
+ @overload
1329
+ def post(
1330
+ self,
1331
+ path: str,
1332
+ *,
1333
+ cast_to: Type[ResponseT],
1334
+ body: Body | None = None,
1335
+ content: BinaryTypes | None = None,
1336
+ options: RequestOptions = {},
1337
+ files: RequestFiles | None = None,
1338
+ stream: bool,
1339
+ stream_cls: type[_StreamT] | None = None,
1340
+ ) -> ResponseT | _StreamT: ...
1341
+
1342
+ def post(
1343
+ self,
1344
+ path: str,
1345
+ *,
1346
+ cast_to: Type[ResponseT],
1347
+ body: Body | None = None,
1348
+ content: BinaryTypes | None = None,
1349
+ options: RequestOptions = {},
1350
+ files: RequestFiles | None = None,
1351
+ stream: bool = False,
1352
+ stream_cls: type[_StreamT] | None = None,
1353
+ ) -> ResponseT | _StreamT:
1354
+ if body is not None and content is not None:
1355
+ raise TypeError("Passing both `body` and `content` is not supported")
1356
+ if files is not None and content is not None:
1357
+ raise TypeError("Passing both `files` and `content` is not supported")
1358
+ if isinstance(body, bytes):
1359
+ warnings.warn(
1360
+ "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
1361
+ "Please pass raw bytes via the `content` parameter instead.",
1362
+ DeprecationWarning,
1363
+ stacklevel=2,
1364
+ )
1365
+ opts = FinalRequestOptions.construct(
1366
+ method="post", url=path, json_data=body, content=content, files=to_httpx_files(files), **options
1367
+ )
1368
+ return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls))
1369
+
1370
+ def patch(
1371
+ self,
1372
+ path: str,
1373
+ *,
1374
+ cast_to: Type[ResponseT],
1375
+ body: Body | None = None,
1376
+ content: BinaryTypes | None = None,
1377
+ files: RequestFiles | None = None,
1378
+ options: RequestOptions = {},
1379
+ ) -> ResponseT:
1380
+ if body is not None and content is not None:
1381
+ raise TypeError("Passing both `body` and `content` is not supported")
1382
+ if files is not None and content is not None:
1383
+ raise TypeError("Passing both `files` and `content` is not supported")
1384
+ if isinstance(body, bytes):
1385
+ warnings.warn(
1386
+ "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
1387
+ "Please pass raw bytes via the `content` parameter instead.",
1388
+ DeprecationWarning,
1389
+ stacklevel=2,
1390
+ )
1391
+ opts = FinalRequestOptions.construct(
1392
+ method="patch", url=path, json_data=body, content=content, files=to_httpx_files(files), **options
1393
+ )
1394
+ return self.request(cast_to, opts)
1395
+
1396
+ def put(
1397
+ self,
1398
+ path: str,
1399
+ *,
1400
+ cast_to: Type[ResponseT],
1401
+ body: Body | None = None,
1402
+ content: BinaryTypes | None = None,
1403
+ files: RequestFiles | None = None,
1404
+ options: RequestOptions = {},
1405
+ ) -> ResponseT:
1406
+ if body is not None and content is not None:
1407
+ raise TypeError("Passing both `body` and `content` is not supported")
1408
+ if files is not None and content is not None:
1409
+ raise TypeError("Passing both `files` and `content` is not supported")
1410
+ if isinstance(body, bytes):
1411
+ warnings.warn(
1412
+ "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
1413
+ "Please pass raw bytes via the `content` parameter instead.",
1414
+ DeprecationWarning,
1415
+ stacklevel=2,
1416
+ )
1417
+ opts = FinalRequestOptions.construct(
1418
+ method="put", url=path, json_data=body, content=content, files=to_httpx_files(files), **options
1419
+ )
1420
+ return self.request(cast_to, opts)
1421
+
1422
+ def delete(
1423
+ self,
1424
+ path: str,
1425
+ *,
1426
+ cast_to: Type[ResponseT],
1427
+ body: Body | None = None,
1428
+ content: BinaryTypes | None = None,
1429
+ options: RequestOptions = {},
1430
+ ) -> ResponseT:
1431
+ if body is not None and content is not None:
1432
+ raise TypeError("Passing both `body` and `content` is not supported")
1433
+ if isinstance(body, bytes):
1434
+ warnings.warn(
1435
+ "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
1436
+ "Please pass raw bytes via the `content` parameter instead.",
1437
+ DeprecationWarning,
1438
+ stacklevel=2,
1439
+ )
1440
+ opts = FinalRequestOptions.construct(method="delete", url=path, json_data=body, content=content, **options)
1441
+ return self.request(cast_to, opts)
1442
+
1443
+ def get_api_list(
1444
+ self,
1445
+ path: str,
1446
+ *,
1447
+ model: Type[object],
1448
+ page: Type[SyncPageT],
1449
+ body: Body | None = None,
1450
+ options: RequestOptions = {},
1451
+ method: str = "get",
1452
+ ) -> SyncPageT:
1453
+ opts = FinalRequestOptions.construct(method=method, url=path, json_data=body, **options)
1454
+ return self._request_api_list(model, page, opts)
1455
+
1456
+
1457
+ class _DefaultAsyncHttpxClient(httpx.AsyncClient):
1458
+ def __init__(self, **kwargs: Any) -> None:
1459
+ kwargs.setdefault("timeout", DEFAULT_TIMEOUT)
1460
+ kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS)
1461
+ kwargs.setdefault("follow_redirects", True)
1462
+
1463
+ if "transport" not in kwargs:
1464
+ socket_options: List[Tuple[int, int, Union[int, bool]]] = [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, True)]
1465
+
1466
+ TCP_KEEPINTVL = getattr(socket, "TCP_KEEPINTVL", None)
1467
+
1468
+ if TCP_KEEPINTVL is not None:
1469
+ socket_options.append((socket.IPPROTO_TCP, TCP_KEEPINTVL, 60))
1470
+ elif sys.platform == "darwin":
1471
+ TCP_KEEPALIVE = getattr(socket, "TCP_KEEPALIVE", 0x10)
1472
+ socket_options.append((socket.IPPROTO_TCP, TCP_KEEPALIVE, 60))
1473
+
1474
+ TCP_KEEPCNT = getattr(socket, "TCP_KEEPCNT", None)
1475
+ if TCP_KEEPCNT is not None:
1476
+ socket_options.append((socket.IPPROTO_TCP, TCP_KEEPCNT, 5))
1477
+
1478
+ TCP_KEEPIDLE = getattr(socket, "TCP_KEEPIDLE", None)
1479
+ if TCP_KEEPIDLE is not None:
1480
+ socket_options.append((socket.IPPROTO_TCP, TCP_KEEPIDLE, 60))
1481
+
1482
+ proxy_map = {key: None if url is None else Proxy(url=url) for key, url in get_environment_proxies().items()}
1483
+
1484
+ transport_kwargs = {
1485
+ arg: kwargs[arg] for arg in ("verify", "cert", "trust_env", "http1", "http2", "limits") if arg in kwargs
1486
+ }
1487
+
1488
+ transport_kwargs["socket_options"] = socket_options
1489
+
1490
+ proxy_mounts = {
1491
+ key: None if proxy is None else AsyncHTTPTransport(proxy=proxy, **transport_kwargs)
1492
+ for key, proxy in proxy_map.items()
1493
+ }
1494
+ default_transport = AsyncHTTPTransport(**transport_kwargs)
1495
+
1496
+ # Prioritize the mounts set by the user over the environment variables.
1497
+ proxy_mounts.update(kwargs.get("mounts", {}))
1498
+ kwargs["mounts"] = proxy_mounts
1499
+
1500
+ # Sets the default transport so that HTTPX won't automatically configure proxies.
1501
+ kwargs["transport"] = default_transport
1502
+
1503
+ super().__init__(**kwargs)
1504
+
1505
+
1506
+ try:
1507
+ import httpx_aiohttp
1508
+ except ImportError:
1509
+
1510
+ class _DefaultAioHttpClient(httpx.AsyncClient):
1511
+ def __init__(self, **_kwargs: Any) -> None:
1512
+ raise RuntimeError("To use the aiohttp client you must have installed the package with the `aiohttp` extra")
1513
+ else:
1514
+
1515
+ class _DefaultAioHttpClient(httpx_aiohttp.HttpxAiohttpClient): # type: ignore
1516
+ def __init__(self, **kwargs: Any) -> None:
1517
+ kwargs.setdefault("timeout", DEFAULT_TIMEOUT)
1518
+ kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS)
1519
+ kwargs.setdefault("follow_redirects", True)
1520
+
1521
+ super().__init__(**kwargs)
1522
+
1523
+
1524
+ if TYPE_CHECKING:
1525
+ DefaultAsyncHttpxClient = httpx.AsyncClient
1526
+ """An alias to `httpx.AsyncClient` that provides the same defaults that this SDK
1527
+ uses internally.
1528
+
1529
+ This is useful because overriding the `http_client` with your own instance of
1530
+ `httpx.AsyncClient` will result in httpx's defaults being used, not ours.
1531
+ """
1532
+
1533
+ DefaultAioHttpClient = httpx.AsyncClient
1534
+ """An alias to `httpx.AsyncClient` that changes the default HTTP transport to `aiohttp`."""
1535
+ else:
1536
+ DefaultAsyncHttpxClient = _DefaultAsyncHttpxClient
1537
+ DefaultAioHttpClient = _DefaultAioHttpClient
1538
+
1539
+
1540
+ class AsyncHttpxClientWrapper(DefaultAsyncHttpxClient):
1541
+ def __del__(self) -> None:
1542
+ if self.is_closed:
1543
+ return
1544
+
1545
+ try:
1546
+ # TODO(someday): support non asyncio runtimes here
1547
+ asyncio.get_running_loop().create_task(self.aclose())
1548
+ except Exception:
1549
+ pass
1550
+
1551
+
1552
+ class AsyncAPIClient(BaseClient[httpx.AsyncClient, AsyncStream[Any]]):
1553
+ _client: httpx.AsyncClient
1554
+ _default_stream_cls: type[AsyncStream[Any]] | None = None
1555
+
1556
+ def __init__(
1557
+ self,
1558
+ *,
1559
+ version: str,
1560
+ base_url: str | URL,
1561
+ _strict_response_validation: bool,
1562
+ max_retries: int = DEFAULT_MAX_RETRIES,
1563
+ timeout: float | Timeout | None | NotGiven = not_given,
1564
+ http_client: httpx.AsyncClient | None = None,
1565
+ custom_headers: Mapping[str, str] | None = None,
1566
+ custom_query: Mapping[str, object] | None = None,
1567
+ ) -> None:
1568
+ if not is_given(timeout):
1569
+ # if the user passed in a custom http client with a non-default
1570
+ # timeout set then we use that timeout.
1571
+ #
1572
+ # note: there is an edge case here where the user passes in a client
1573
+ # where they've explicitly set the timeout to match the default timeout
1574
+ # as this check is structural, meaning that we'll think they didn't
1575
+ # pass in a timeout and will ignore it
1576
+ if http_client and http_client.timeout != HTTPX_DEFAULT_TIMEOUT:
1577
+ timeout = http_client.timeout
1578
+ else:
1579
+ timeout = DEFAULT_TIMEOUT
1580
+
1581
+ if http_client is not None and not isinstance(http_client, httpx.AsyncClient): # pyright: ignore[reportUnnecessaryIsInstance]
1582
+ raise TypeError(
1583
+ f"Invalid `http_client` argument; Expected an instance of `httpx.AsyncClient` but got {type(http_client)}"
1584
+ )
1585
+
1586
+ super().__init__(
1587
+ version=version,
1588
+ base_url=base_url,
1589
+ # cast to a valid type because mypy doesn't understand our type narrowing
1590
+ timeout=cast(Timeout, timeout),
1591
+ max_retries=max_retries,
1592
+ custom_query=custom_query,
1593
+ custom_headers=custom_headers,
1594
+ _strict_response_validation=_strict_response_validation,
1595
+ )
1596
+ self._client = http_client or AsyncHttpxClientWrapper(
1597
+ base_url=base_url,
1598
+ # cast to a valid type because mypy doesn't understand our type narrowing
1599
+ timeout=cast(Timeout, timeout),
1600
+ )
1601
+
1602
+ def is_closed(self) -> bool:
1603
+ return self._client.is_closed
1604
+
1605
+ async def close(self) -> None:
1606
+ """Close the underlying HTTPX client.
1607
+
1608
+ The client will *not* be usable after this.
1609
+ """
1610
+ await self._client.aclose()
1611
+
1612
+ async def __aenter__(self: _T) -> _T:
1613
+ return self
1614
+
1615
+ async def __aexit__(
1616
+ self,
1617
+ exc_type: type[BaseException] | None,
1618
+ exc: BaseException | None,
1619
+ exc_tb: TracebackType | None,
1620
+ ) -> None:
1621
+ await self.close()
1622
+
1623
+ async def _prepare_options(
1624
+ self,
1625
+ options: FinalRequestOptions, # noqa: ARG002
1626
+ ) -> FinalRequestOptions:
1627
+ """Hook for mutating the given options"""
1628
+ return options
1629
+
1630
+ async def _prepare_request(
1631
+ self,
1632
+ request: httpx.Request, # noqa: ARG002
1633
+ ) -> None:
1634
+ """This method is used as a callback for mutating the `Request` object
1635
+ after it has been constructed.
1636
+ This is useful for cases where you want to add certain headers based off of
1637
+ the request properties, e.g. `url`, `method` etc.
1638
+ """
1639
+ return None
1640
+
1641
+ @overload
1642
+ async def request(
1643
+ self,
1644
+ cast_to: Type[ResponseT],
1645
+ options: FinalRequestOptions,
1646
+ *,
1647
+ stream: Literal[False] = False,
1648
+ ) -> ResponseT: ...
1649
+
1650
+ @overload
1651
+ async def request(
1652
+ self,
1653
+ cast_to: Type[ResponseT],
1654
+ options: FinalRequestOptions,
1655
+ *,
1656
+ stream: Literal[True],
1657
+ stream_cls: type[_AsyncStreamT],
1658
+ ) -> _AsyncStreamT: ...
1659
+
1660
+ @overload
1661
+ async def request(
1662
+ self,
1663
+ cast_to: Type[ResponseT],
1664
+ options: FinalRequestOptions,
1665
+ *,
1666
+ stream: bool,
1667
+ stream_cls: type[_AsyncStreamT] | None = None,
1668
+ ) -> ResponseT | _AsyncStreamT: ...
1669
+
1670
+ async def request(
1671
+ self,
1672
+ cast_to: Type[ResponseT],
1673
+ options: FinalRequestOptions,
1674
+ *,
1675
+ stream: bool = False,
1676
+ stream_cls: type[_AsyncStreamT] | None = None,
1677
+ ) -> ResponseT | _AsyncStreamT:
1678
+ if self._platform is None:
1679
+ # `get_platform` can make blocking IO calls so we
1680
+ # execute it earlier while we are in an async context
1681
+ self._platform = await asyncify(get_platform)()
1682
+
1683
+ cast_to = self._maybe_override_cast_to(cast_to, options)
1684
+
1685
+ # create a copy of the options we were given so that if the
1686
+ # options are mutated later & we then retry, the retries are
1687
+ # given the original options
1688
+ input_options = model_copy(options)
1689
+ if input_options.idempotency_key is None and input_options.method.lower() != "get":
1690
+ # ensure the idempotency key is reused between requests
1691
+ input_options.idempotency_key = self._idempotency_key()
1692
+
1693
+ response: httpx.Response | None = None
1694
+ max_retries = input_options.get_max_retries(self.max_retries)
1695
+
1696
+ retries_taken = 0
1697
+ for retries_taken in range(max_retries + 1):
1698
+ options = model_copy(input_options)
1699
+ options = await self._prepare_options(options)
1700
+
1701
+ remaining_retries = max_retries - retries_taken
1702
+ request = self._build_request(options, retries_taken=retries_taken)
1703
+ await self._prepare_request(request)
1704
+
1705
+ kwargs: HttpxSendArgs = {}
1706
+ if self.custom_auth is not None:
1707
+ kwargs["auth"] = self.custom_auth
1708
+
1709
+ if options.follow_redirects is not None:
1710
+ kwargs["follow_redirects"] = options.follow_redirects
1711
+
1712
+ log.debug("Sending HTTP Request: %s %s", request.method, request.url)
1713
+
1714
+ response = None
1715
+ try:
1716
+ response = await self._client.send(
1717
+ request,
1718
+ stream=stream or self._should_stream_response_body(request=request),
1719
+ **kwargs,
1720
+ )
1721
+ except httpx.TimeoutException as err:
1722
+ log.debug("Encountered httpx.TimeoutException", exc_info=True)
1723
+
1724
+ if remaining_retries > 0:
1725
+ await self._sleep_for_retry(
1726
+ retries_taken=retries_taken,
1727
+ max_retries=max_retries,
1728
+ options=input_options,
1729
+ response=None,
1730
+ )
1731
+ continue
1732
+
1733
+ log.debug("Raising timeout error")
1734
+ raise APITimeoutError(request=request) from err
1735
+ except Exception as err:
1736
+ log.debug("Encountered Exception", exc_info=True)
1737
+
1738
+ if remaining_retries > 0:
1739
+ await self._sleep_for_retry(
1740
+ retries_taken=retries_taken,
1741
+ max_retries=max_retries,
1742
+ options=input_options,
1743
+ response=None,
1744
+ )
1745
+ continue
1746
+
1747
+ log.debug("Raising connection error")
1748
+ raise APIConnectionError(request=request) from err
1749
+
1750
+ log.debug(
1751
+ 'HTTP Response: %s %s "%i %s" %s',
1752
+ request.method,
1753
+ request.url,
1754
+ response.status_code,
1755
+ response.reason_phrase,
1756
+ response.headers,
1757
+ )
1758
+ log.debug("request_id: %s", response.headers.get("request-id"))
1759
+
1760
+ try:
1761
+ response.raise_for_status()
1762
+ except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code
1763
+ log.debug("Encountered httpx.HTTPStatusError", exc_info=True)
1764
+
1765
+ if remaining_retries > 0 and self._should_retry(err.response):
1766
+ await err.response.aclose()
1767
+ await self._sleep_for_retry(
1768
+ retries_taken=retries_taken,
1769
+ max_retries=max_retries,
1770
+ options=input_options,
1771
+ response=response,
1772
+ )
1773
+ continue
1774
+
1775
+ # If the response is streamed then we need to explicitly read the response
1776
+ # to completion before attempting to access the response text.
1777
+ if not err.response.is_closed:
1778
+ await err.response.aread()
1779
+
1780
+ log.debug("Re-raising status error")
1781
+ raise self._make_status_error_from_response(err.response) from None
1782
+
1783
+ break
1784
+
1785
+ assert response is not None, "could not resolve response (should never happen)"
1786
+ return await self._process_response(
1787
+ cast_to=cast_to,
1788
+ options=options,
1789
+ response=response,
1790
+ stream=stream,
1791
+ stream_cls=stream_cls,
1792
+ retries_taken=retries_taken,
1793
+ )
1794
+
1795
+ async def _sleep_for_retry(
1796
+ self, *, retries_taken: int, max_retries: int, options: FinalRequestOptions, response: httpx.Response | None
1797
+ ) -> None:
1798
+ remaining_retries = max_retries - retries_taken
1799
+ if remaining_retries == 1:
1800
+ log.debug("1 retry left")
1801
+ else:
1802
+ log.debug("%i retries left", remaining_retries)
1803
+
1804
+ timeout = self._calculate_retry_timeout(remaining_retries, options, response.headers if response else None)
1805
+ log.info("Retrying request to %s in %f seconds", options.url, timeout)
1806
+
1807
+ await anyio.sleep(timeout)
1808
+
1809
+ async def _process_response(
1810
+ self,
1811
+ *,
1812
+ cast_to: Type[ResponseT],
1813
+ options: FinalRequestOptions,
1814
+ response: httpx.Response,
1815
+ stream: bool,
1816
+ stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None,
1817
+ retries_taken: int = 0,
1818
+ ) -> ResponseT:
1819
+ if response.request.headers.get(RAW_RESPONSE_HEADER) == "true":
1820
+ return cast(
1821
+ ResponseT,
1822
+ LegacyAPIResponse(
1823
+ raw=response,
1824
+ client=self,
1825
+ cast_to=cast_to,
1826
+ stream=stream,
1827
+ stream_cls=stream_cls,
1828
+ options=options,
1829
+ retries_taken=retries_taken,
1830
+ ),
1831
+ )
1832
+
1833
+ origin = get_origin(cast_to) or cast_to
1834
+
1835
+ if (
1836
+ inspect.isclass(origin)
1837
+ and issubclass(origin, BaseAPIResponse)
1838
+ # we only want to actually return the custom BaseAPIResponse class if we're
1839
+ # returning the raw response, or if we're not streaming SSE, as if we're streaming
1840
+ # SSE then `cast_to` doesn't actively reflect the type we need to parse into
1841
+ and (not stream or bool(response.request.headers.get(RAW_RESPONSE_HEADER)))
1842
+ ):
1843
+ if not issubclass(origin, AsyncAPIResponse):
1844
+ raise TypeError(f"API Response types must subclass {AsyncAPIResponse}; Received {origin}")
1845
+
1846
+ response_cls = cast("type[BaseAPIResponse[Any]]", cast_to)
1847
+ return cast(
1848
+ "ResponseT",
1849
+ response_cls(
1850
+ raw=response,
1851
+ client=self,
1852
+ cast_to=extract_response_type(response_cls),
1853
+ stream=stream,
1854
+ stream_cls=stream_cls,
1855
+ options=options,
1856
+ retries_taken=retries_taken,
1857
+ ),
1858
+ )
1859
+
1860
+ if cast_to == httpx.Response:
1861
+ return cast(ResponseT, response)
1862
+
1863
+ api_response = AsyncAPIResponse(
1864
+ raw=response,
1865
+ client=self,
1866
+ cast_to=cast("type[ResponseT]", cast_to), # pyright: ignore[reportUnnecessaryCast]
1867
+ stream=stream,
1868
+ stream_cls=stream_cls,
1869
+ options=options,
1870
+ retries_taken=retries_taken,
1871
+ )
1872
+ if bool(response.request.headers.get(RAW_RESPONSE_HEADER)):
1873
+ return cast(ResponseT, api_response)
1874
+
1875
+ return await api_response.parse()
1876
+
1877
+ def _request_api_list(
1878
+ self,
1879
+ model: Type[_T],
1880
+ page: Type[AsyncPageT],
1881
+ options: FinalRequestOptions,
1882
+ ) -> AsyncPaginator[_T, AsyncPageT]:
1883
+ return AsyncPaginator(client=self, options=options, page_cls=page, model=model)
1884
+
1885
+ @overload
1886
+ async def get(
1887
+ self,
1888
+ path: str,
1889
+ *,
1890
+ cast_to: Type[ResponseT],
1891
+ options: RequestOptions = {},
1892
+ stream: Literal[False] = False,
1893
+ ) -> ResponseT: ...
1894
+
1895
+ @overload
1896
+ async def get(
1897
+ self,
1898
+ path: str,
1899
+ *,
1900
+ cast_to: Type[ResponseT],
1901
+ options: RequestOptions = {},
1902
+ stream: Literal[True],
1903
+ stream_cls: type[_AsyncStreamT],
1904
+ ) -> _AsyncStreamT: ...
1905
+
1906
+ @overload
1907
+ async def get(
1908
+ self,
1909
+ path: str,
1910
+ *,
1911
+ cast_to: Type[ResponseT],
1912
+ options: RequestOptions = {},
1913
+ stream: bool,
1914
+ stream_cls: type[_AsyncStreamT] | None = None,
1915
+ ) -> ResponseT | _AsyncStreamT: ...
1916
+
1917
+ async def get(
1918
+ self,
1919
+ path: str,
1920
+ *,
1921
+ cast_to: Type[ResponseT],
1922
+ options: RequestOptions = {},
1923
+ stream: bool = False,
1924
+ stream_cls: type[_AsyncStreamT] | None = None,
1925
+ ) -> ResponseT | _AsyncStreamT:
1926
+ opts = FinalRequestOptions.construct(method="get", url=path, **options)
1927
+ return await self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)
1928
+
1929
+ @overload
1930
+ async def post(
1931
+ self,
1932
+ path: str,
1933
+ *,
1934
+ cast_to: Type[ResponseT],
1935
+ body: Body | None = None,
1936
+ content: AsyncBinaryTypes | None = None,
1937
+ files: RequestFiles | None = None,
1938
+ options: RequestOptions = {},
1939
+ stream: Literal[False] = False,
1940
+ ) -> ResponseT: ...
1941
+
1942
+ @overload
1943
+ async def post(
1944
+ self,
1945
+ path: str,
1946
+ *,
1947
+ cast_to: Type[ResponseT],
1948
+ body: Body | None = None,
1949
+ content: AsyncBinaryTypes | None = None,
1950
+ files: RequestFiles | None = None,
1951
+ options: RequestOptions = {},
1952
+ stream: Literal[True],
1953
+ stream_cls: type[_AsyncStreamT],
1954
+ ) -> _AsyncStreamT: ...
1955
+
1956
+ @overload
1957
+ async def post(
1958
+ self,
1959
+ path: str,
1960
+ *,
1961
+ cast_to: Type[ResponseT],
1962
+ body: Body | None = None,
1963
+ content: AsyncBinaryTypes | None = None,
1964
+ files: RequestFiles | None = None,
1965
+ options: RequestOptions = {},
1966
+ stream: bool,
1967
+ stream_cls: type[_AsyncStreamT] | None = None,
1968
+ ) -> ResponseT | _AsyncStreamT: ...
1969
+
1970
+ async def post(
1971
+ self,
1972
+ path: str,
1973
+ *,
1974
+ cast_to: Type[ResponseT],
1975
+ body: Body | None = None,
1976
+ content: AsyncBinaryTypes | None = None,
1977
+ files: RequestFiles | None = None,
1978
+ options: RequestOptions = {},
1979
+ stream: bool = False,
1980
+ stream_cls: type[_AsyncStreamT] | None = None,
1981
+ ) -> ResponseT | _AsyncStreamT:
1982
+ if body is not None and content is not None:
1983
+ raise TypeError("Passing both `body` and `content` is not supported")
1984
+ if files is not None and content is not None:
1985
+ raise TypeError("Passing both `files` and `content` is not supported")
1986
+ if isinstance(body, bytes):
1987
+ warnings.warn(
1988
+ "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
1989
+ "Please pass raw bytes via the `content` parameter instead.",
1990
+ DeprecationWarning,
1991
+ stacklevel=2,
1992
+ )
1993
+ opts = FinalRequestOptions.construct(
1994
+ method="post", url=path, json_data=body, content=content, files=await async_to_httpx_files(files), **options
1995
+ )
1996
+ return await self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)
1997
+
1998
+ async def patch(
1999
+ self,
2000
+ path: str,
2001
+ *,
2002
+ cast_to: Type[ResponseT],
2003
+ body: Body | None = None,
2004
+ content: AsyncBinaryTypes | None = None,
2005
+ files: RequestFiles | None = None,
2006
+ options: RequestOptions = {},
2007
+ ) -> ResponseT:
2008
+ if body is not None and content is not None:
2009
+ raise TypeError("Passing both `body` and `content` is not supported")
2010
+ if files is not None and content is not None:
2011
+ raise TypeError("Passing both `files` and `content` is not supported")
2012
+ if isinstance(body, bytes):
2013
+ warnings.warn(
2014
+ "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
2015
+ "Please pass raw bytes via the `content` parameter instead.",
2016
+ DeprecationWarning,
2017
+ stacklevel=2,
2018
+ )
2019
+ opts = FinalRequestOptions.construct(
2020
+ method="patch",
2021
+ url=path,
2022
+ json_data=body,
2023
+ content=content,
2024
+ files=await async_to_httpx_files(files),
2025
+ **options,
2026
+ )
2027
+ return await self.request(cast_to, opts)
2028
+
2029
+ async def put(
2030
+ self,
2031
+ path: str,
2032
+ *,
2033
+ cast_to: Type[ResponseT],
2034
+ body: Body | None = None,
2035
+ content: AsyncBinaryTypes | None = None,
2036
+ files: RequestFiles | None = None,
2037
+ options: RequestOptions = {},
2038
+ ) -> ResponseT:
2039
+ if body is not None and content is not None:
2040
+ raise TypeError("Passing both `body` and `content` is not supported")
2041
+ if files is not None and content is not None:
2042
+ raise TypeError("Passing both `files` and `content` is not supported")
2043
+ if isinstance(body, bytes):
2044
+ warnings.warn(
2045
+ "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
2046
+ "Please pass raw bytes via the `content` parameter instead.",
2047
+ DeprecationWarning,
2048
+ stacklevel=2,
2049
+ )
2050
+ opts = FinalRequestOptions.construct(
2051
+ method="put", url=path, json_data=body, content=content, files=await async_to_httpx_files(files), **options
2052
+ )
2053
+ return await self.request(cast_to, opts)
2054
+
2055
+ async def delete(
2056
+ self,
2057
+ path: str,
2058
+ *,
2059
+ cast_to: Type[ResponseT],
2060
+ body: Body | None = None,
2061
+ content: AsyncBinaryTypes | None = None,
2062
+ options: RequestOptions = {},
2063
+ ) -> ResponseT:
2064
+ if body is not None and content is not None:
2065
+ raise TypeError("Passing both `body` and `content` is not supported")
2066
+ if isinstance(body, bytes):
2067
+ warnings.warn(
2068
+ "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
2069
+ "Please pass raw bytes via the `content` parameter instead.",
2070
+ DeprecationWarning,
2071
+ stacklevel=2,
2072
+ )
2073
+ opts = FinalRequestOptions.construct(method="delete", url=path, json_data=body, content=content, **options)
2074
+ return await self.request(cast_to, opts)
2075
+
2076
+ def get_api_list(
2077
+ self,
2078
+ path: str,
2079
+ *,
2080
+ model: Type[_T],
2081
+ page: Type[AsyncPageT],
2082
+ body: Body | None = None,
2083
+ options: RequestOptions = {},
2084
+ method: str = "get",
2085
+ ) -> AsyncPaginator[_T, AsyncPageT]:
2086
+ opts = FinalRequestOptions.construct(method=method, url=path, json_data=body, **options)
2087
+ return self._request_api_list(model, page, opts)
2088
+
2089
+
2090
+ def make_request_options(
2091
+ *,
2092
+ query: Query | None = None,
2093
+ extra_headers: Headers | None = None,
2094
+ extra_query: Query | None = None,
2095
+ extra_body: Body | None = None,
2096
+ idempotency_key: str | None = None,
2097
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
2098
+ post_parser: PostParser | NotGiven = not_given,
2099
+ ) -> RequestOptions:
2100
+ """Create a dict of type RequestOptions without keys of NotGiven values."""
2101
+ options: RequestOptions = {}
2102
+ if extra_headers is not None:
2103
+ options["headers"] = extra_headers
2104
+
2105
+ if extra_body is not None:
2106
+ options["extra_json"] = cast(AnyMapping, extra_body)
2107
+
2108
+ if query is not None:
2109
+ options["params"] = query
2110
+
2111
+ if extra_query is not None:
2112
+ options["params"] = {**options.get("params", {}), **extra_query}
2113
+
2114
+ if not isinstance(timeout, NotGiven):
2115
+ options["timeout"] = timeout
2116
+
2117
+ if idempotency_key is not None:
2118
+ options["idempotency_key"] = idempotency_key
2119
+
2120
+ if is_given(post_parser):
2121
+ # internal
2122
+ options["post_parser"] = post_parser # type: ignore
2123
+
2124
+ return options
2125
+
2126
+
2127
+ class ForceMultipartDict(Dict[str, None]):
2128
+ def __bool__(self) -> bool:
2129
+ return True
2130
+
2131
+
2132
+ class OtherPlatform:
2133
+ def __init__(self, name: str) -> None:
2134
+ self.name = name
2135
+
2136
+ @override
2137
+ def __str__(self) -> str:
2138
+ return f"Other:{self.name}"
2139
+
2140
+
2141
+ Platform = Union[
2142
+ OtherPlatform,
2143
+ Literal[
2144
+ "MacOS",
2145
+ "Linux",
2146
+ "Windows",
2147
+ "FreeBSD",
2148
+ "OpenBSD",
2149
+ "iOS",
2150
+ "Android",
2151
+ "Unknown",
2152
+ ],
2153
+ ]
2154
+
2155
+
2156
+ def get_platform() -> Platform:
2157
+ try:
2158
+ system = platform.system().lower()
2159
+ platform_name = platform.platform().lower()
2160
+ except Exception:
2161
+ return "Unknown"
2162
+
2163
+ if "iphone" in platform_name or "ipad" in platform_name:
2164
+ # Tested using Python3IDE on an iPhone 11 and Pythonista on an iPad 7
2165
+ # system is Darwin and platform_name is a string like:
2166
+ # - Darwin-21.6.0-iPhone12,1-64bit
2167
+ # - Darwin-21.6.0-iPad7,11-64bit
2168
+ return "iOS"
2169
+
2170
+ if system == "darwin":
2171
+ return "MacOS"
2172
+
2173
+ if system == "windows":
2174
+ return "Windows"
2175
+
2176
+ if "android" in platform_name:
2177
+ # Tested using Pydroid 3
2178
+ # system is Linux and platform_name is a string like 'Linux-5.10.81-android12-9-00001-geba40aecb3b7-ab8534902-aarch64-with-libc'
2179
+ return "Android"
2180
+
2181
+ if system == "linux":
2182
+ # https://distro.readthedocs.io/en/latest/#distro.id
2183
+ distro_id = distro.id()
2184
+ if distro_id == "freebsd":
2185
+ return "FreeBSD"
2186
+
2187
+ if distro_id == "openbsd":
2188
+ return "OpenBSD"
2189
+
2190
+ return "Linux"
2191
+
2192
+ if platform_name:
2193
+ return OtherPlatform(platform_name)
2194
+
2195
+ return "Unknown"
2196
+
2197
+
2198
+ @lru_cache(maxsize=None)
2199
+ def platform_headers(version: str, *, platform: Platform | None) -> Dict[str, str]:
2200
+ return {
2201
+ "X-Stainless-Lang": "python",
2202
+ "X-Stainless-Package-Version": version,
2203
+ "X-Stainless-OS": str(platform or get_platform()),
2204
+ "X-Stainless-Arch": str(get_architecture()),
2205
+ "X-Stainless-Runtime": get_python_runtime(),
2206
+ "X-Stainless-Runtime-Version": get_python_version(),
2207
+ }
2208
+
2209
+
2210
+ class OtherArch:
2211
+ def __init__(self, name: str) -> None:
2212
+ self.name = name
2213
+
2214
+ @override
2215
+ def __str__(self) -> str:
2216
+ return f"other:{self.name}"
2217
+
2218
+
2219
+ Arch = Union[OtherArch, Literal["x32", "x64", "arm", "arm64", "unknown"]]
2220
+
2221
+
2222
+ def get_python_runtime() -> str:
2223
+ try:
2224
+ return platform.python_implementation()
2225
+ except Exception:
2226
+ return "unknown"
2227
+
2228
+
2229
+ def get_python_version() -> str:
2230
+ try:
2231
+ return platform.python_version()
2232
+ except Exception:
2233
+ return "unknown"
2234
+
2235
+
2236
+ def get_architecture() -> Arch:
2237
+ try:
2238
+ machine = platform.machine().lower()
2239
+ except Exception:
2240
+ return "unknown"
2241
+
2242
+ if machine in ("arm64", "aarch64"):
2243
+ return "arm64"
2244
+
2245
+ # TODO: untested
2246
+ if machine == "arm":
2247
+ return "arm"
2248
+
2249
+ if machine == "x86_64":
2250
+ return "x64"
2251
+
2252
+ # TODO: untested
2253
+ if sys.maxsize <= 2**32:
2254
+ return "x32"
2255
+
2256
+ if machine:
2257
+ return OtherArch(machine)
2258
+
2259
+ return "unknown"
2260
+
2261
+
2262
+ def _merge_mappings(
2263
+ obj1: Mapping[_T_co, Union[_T, Omit]],
2264
+ obj2: Mapping[_T_co, Union[_T, Omit]],
2265
+ ) -> Dict[_T_co, _T]:
2266
+ """Merge two mappings of the same type, removing any values that are instances of `Omit`.
2267
+
2268
+ In cases with duplicate keys the second mapping takes precedence.
2269
+ """
2270
+ merged = {**obj1, **obj2}
2271
+ return {key: value for key, value in merged.items() if not isinstance(value, Omit)}
data/miniconda3/lib/python3.13/site-packages/anthropic/_client.py ADDED
@@ -0,0 +1,659 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import TYPE_CHECKING, Any, Mapping
7
+ from typing_extensions import Self, override
8
+
9
+ import httpx
10
+
11
+ from . import _constants, _exceptions
12
+ from ._qs import Querystring
13
+ from ._types import (
14
+ Omit,
15
+ Headers,
16
+ Timeout,
17
+ NotGiven,
18
+ Transport,
19
+ ProxiesTypes,
20
+ RequestOptions,
21
+ not_given,
22
+ )
23
+ from ._utils import is_given, get_async_library
24
+ from ._compat import cached_property
25
+ from ._version import __version__
26
+ from ._streaming import Stream as Stream, AsyncStream as AsyncStream
27
+ from ._exceptions import APIStatusError
28
+ from ._base_client import (
29
+ DEFAULT_MAX_RETRIES,
30
+ SyncAPIClient,
31
+ AsyncAPIClient,
32
+ )
33
+
34
+ if TYPE_CHECKING:
35
+ from .resources import beta, models, messages, completions
36
+ from .resources.models import Models, AsyncModels
37
+ from .resources.beta.beta import Beta, AsyncBeta
38
+ from .resources.completions import Completions, AsyncCompletions
39
+ from .resources.messages.messages import Messages, AsyncMessages
40
+
41
+ __all__ = [
42
+ "Timeout",
43
+ "Transport",
44
+ "ProxiesTypes",
45
+ "RequestOptions",
46
+ "Anthropic",
47
+ "AsyncAnthropic",
48
+ "Client",
49
+ "AsyncClient",
50
+ ]
51
+
52
+
53
+ class Anthropic(SyncAPIClient):
54
+ # client options
55
+ api_key: str | None
56
+ auth_token: str | None
57
+
58
+ # constants
59
+ HUMAN_PROMPT = _constants.HUMAN_PROMPT
60
+ AI_PROMPT = _constants.AI_PROMPT
61
+
62
+ def __init__(
63
+ self,
64
+ *,
65
+ api_key: str | None = None,
66
+ auth_token: str | None = None,
67
+ base_url: str | httpx.URL | None = None,
68
+ timeout: float | Timeout | None | NotGiven = not_given,
69
+ max_retries: int = DEFAULT_MAX_RETRIES,
70
+ default_headers: Mapping[str, str] | None = None,
71
+ default_query: Mapping[str, object] | None = None,
72
+ # Configure a custom httpx client.
73
+ # We provide a `DefaultHttpxClient` class that you can pass to retain the default values we use for `limits`, `timeout` & `follow_redirects`.
74
+ # See the [httpx documentation](https://www.python-httpx.org/api/#client) for more details.
75
+ http_client: httpx.Client | None = None,
76
+ # Enable or disable schema validation for data returned by the API.
77
+ # When enabled an error APIResponseValidationError is raised
78
+ # if the API responds with invalid data for the expected schema.
79
+ #
80
+ # This parameter may be removed or changed in the future.
81
+ # If you rely on this feature, please open a GitHub issue
82
+ # outlining your use-case to help us decide if it should be
83
+ # part of our public interface in the future.
84
+ _strict_response_validation: bool = False,
85
+ ) -> None:
86
+ """Construct a new synchronous Anthropic client instance.
87
+
88
+ This automatically infers the following arguments from their corresponding environment variables if they are not provided:
89
+ - `api_key` from `ANTHROPIC_API_KEY`
90
+ - `auth_token` from `ANTHROPIC_AUTH_TOKEN`
91
+ """
92
+ if api_key is None:
93
+ api_key = os.environ.get("ANTHROPIC_API_KEY")
94
+ self.api_key = api_key
95
+
96
+ if auth_token is None:
97
+ auth_token = os.environ.get("ANTHROPIC_AUTH_TOKEN")
98
+ self.auth_token = auth_token
99
+
100
+ if base_url is None:
101
+ base_url = os.environ.get("ANTHROPIC_BASE_URL")
102
+ if base_url is None:
103
+ base_url = f"https://api.anthropic.com"
104
+
105
+ super().__init__(
106
+ version=__version__,
107
+ base_url=base_url,
108
+ max_retries=max_retries,
109
+ timeout=timeout,
110
+ http_client=http_client,
111
+ custom_headers=default_headers,
112
+ custom_query=default_query,
113
+ _strict_response_validation=_strict_response_validation,
114
+ )
115
+
116
+ self._default_stream_cls = Stream
117
+
118
+ @cached_property
119
+ def completions(self) -> Completions:
120
+ from .resources.completions import Completions
121
+
122
+ return Completions(self)
123
+
124
+ @cached_property
125
+ def messages(self) -> Messages:
126
+ from .resources.messages import Messages
127
+
128
+ return Messages(self)
129
+
130
+ @cached_property
131
+ def models(self) -> Models:
132
+ from .resources.models import Models
133
+
134
+ return Models(self)
135
+
136
+ @cached_property
137
+ def beta(self) -> Beta:
138
+ from .resources.beta import Beta
139
+
140
+ return Beta(self)
141
+
142
+ @cached_property
143
+ def with_raw_response(self) -> AnthropicWithRawResponse:
144
+ return AnthropicWithRawResponse(self)
145
+
146
+ @cached_property
147
+ def with_streaming_response(self) -> AnthropicWithStreamedResponse:
148
+ return AnthropicWithStreamedResponse(self)
149
+
150
+ @property
151
+ @override
152
+ def qs(self) -> Querystring:
153
+ return Querystring(array_format="comma")
154
+
155
+ @property
156
+ @override
157
+ def auth_headers(self) -> dict[str, str]:
158
+ return {**self._api_key_auth, **self._bearer_auth}
159
+
160
+ @property
161
+ def _api_key_auth(self) -> dict[str, str]:
162
+ api_key = self.api_key
163
+ if api_key is None:
164
+ return {}
165
+ return {"X-Api-Key": api_key}
166
+
167
+ @property
168
+ def _bearer_auth(self) -> dict[str, str]:
169
+ auth_token = self.auth_token
170
+ if auth_token is None:
171
+ return {}
172
+ return {"Authorization": f"Bearer {auth_token}"}
173
+
174
+ @property
175
+ @override
176
+ def default_headers(self) -> dict[str, str | Omit]:
177
+ return {
178
+ **super().default_headers,
179
+ "X-Stainless-Async": "false",
180
+ "anthropic-version": "2023-06-01",
181
+ **self._custom_headers,
182
+ }
183
+
184
+ @override
185
+ def _validate_headers(self, headers: Headers, custom_headers: Headers) -> None:
186
+ if headers.get("Authorization") or headers.get("X-Api-Key"):
187
+ # valid
188
+ return
189
+
190
+ if headers.get("X-Api-Key") or isinstance(custom_headers.get("X-Api-Key"), Omit):
191
+ return
192
+
193
+ if headers.get("Authorization") or isinstance(custom_headers.get("Authorization"), Omit):
194
+ return
195
+
196
+ raise TypeError(
197
+ '"Could not resolve authentication method. Expected either api_key or auth_token to be set. Or for one of the `X-Api-Key` or `Authorization` headers to be explicitly omitted"'
198
+ )
199
+
200
+ def copy(
201
+ self,
202
+ *,
203
+ api_key: str | None = None,
204
+ auth_token: str | None = None,
205
+ base_url: str | httpx.URL | None = None,
206
+ timeout: float | Timeout | None | NotGiven = not_given,
207
+ http_client: httpx.Client | None = None,
208
+ max_retries: int | NotGiven = not_given,
209
+ default_headers: Mapping[str, str] | None = None,
210
+ set_default_headers: Mapping[str, str] | None = None,
211
+ default_query: Mapping[str, object] | None = None,
212
+ set_default_query: Mapping[str, object] | None = None,
213
+ _extra_kwargs: Mapping[str, Any] = {},
214
+ ) -> Self:
215
+ """
216
+ Create a new client instance re-using the same options given to the current client with optional overriding.
217
+ """
218
+ if default_headers is not None and set_default_headers is not None:
219
+ raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive")
220
+
221
+ if default_query is not None and set_default_query is not None:
222
+ raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive")
223
+
224
+ headers = self._custom_headers
225
+ if default_headers is not None:
226
+ headers = {**headers, **default_headers}
227
+ elif set_default_headers is not None:
228
+ headers = set_default_headers
229
+
230
+ params = self._custom_query
231
+ if default_query is not None:
232
+ params = {**params, **default_query}
233
+ elif set_default_query is not None:
234
+ params = set_default_query
235
+
236
+ http_client = http_client or self._client
237
+ return self.__class__(
238
+ api_key=api_key or self.api_key,
239
+ auth_token=auth_token or self.auth_token,
240
+ base_url=base_url or self.base_url,
241
+ timeout=self.timeout if isinstance(timeout, NotGiven) else timeout,
242
+ http_client=http_client,
243
+ max_retries=max_retries if is_given(max_retries) else self.max_retries,
244
+ default_headers=headers,
245
+ default_query=params,
246
+ **_extra_kwargs,
247
+ )
248
+
249
+ # Alias for `copy` for nicer inline usage, e.g.
250
+ # client.with_options(timeout=10).foo.create(...)
251
+ with_options = copy
252
+
253
+ @override
254
+ def _make_status_error(
255
+ self,
256
+ err_msg: str,
257
+ *,
258
+ body: object,
259
+ response: httpx.Response,
260
+ ) -> APIStatusError:
261
+ if response.status_code == 400:
262
+ return _exceptions.BadRequestError(err_msg, response=response, body=body)
263
+
264
+ if response.status_code == 401:
265
+ return _exceptions.AuthenticationError(err_msg, response=response, body=body)
266
+
267
+ if response.status_code == 403:
268
+ return _exceptions.PermissionDeniedError(err_msg, response=response, body=body)
269
+
270
+ if response.status_code == 404:
271
+ return _exceptions.NotFoundError(err_msg, response=response, body=body)
272
+
273
+ if response.status_code == 409:
274
+ return _exceptions.ConflictError(err_msg, response=response, body=body)
275
+
276
+ if response.status_code == 413:
277
+ return _exceptions.RequestTooLargeError(err_msg, response=response, body=body)
278
+
279
+ if response.status_code == 422:
280
+ return _exceptions.UnprocessableEntityError(err_msg, response=response, body=body)
281
+
282
+ if response.status_code == 429:
283
+ return _exceptions.RateLimitError(err_msg, response=response, body=body)
284
+
285
+ if response.status_code == 529:
286
+ return _exceptions.OverloadedError(err_msg, response=response, body=body)
287
+
288
+ if response.status_code >= 500:
289
+ return _exceptions.InternalServerError(err_msg, response=response, body=body)
290
+ return APIStatusError(err_msg, response=response, body=body)
291
+
292
+
293
+ class AsyncAnthropic(AsyncAPIClient):
294
+ # client options
295
+ api_key: str | None
296
+ auth_token: str | None
297
+
298
+ # constants
299
+ HUMAN_PROMPT = _constants.HUMAN_PROMPT
300
+ AI_PROMPT = _constants.AI_PROMPT
301
+
302
+ def __init__(
303
+ self,
304
+ *,
305
+ api_key: str | None = None,
306
+ auth_token: str | None = None,
307
+ base_url: str | httpx.URL | None = None,
308
+ timeout: float | Timeout | None | NotGiven = not_given,
309
+ max_retries: int = DEFAULT_MAX_RETRIES,
310
+ default_headers: Mapping[str, str] | None = None,
311
+ default_query: Mapping[str, object] | None = None,
312
+ # Configure a custom httpx client.
313
+ # We provide a `DefaultAsyncHttpxClient` class that you can pass to retain the default values we use for `limits`, `timeout` & `follow_redirects`.
314
+ # See the [httpx documentation](https://www.python-httpx.org/api/#asyncclient) for more details.
315
+ http_client: httpx.AsyncClient | None = None,
316
+ # Enable or disable schema validation for data returned by the API.
317
+ # When enabled an error APIResponseValidationError is raised
318
+ # if the API responds with invalid data for the expected schema.
319
+ #
320
+ # This parameter may be removed or changed in the future.
321
+ # If you rely on this feature, please open a GitHub issue
322
+ # outlining your use-case to help us decide if it should be
323
+ # part of our public interface in the future.
324
+ _strict_response_validation: bool = False,
325
+ ) -> None:
326
+ """Construct a new async AsyncAnthropic client instance.
327
+
328
+ This automatically infers the following arguments from their corresponding environment variables if they are not provided:
329
+ - `api_key` from `ANTHROPIC_API_KEY`
330
+ - `auth_token` from `ANTHROPIC_AUTH_TOKEN`
331
+ """
332
+ if api_key is None:
333
+ api_key = os.environ.get("ANTHROPIC_API_KEY")
334
+ self.api_key = api_key
335
+
336
+ if auth_token is None:
337
+ auth_token = os.environ.get("ANTHROPIC_AUTH_TOKEN")
338
+ self.auth_token = auth_token
339
+
340
+ if base_url is None:
341
+ base_url = os.environ.get("ANTHROPIC_BASE_URL")
342
+ if base_url is None:
343
+ base_url = f"https://api.anthropic.com"
344
+
345
+ super().__init__(
346
+ version=__version__,
347
+ base_url=base_url,
348
+ max_retries=max_retries,
349
+ timeout=timeout,
350
+ http_client=http_client,
351
+ custom_headers=default_headers,
352
+ custom_query=default_query,
353
+ _strict_response_validation=_strict_response_validation,
354
+ )
355
+
356
+ self._default_stream_cls = AsyncStream
357
+
358
+ @cached_property
359
+ def completions(self) -> AsyncCompletions:
360
+ from .resources.completions import AsyncCompletions
361
+
362
+ return AsyncCompletions(self)
363
+
364
+ @cached_property
365
+ def messages(self) -> AsyncMessages:
366
+ from .resources.messages import AsyncMessages
367
+
368
+ return AsyncMessages(self)
369
+
370
+ @cached_property
371
+ def models(self) -> AsyncModels:
372
+ from .resources.models import AsyncModels
373
+
374
+ return AsyncModels(self)
375
+
376
+ @cached_property
377
+ def beta(self) -> AsyncBeta:
378
+ from .resources.beta import AsyncBeta
379
+
380
+ return AsyncBeta(self)
381
+
382
+ @cached_property
383
+ def with_raw_response(self) -> AsyncAnthropicWithRawResponse:
384
+ return AsyncAnthropicWithRawResponse(self)
385
+
386
+ @cached_property
387
+ def with_streaming_response(self) -> AsyncAnthropicWithStreamedResponse:
388
+ return AsyncAnthropicWithStreamedResponse(self)
389
+
390
+ @property
391
+ @override
392
+ def qs(self) -> Querystring:
393
+ return Querystring(array_format="comma")
394
+
395
+ @property
396
+ @override
397
+ def auth_headers(self) -> dict[str, str]:
398
+ return {**self._api_key_auth, **self._bearer_auth}
399
+
400
+ @property
401
+ def _api_key_auth(self) -> dict[str, str]:
402
+ api_key = self.api_key
403
+ if api_key is None:
404
+ return {}
405
+ return {"X-Api-Key": api_key}
406
+
407
+ @property
408
+ def _bearer_auth(self) -> dict[str, str]:
409
+ auth_token = self.auth_token
410
+ if auth_token is None:
411
+ return {}
412
+ return {"Authorization": f"Bearer {auth_token}"}
413
+
414
+ @property
415
+ @override
416
+ def default_headers(self) -> dict[str, str | Omit]:
417
+ return {
418
+ **super().default_headers,
419
+ "X-Stainless-Async": f"async:{get_async_library()}",
420
+ "anthropic-version": "2023-06-01",
421
+ **self._custom_headers,
422
+ }
423
+
424
+ @override
425
+ def _validate_headers(self, headers: Headers, custom_headers: Headers) -> None:
426
+ if headers.get("Authorization") or headers.get("X-Api-Key"):
427
+ # valid
428
+ return
429
+
430
+ if headers.get("X-Api-Key") or isinstance(custom_headers.get("X-Api-Key"), Omit):
431
+ return
432
+
433
+ if headers.get("Authorization") or isinstance(custom_headers.get("Authorization"), Omit):
434
+ return
435
+
436
+ raise TypeError(
437
+ '"Could not resolve authentication method. Expected either api_key or auth_token to be set. Or for one of the `X-Api-Key` or `Authorization` headers to be explicitly omitted"'
438
+ )
439
+
440
+ def copy(
441
+ self,
442
+ *,
443
+ api_key: str | None = None,
444
+ auth_token: str | None = None,
445
+ base_url: str | httpx.URL | None = None,
446
+ timeout: float | Timeout | None | NotGiven = not_given,
447
+ http_client: httpx.AsyncClient | None = None,
448
+ max_retries: int | NotGiven = not_given,
449
+ default_headers: Mapping[str, str] | None = None,
450
+ set_default_headers: Mapping[str, str] | None = None,
451
+ default_query: Mapping[str, object] | None = None,
452
+ set_default_query: Mapping[str, object] | None = None,
453
+ _extra_kwargs: Mapping[str, Any] = {},
454
+ ) -> Self:
455
+ """
456
+ Create a new client instance re-using the same options given to the current client with optional overriding.
457
+ """
458
+ if default_headers is not None and set_default_headers is not None:
459
+ raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive")
460
+
461
+ if default_query is not None and set_default_query is not None:
462
+ raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive")
463
+
464
+ headers = self._custom_headers
465
+ if default_headers is not None:
466
+ headers = {**headers, **default_headers}
467
+ elif set_default_headers is not None:
468
+ headers = set_default_headers
469
+
470
+ params = self._custom_query
471
+ if default_query is not None:
472
+ params = {**params, **default_query}
473
+ elif set_default_query is not None:
474
+ params = set_default_query
475
+
476
+ http_client = http_client or self._client
477
+ return self.__class__(
478
+ api_key=api_key or self.api_key,
479
+ auth_token=auth_token or self.auth_token,
480
+ base_url=base_url or self.base_url,
481
+ timeout=self.timeout if isinstance(timeout, NotGiven) else timeout,
482
+ http_client=http_client,
483
+ max_retries=max_retries if is_given(max_retries) else self.max_retries,
484
+ default_headers=headers,
485
+ default_query=params,
486
+ **_extra_kwargs,
487
+ )
488
+
489
+ # Alias for `copy` for nicer inline usage, e.g.
490
+ # client.with_options(timeout=10).foo.create(...)
491
+ with_options = copy
492
+
493
+ @override
494
+ def _make_status_error(
495
+ self,
496
+ err_msg: str,
497
+ *,
498
+ body: object,
499
+ response: httpx.Response,
500
+ ) -> APIStatusError:
501
+ if response.status_code == 400:
502
+ return _exceptions.BadRequestError(err_msg, response=response, body=body)
503
+
504
+ if response.status_code == 401:
505
+ return _exceptions.AuthenticationError(err_msg, response=response, body=body)
506
+
507
+ if response.status_code == 403:
508
+ return _exceptions.PermissionDeniedError(err_msg, response=response, body=body)
509
+
510
+ if response.status_code == 404:
511
+ return _exceptions.NotFoundError(err_msg, response=response, body=body)
512
+
513
+ if response.status_code == 409:
514
+ return _exceptions.ConflictError(err_msg, response=response, body=body)
515
+
516
+ if response.status_code == 413:
517
+ return _exceptions.RequestTooLargeError(err_msg, response=response, body=body)
518
+
519
+ if response.status_code == 422:
520
+ return _exceptions.UnprocessableEntityError(err_msg, response=response, body=body)
521
+
522
+ if response.status_code == 429:
523
+ return _exceptions.RateLimitError(err_msg, response=response, body=body)
524
+
525
+ if response.status_code == 529:
526
+ return _exceptions.OverloadedError(err_msg, response=response, body=body)
527
+
528
+ if response.status_code >= 500:
529
+ return _exceptions.InternalServerError(err_msg, response=response, body=body)
530
+ return APIStatusError(err_msg, response=response, body=body)
531
+
532
+
533
+ class AnthropicWithRawResponse:
534
+ _client: Anthropic
535
+
536
+ def __init__(self, client: Anthropic) -> None:
537
+ self._client = client
538
+
539
+ @cached_property
540
+ def completions(self) -> completions.CompletionsWithRawResponse:
541
+ from .resources.completions import CompletionsWithRawResponse
542
+
543
+ return CompletionsWithRawResponse(self._client.completions)
544
+
545
+ @cached_property
546
+ def messages(self) -> messages.MessagesWithRawResponse:
547
+ from .resources.messages import MessagesWithRawResponse
548
+
549
+ return MessagesWithRawResponse(self._client.messages)
550
+
551
+ @cached_property
552
+ def models(self) -> models.ModelsWithRawResponse:
553
+ from .resources.models import ModelsWithRawResponse
554
+
555
+ return ModelsWithRawResponse(self._client.models)
556
+
557
+ @cached_property
558
+ def beta(self) -> beta.BetaWithRawResponse:
559
+ from .resources.beta import BetaWithRawResponse
560
+
561
+ return BetaWithRawResponse(self._client.beta)
562
+
563
+
564
+ class AsyncAnthropicWithRawResponse:
565
+ _client: AsyncAnthropic
566
+
567
+ def __init__(self, client: AsyncAnthropic) -> None:
568
+ self._client = client
569
+
570
+ @cached_property
571
+ def completions(self) -> completions.AsyncCompletionsWithRawResponse:
572
+ from .resources.completions import AsyncCompletionsWithRawResponse
573
+
574
+ return AsyncCompletionsWithRawResponse(self._client.completions)
575
+
576
+ @cached_property
577
+ def messages(self) -> messages.AsyncMessagesWithRawResponse:
578
+ from .resources.messages import AsyncMessagesWithRawResponse
579
+
580
+ return AsyncMessagesWithRawResponse(self._client.messages)
581
+
582
+ @cached_property
583
+ def models(self) -> models.AsyncModelsWithRawResponse:
584
+ from .resources.models import AsyncModelsWithRawResponse
585
+
586
+ return AsyncModelsWithRawResponse(self._client.models)
587
+
588
+ @cached_property
589
+ def beta(self) -> beta.AsyncBetaWithRawResponse:
590
+ from .resources.beta import AsyncBetaWithRawResponse
591
+
592
+ return AsyncBetaWithRawResponse(self._client.beta)
593
+
594
+
595
+ class AnthropicWithStreamedResponse:
596
+ _client: Anthropic
597
+
598
+ def __init__(self, client: Anthropic) -> None:
599
+ self._client = client
600
+
601
+ @cached_property
602
+ def completions(self) -> completions.CompletionsWithStreamingResponse:
603
+ from .resources.completions import CompletionsWithStreamingResponse
604
+
605
+ return CompletionsWithStreamingResponse(self._client.completions)
606
+
607
+ @cached_property
608
+ def messages(self) -> messages.MessagesWithStreamingResponse:
609
+ from .resources.messages import MessagesWithStreamingResponse
610
+
611
+ return MessagesWithStreamingResponse(self._client.messages)
612
+
613
+ @cached_property
614
+ def models(self) -> models.ModelsWithStreamingResponse:
615
+ from .resources.models import ModelsWithStreamingResponse
616
+
617
+ return ModelsWithStreamingResponse(self._client.models)
618
+
619
+ @cached_property
620
+ def beta(self) -> beta.BetaWithStreamingResponse:
621
+ from .resources.beta import BetaWithStreamingResponse
622
+
623
+ return BetaWithStreamingResponse(self._client.beta)
624
+
625
+
626
+ class AsyncAnthropicWithStreamedResponse:
627
+ _client: AsyncAnthropic
628
+
629
+ def __init__(self, client: AsyncAnthropic) -> None:
630
+ self._client = client
631
+
632
+ @cached_property
633
+ def completions(self) -> completions.AsyncCompletionsWithStreamingResponse:
634
+ from .resources.completions import AsyncCompletionsWithStreamingResponse
635
+
636
+ return AsyncCompletionsWithStreamingResponse(self._client.completions)
637
+
638
+ @cached_property
639
+ def messages(self) -> messages.AsyncMessagesWithStreamingResponse:
640
+ from .resources.messages import AsyncMessagesWithStreamingResponse
641
+
642
+ return AsyncMessagesWithStreamingResponse(self._client.messages)
643
+
644
+ @cached_property
645
+ def models(self) -> models.AsyncModelsWithStreamingResponse:
646
+ from .resources.models import AsyncModelsWithStreamingResponse
647
+
648
+ return AsyncModelsWithStreamingResponse(self._client.models)
649
+
650
+ @cached_property
651
+ def beta(self) -> beta.AsyncBetaWithStreamingResponse:
652
+ from .resources.beta import AsyncBetaWithStreamingResponse
653
+
654
+ return AsyncBetaWithStreamingResponse(self._client.beta)
655
+
656
+
657
+ Client = Anthropic
658
+
659
+ AsyncClient = AsyncAnthropic
data/miniconda3/lib/python3.13/site-packages/anthropic/_compat.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, cast, overload
4
+ from datetime import date, datetime
5
+ from typing_extensions import Self, Literal, TypedDict
6
+
7
+ import pydantic
8
+ from pydantic.fields import FieldInfo
9
+
10
+ from ._types import IncEx, StrBytesIntFloat
11
+
12
+ _T = TypeVar("_T")
13
+ _ModelT = TypeVar("_ModelT", bound=pydantic.BaseModel)
14
+
15
+ # --------------- Pydantic v2, v3 compatibility ---------------
16
+
17
+ # Pyright incorrectly reports some of our functions as overriding a method when they don't
18
+ # pyright: reportIncompatibleMethodOverride=false
19
+
20
+ PYDANTIC_V1 = pydantic.VERSION.startswith("1.")
21
+
22
+ if TYPE_CHECKING:
23
+
24
+ def parse_date(value: date | StrBytesIntFloat) -> date: # noqa: ARG001
25
+ ...
26
+
27
+ def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime: # noqa: ARG001
28
+ ...
29
+
30
+ def get_args(t: type[Any]) -> tuple[Any, ...]: # noqa: ARG001
31
+ ...
32
+
33
+ def is_union(tp: type[Any] | None) -> bool: # noqa: ARG001
34
+ ...
35
+
36
+ def get_origin(t: type[Any]) -> type[Any] | None: # noqa: ARG001
37
+ ...
38
+
39
+ def is_literal_type(type_: type[Any]) -> bool: # noqa: ARG001
40
+ ...
41
+
42
+ def is_typeddict(type_: type[Any]) -> bool: # noqa: ARG001
43
+ ...
44
+
45
+ else:
46
+ # v1 re-exports
47
+ if PYDANTIC_V1:
48
+ from pydantic.typing import (
49
+ get_args as get_args,
50
+ is_union as is_union,
51
+ get_origin as get_origin,
52
+ is_typeddict as is_typeddict,
53
+ is_literal_type as is_literal_type,
54
+ )
55
+ from pydantic.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime
56
+ else:
57
+ from ._utils import (
58
+ get_args as get_args,
59
+ is_union as is_union,
60
+ get_origin as get_origin,
61
+ parse_date as parse_date,
62
+ is_typeddict as is_typeddict,
63
+ parse_datetime as parse_datetime,
64
+ is_literal_type as is_literal_type,
65
+ )
66
+
67
+
68
+ # refactored config
69
+ if TYPE_CHECKING:
70
+ from pydantic import ConfigDict as ConfigDict
71
+ else:
72
+ if PYDANTIC_V1:
73
+ # TODO: provide an error message here?
74
+ ConfigDict = None
75
+ else:
76
+ from pydantic import ConfigDict as ConfigDict
77
+
78
+
79
+ # renamed methods / properties
80
+ def parse_obj(model: type[_ModelT], value: object) -> _ModelT:
81
+ if PYDANTIC_V1:
82
+ return cast(_ModelT, model.parse_obj(value)) # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
83
+ else:
84
+ return model.model_validate(value)
85
+
86
+
87
+ def field_is_required(field: FieldInfo) -> bool:
88
+ if PYDANTIC_V1:
89
+ return field.required # type: ignore
90
+ return field.is_required()
91
+
92
+
93
+ def field_get_default(field: FieldInfo) -> Any:
94
+ value = field.get_default()
95
+ if PYDANTIC_V1:
96
+ return value
97
+ from pydantic_core import PydanticUndefined
98
+
99
+ if value == PydanticUndefined:
100
+ return None
101
+ return value
102
+
103
+
104
+ def field_outer_type(field: FieldInfo) -> Any:
105
+ if PYDANTIC_V1:
106
+ return field.outer_type_ # type: ignore
107
+ return field.annotation
108
+
109
+
110
+ def get_model_config(model: type[pydantic.BaseModel]) -> Any:
111
+ if PYDANTIC_V1:
112
+ return model.__config__ # type: ignore
113
+ return model.model_config
114
+
115
+
116
+ def get_model_fields(model: type[pydantic.BaseModel]) -> dict[str, FieldInfo]:
117
+ if PYDANTIC_V1:
118
+ return model.__fields__ # type: ignore
119
+ return model.model_fields
120
+
121
+
122
+ def model_copy(model: _ModelT, *, deep: bool = False) -> _ModelT:
123
+ if PYDANTIC_V1:
124
+ return model.copy(deep=deep) # type: ignore
125
+ return model.model_copy(deep=deep)
126
+
127
+
128
+ def model_json(model: pydantic.BaseModel, *, indent: int | None = None) -> str:
129
+ if PYDANTIC_V1:
130
+ return model.json(indent=indent) # type: ignore
131
+ return model.model_dump_json(indent=indent)
132
+
133
+
134
+ def model_parse_json(model: type[_ModelT], data: str | bytes) -> _ModelT:
135
+ if PYDANTIC_V1:
136
+ return model.parse_raw(data) # pyright: ignore[reportDeprecated]
137
+ return model.model_validate_json(data)
138
+
139
+
140
+ class _ModelDumpKwargs(TypedDict, total=False):
141
+ by_alias: bool
142
+
143
+
144
+ def model_dump(
145
+ model: pydantic.BaseModel,
146
+ *,
147
+ exclude: IncEx | None = None,
148
+ exclude_unset: bool = False,
149
+ exclude_defaults: bool = False,
150
+ warnings: bool = True,
151
+ mode: Literal["json", "python"] = "python",
152
+ by_alias: bool | None = None,
153
+ ) -> dict[str, Any]:
154
+ if (not PYDANTIC_V1) or hasattr(model, "model_dump"):
155
+ kwargs: _ModelDumpKwargs = {}
156
+ if by_alias is not None:
157
+ kwargs["by_alias"] = by_alias
158
+ return model.model_dump(
159
+ mode=mode,
160
+ exclude=exclude,
161
+ exclude_unset=exclude_unset,
162
+ exclude_defaults=exclude_defaults,
163
+ # warnings are not supported in Pydantic v1
164
+ warnings=True if PYDANTIC_V1 else warnings,
165
+ **kwargs,
166
+ )
167
+ return cast(
168
+ "dict[str, Any]",
169
+ model.dict( # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
170
+ exclude=exclude, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, by_alias=bool(by_alias)
171
+ ),
172
+ )
173
+
174
+
175
+ def model_parse(model: type[_ModelT], data: Any) -> _ModelT:
176
+ if PYDANTIC_V1:
177
+ return model.parse_obj(data) # pyright: ignore[reportDeprecated]
178
+ return model.model_validate(data)
179
+
180
+
181
+ # generic models
182
+ if TYPE_CHECKING:
183
+
184
+ class GenericModel(pydantic.BaseModel): ...
185
+
186
+ else:
187
+ if PYDANTIC_V1:
188
+ import pydantic.generics
189
+
190
+ class GenericModel(pydantic.generics.GenericModel, pydantic.BaseModel): ...
191
+ else:
192
+ # there no longer needs to be a distinction in v2 but
193
+ # we still have to create our own subclass to avoid
194
+ # inconsistent MRO ordering errors
195
+ class GenericModel(pydantic.BaseModel): ...
196
+
197
+
198
+ # cached properties
199
+ if TYPE_CHECKING:
200
+ cached_property = property
201
+
202
+ # we define a separate type (copied from typeshed)
203
+ # that represents that `cached_property` is `set`able
204
+ # at runtime, which differs from `@property`.
205
+ #
206
+ # this is a separate type as editors likely special case
207
+ # `@property` and we don't want to cause issues just to have
208
+ # more helpful internal types.
209
+
210
+ class typed_cached_property(Generic[_T]):
211
+ func: Callable[[Any], _T]
212
+ attrname: str | None
213
+
214
+ def __init__(self, func: Callable[[Any], _T]) -> None: ...
215
+
216
+ @overload
217
+ def __get__(self, instance: None, owner: type[Any] | None = None) -> Self: ...
218
+
219
+ @overload
220
+ def __get__(self, instance: object, owner: type[Any] | None = None) -> _T: ...
221
+
222
+ def __get__(self, instance: object, owner: type[Any] | None = None) -> _T | Self:
223
+ raise NotImplementedError()
224
+
225
+ def __set_name__(self, owner: type[Any], name: str) -> None: ...
226
+
227
+ # __set__ is not defined at runtime, but @cached_property is designed to be settable
228
+ def __set__(self, instance: object, value: _T) -> None: ...
229
+ else:
230
+ from functools import cached_property as cached_property
231
+
232
+ typed_cached_property = cached_property
data/miniconda3/lib/python3.13/site-packages/anthropic/_constants.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ import httpx
4
+
5
+ RAW_RESPONSE_HEADER = "X-Stainless-Raw-Response"
6
+ OVERRIDE_CAST_TO_HEADER = "____stainless_override_cast_to"
7
+
8
+ # default timeout is 10 minutes
9
+ DEFAULT_TIMEOUT = httpx.Timeout(timeout=10 * 60, connect=5.0)
10
+ DEFAULT_MAX_RETRIES = 2
11
+ DEFAULT_CONNECTION_LIMITS = httpx.Limits(max_connections=1000, max_keepalive_connections=100)
12
+
13
+ INITIAL_RETRY_DELAY = 0.5
14
+ MAX_RETRY_DELAY = 8.0
15
+
16
+ HUMAN_PROMPT = "\n\nHuman:"
17
+
18
+ AI_PROMPT = "\n\nAssistant:"
19
+
20
+ MODEL_NONSTREAMING_TOKENS = {
21
+ "claude-opus-4-20250514": 8_192,
22
+ "claude-opus-4-0": 8_192,
23
+ "claude-4-opus-20250514": 8_192,
24
+ "anthropic.claude-opus-4-20250514-v1:0": 8_192,
25
+ "claude-opus-4@20250514": 8_192,
26
+ "claude-opus-4-1-20250805": 8192,
27
+ "anthropic.claude-opus-4-1-20250805-v1:0": 8192,
28
+ "claude-opus-4-1@20250805": 8192,
29
+ }
data/miniconda3/lib/python3.13/site-packages/anthropic/_exceptions.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Union, cast
6
+ from typing_extensions import Literal
7
+
8
+ import httpx
9
+
10
+ from ._utils import is_dict
11
+ from .types.shared.error_type import ErrorType
12
+
13
+ __all__ = [
14
+ "BadRequestError",
15
+ "AuthenticationError",
16
+ "PermissionDeniedError",
17
+ "NotFoundError",
18
+ "ConflictError",
19
+ "UnprocessableEntityError",
20
+ "RateLimitError",
21
+ "InternalServerError",
22
+ ]
23
+
24
+
25
+ class AnthropicError(Exception):
26
+ pass
27
+
28
+
29
+ class APIError(AnthropicError):
30
+ message: str
31
+ request: httpx.Request
32
+
33
+ body: object | None
34
+ """The API response body.
35
+
36
+ If the API responded with a valid JSON structure then this property will be the
37
+ decoded result.
38
+
39
+ If it isn't a valid JSON structure then this will be the raw response.
40
+
41
+ If there was no response associated with this error then it will be `None`.
42
+ """
43
+
44
+ def __init__(self, message: str, request: httpx.Request, *, body: object | None) -> None: # noqa: ARG002
45
+ super().__init__(message)
46
+ self.request = request
47
+ self.message = message
48
+ self.body = body
49
+
50
+
51
+ class APIResponseValidationError(APIError):
52
+ response: httpx.Response
53
+ status_code: int
54
+
55
+ def __init__(self, response: httpx.Response, body: object | None, *, message: str | None = None) -> None:
56
+ super().__init__(message or "Data returned by API invalid for expected schema.", response.request, body=body)
57
+ self.response = response
58
+ self.status_code = response.status_code
59
+
60
+
61
+ class APIStatusError(APIError):
62
+ """Raised when an API response has a status code of 4xx or 5xx."""
63
+
64
+ response: httpx.Response
65
+ status_code: int
66
+ request_id: str | None
67
+ type: ErrorType | None
68
+
69
+ def __init__(self, message: str, *, response: httpx.Response, body: object | None) -> None:
70
+ super().__init__(message, response.request, body=body)
71
+ self.response = response
72
+ self.status_code = response.status_code
73
+ self.request_id = response.headers.get("request-id")
74
+
75
+ self.type = None
76
+ if is_dict(body):
77
+ error = body.get("error")
78
+ if is_dict(error):
79
+ self.type = cast(Union[ErrorType, None], error.get("type"))
80
+
81
+
82
+ class APIConnectionError(APIError):
83
+ def __init__(self, *, message: str = "Connection error.", request: httpx.Request) -> None:
84
+ super().__init__(message, request, body=None)
85
+
86
+
87
+ class APITimeoutError(APIConnectionError):
88
+ def __init__(self, request: httpx.Request) -> None:
89
+ super().__init__(
90
+ message="Request timed out or interrupted. This could be due to a network timeout, dropped connection, or request cancellation. See https://docs.anthropic.com/en/api/errors#long-requests for more details.",
91
+ request=request,
92
+ )
93
+
94
+
95
+ class BadRequestError(APIStatusError):
96
+ status_code: Literal[400] = 400 # pyright: ignore[reportIncompatibleVariableOverride]
97
+
98
+
99
+ class AuthenticationError(APIStatusError):
100
+ status_code: Literal[401] = 401 # pyright: ignore[reportIncompatibleVariableOverride]
101
+
102
+
103
+ class PermissionDeniedError(APIStatusError):
104
+ status_code: Literal[403] = 403 # pyright: ignore[reportIncompatibleVariableOverride]
105
+
106
+
107
+ class NotFoundError(APIStatusError):
108
+ status_code: Literal[404] = 404 # pyright: ignore[reportIncompatibleVariableOverride]
109
+
110
+
111
+ class ConflictError(APIStatusError):
112
+ status_code: Literal[409] = 409 # pyright: ignore[reportIncompatibleVariableOverride]
113
+
114
+
115
+ class RequestTooLargeError(APIStatusError):
116
+ status_code: Literal[413] = 413 # pyright: ignore[reportIncompatibleVariableOverride]
117
+
118
+
119
+ class UnprocessableEntityError(APIStatusError):
120
+ status_code: Literal[422] = 422 # pyright: ignore[reportIncompatibleVariableOverride]
121
+
122
+
123
+ class RateLimitError(APIStatusError):
124
+ status_code: Literal[429] = 429 # pyright: ignore[reportIncompatibleVariableOverride]
125
+
126
+
127
+ class ServiceUnavailableError(APIStatusError):
128
+ status_code: Literal[503] = 503 # pyright: ignore[reportIncompatibleVariableOverride]
129
+
130
+
131
+ class OverloadedError(APIStatusError):
132
+ status_code: Literal[529] = 529 # pyright: ignore[reportIncompatibleVariableOverride]
133
+
134
+
135
+ class DeadlineExceededError(APIStatusError):
136
+ status_code: Literal[504] = 504 # pyright: ignore[reportIncompatibleVariableOverride]
137
+
138
+
139
+ class InternalServerError(APIStatusError):
140
+ pass
data/miniconda3/lib/python3.13/site-packages/anthropic/_files.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import os
5
+ import pathlib
6
+ from typing import overload
7
+ from typing_extensions import TypeGuard
8
+
9
+ import anyio
10
+
11
+ from ._types import (
12
+ FileTypes,
13
+ FileContent,
14
+ RequestFiles,
15
+ HttpxFileTypes,
16
+ Base64FileInput,
17
+ HttpxFileContent,
18
+ HttpxRequestFiles,
19
+ )
20
+ from ._utils import is_tuple_t, is_mapping_t, is_sequence_t
21
+
22
+
23
+ def is_base64_file_input(obj: object) -> TypeGuard[Base64FileInput]:
24
+ return isinstance(obj, io.IOBase) or isinstance(obj, os.PathLike)
25
+
26
+
27
+ def is_file_content(obj: object) -> TypeGuard[FileContent]:
28
+ return (
29
+ isinstance(obj, bytes) or isinstance(obj, tuple) or isinstance(obj, io.IOBase) or isinstance(obj, os.PathLike)
30
+ )
31
+
32
+
33
+ def assert_is_file_content(obj: object, *, key: str | None = None) -> None:
34
+ if not is_file_content(obj):
35
+ prefix = f"Expected entry at `{key}`" if key is not None else f"Expected file input `{obj!r}`"
36
+ raise RuntimeError(
37
+ f"{prefix} to be bytes, an io.IOBase instance, PathLike or a tuple but received {type(obj)} instead. See https://github.com/anthropics/anthropic-sdk-python/tree/main#file-uploads"
38
+ ) from None
39
+
40
+
41
+ @overload
42
+ def to_httpx_files(files: None) -> None: ...
43
+
44
+
45
+ @overload
46
+ def to_httpx_files(files: RequestFiles) -> HttpxRequestFiles: ...
47
+
48
+
49
+ def to_httpx_files(files: RequestFiles | None) -> HttpxRequestFiles | None:
50
+ if files is None:
51
+ return None
52
+
53
+ if is_mapping_t(files):
54
+ files = {key: _transform_file(file) for key, file in files.items()}
55
+ elif is_sequence_t(files):
56
+ files = [(key, _transform_file(file)) for key, file in files]
57
+ else:
58
+ raise TypeError(f"Unexpected file type input {type(files)}, expected mapping or sequence")
59
+
60
+ return files
61
+
62
+
63
+ def _transform_file(file: FileTypes) -> HttpxFileTypes:
64
+ if is_file_content(file):
65
+ if isinstance(file, os.PathLike):
66
+ path = pathlib.Path(file)
67
+ return (path.name, path.read_bytes())
68
+
69
+ return file
70
+
71
+ if is_tuple_t(file):
72
+ return (file[0], read_file_content(file[1]), *file[2:])
73
+
74
+ raise TypeError(f"Expected file types input to be a FileContent type or to be a tuple")
75
+
76
+
77
+ def read_file_content(file: FileContent) -> HttpxFileContent:
78
+ if isinstance(file, os.PathLike):
79
+ return pathlib.Path(file).read_bytes()
80
+ return file
81
+
82
+
83
+ @overload
84
+ async def async_to_httpx_files(files: None) -> None: ...
85
+
86
+
87
+ @overload
88
+ async def async_to_httpx_files(files: RequestFiles) -> HttpxRequestFiles: ...
89
+
90
+
91
+ async def async_to_httpx_files(files: RequestFiles | None) -> HttpxRequestFiles | None:
92
+ if files is None:
93
+ return None
94
+
95
+ if is_mapping_t(files):
96
+ files = {key: await _async_transform_file(file) for key, file in files.items()}
97
+ elif is_sequence_t(files):
98
+ files = [(key, await _async_transform_file(file)) for key, file in files]
99
+ else:
100
+ raise TypeError("Unexpected file type input {type(files)}, expected mapping or sequence")
101
+
102
+ return files
103
+
104
+
105
+ async def _async_transform_file(file: FileTypes) -> HttpxFileTypes:
106
+ if is_file_content(file):
107
+ if isinstance(file, os.PathLike):
108
+ path = anyio.Path(file)
109
+ return (path.name, await path.read_bytes())
110
+
111
+ return file
112
+
113
+ if is_tuple_t(file):
114
+ return (file[0], await async_read_file_content(file[1]), *file[2:])
115
+
116
+ raise TypeError(f"Expected file types input to be a FileContent type or to be a tuple")
117
+
118
+
119
+ async def async_read_file_content(file: FileContent) -> HttpxFileContent:
120
+ if isinstance(file, os.PathLike):
121
+ return await anyio.Path(file).read_bytes()
122
+
123
+ return file
data/miniconda3/lib/python3.13/site-packages/anthropic/_legacy_response.py ADDED
@@ -0,0 +1,514 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import inspect
5
+ import logging
6
+ import datetime
7
+ import functools
8
+ from typing import (
9
+ TYPE_CHECKING,
10
+ Any,
11
+ Union,
12
+ Generic,
13
+ TypeVar,
14
+ Callable,
15
+ Iterator,
16
+ AsyncIterator,
17
+ cast,
18
+ overload,
19
+ )
20
+ from typing_extensions import Awaitable, ParamSpec, override, deprecated, get_origin
21
+
22
+ import anyio
23
+ import httpx
24
+ import pydantic
25
+
26
+ from ._types import NoneType
27
+ from ._utils import is_given, extract_type_arg, is_annotated_type, is_type_alias_type
28
+ from ._models import BaseModel, is_basemodel, add_request_id
29
+ from ._constants import RAW_RESPONSE_HEADER
30
+ from ._streaming import Stream, AsyncStream, is_stream_class_type, extract_stream_chunk_type
31
+ from ._exceptions import APIResponseValidationError
32
+ from ._decoders.jsonl import JSONLDecoder, AsyncJSONLDecoder
33
+
34
+ if TYPE_CHECKING:
35
+ from ._models import FinalRequestOptions
36
+ from ._base_client import BaseClient
37
+
38
+
39
+ P = ParamSpec("P")
40
+ R = TypeVar("R")
41
+ _T = TypeVar("_T")
42
+ _T_co = TypeVar("_T_co", covariant=True)
43
+
44
+ log: logging.Logger = logging.getLogger(__name__)
45
+
46
+
47
+ class LegacyAPIResponse(Generic[R]):
48
+ """This is a legacy class as it will be replaced by `APIResponse`
49
+ and `AsyncAPIResponse` in the `_response.py` file in the next major
50
+ release.
51
+
52
+ For the sync client this will mostly be the same with the exception
53
+ of `content` & `text` will be methods instead of properties. In the
54
+ async client, all methods will be async.
55
+
56
+ A migration script will be provided & the migration in general should
57
+ be smooth.
58
+ """
59
+
60
+ _cast_to: type[R]
61
+ _client: BaseClient[Any, Any]
62
+ _parsed_by_type: dict[type[Any], Any]
63
+ _stream: bool
64
+ _stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None
65
+ _options: FinalRequestOptions
66
+
67
+ http_response: httpx.Response
68
+
69
+ retries_taken: int
70
+ """The number of retries made. If no retries happened this will be `0`"""
71
+
72
+ def __init__(
73
+ self,
74
+ *,
75
+ raw: httpx.Response,
76
+ cast_to: type[R],
77
+ client: BaseClient[Any, Any],
78
+ stream: bool,
79
+ stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None,
80
+ options: FinalRequestOptions,
81
+ retries_taken: int = 0,
82
+ ) -> None:
83
+ self._cast_to = cast_to
84
+ self._client = client
85
+ self._parsed_by_type = {}
86
+ self._stream = stream
87
+ self._stream_cls = stream_cls
88
+ self._options = options
89
+ self.http_response = raw
90
+ self.retries_taken = retries_taken
91
+
92
+ @property
93
+ def request_id(self) -> str | None:
94
+ return self.http_response.headers.get("request-id") # type: ignore[no-any-return]
95
+
96
+ @overload
97
+ def parse(self, *, to: type[_T]) -> _T: ...
98
+
99
+ @overload
100
+ def parse(self) -> R: ...
101
+
102
+ def parse(self, *, to: type[_T] | None = None) -> R | _T:
103
+ """Returns the rich python representation of this response's data.
104
+
105
+ NOTE: For the async client: this will become a coroutine in the next major version.
106
+
107
+ For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`.
108
+
109
+ You can customise the type that the response is parsed into through
110
+ the `to` argument, e.g.
111
+
112
+ ```py
113
+ from anthropic import BaseModel
114
+
115
+
116
+ class MyModel(BaseModel):
117
+ foo: str
118
+
119
+
120
+ obj = response.parse(to=MyModel)
121
+ print(obj.foo)
122
+ ```
123
+
124
+ We support parsing:
125
+ - `BaseModel`
126
+ - `dict`
127
+ - `list`
128
+ - `Union`
129
+ - `str`
130
+ - `int`
131
+ - `float`
132
+ - `httpx.Response`
133
+ """
134
+ cache_key = to if to is not None else self._cast_to
135
+ cached = self._parsed_by_type.get(cache_key)
136
+ if cached is not None:
137
+ return cached # type: ignore[no-any-return]
138
+
139
+ parsed = self._parse(to=to)
140
+ if is_given(self._options.post_parser):
141
+ parsed = self._options.post_parser(parsed)
142
+
143
+ if isinstance(parsed, BaseModel):
144
+ add_request_id(parsed, self.request_id)
145
+
146
+ self._parsed_by_type[cache_key] = parsed
147
+ return cast(R, parsed)
148
+
149
+ @property
150
+ def headers(self) -> httpx.Headers:
151
+ return self.http_response.headers
152
+
153
+ @property
154
+ def http_request(self) -> httpx.Request:
155
+ return self.http_response.request
156
+
157
+ @property
158
+ def status_code(self) -> int:
159
+ return self.http_response.status_code
160
+
161
+ @property
162
+ def url(self) -> httpx.URL:
163
+ return self.http_response.url
164
+
165
+ @property
166
+ def method(self) -> str:
167
+ return self.http_request.method
168
+
169
+ @property
170
+ def content(self) -> bytes:
171
+ """Return the binary response content.
172
+
173
+ NOTE: this will be removed in favour of `.read()` in the
174
+ next major version.
175
+ """
176
+ return self.http_response.content
177
+
178
+ @property
179
+ def text(self) -> str:
180
+ """Return the decoded response content.
181
+
182
+ NOTE: this will be turned into a method in the next major version.
183
+ """
184
+ return self.http_response.text
185
+
186
+ @property
187
+ def http_version(self) -> str:
188
+ return self.http_response.http_version
189
+
190
+ @property
191
+ def is_closed(self) -> bool:
192
+ return self.http_response.is_closed
193
+
194
+ @property
195
+ def elapsed(self) -> datetime.timedelta:
196
+ """The time taken for the complete request/response cycle to complete."""
197
+ return self.http_response.elapsed
198
+
199
+ def _parse(self, *, to: type[_T] | None = None) -> R | _T:
200
+ cast_to = to if to is not None else self._cast_to
201
+
202
+ # unwrap `TypeAlias('Name', T)` -> `T`
203
+ if is_type_alias_type(cast_to):
204
+ cast_to = cast_to.__value__ # type: ignore[unreachable]
205
+
206
+ # unwrap `Annotated[T, ...]` -> `T`
207
+ if cast_to and is_annotated_type(cast_to):
208
+ cast_to = extract_type_arg(cast_to, 0)
209
+
210
+ origin = get_origin(cast_to) or cast_to
211
+
212
+ if inspect.isclass(origin):
213
+ if issubclass(cast(Any, origin), JSONLDecoder):
214
+ return cast(
215
+ R,
216
+ cast("type[JSONLDecoder[Any]]", cast_to)(
217
+ raw_iterator=self.http_response.iter_bytes(chunk_size=64),
218
+ line_type=extract_type_arg(cast_to, 0),
219
+ http_response=self.http_response,
220
+ ),
221
+ )
222
+
223
+ if issubclass(cast(Any, origin), AsyncJSONLDecoder):
224
+ return cast(
225
+ R,
226
+ cast("type[AsyncJSONLDecoder[Any]]", cast_to)(
227
+ raw_iterator=self.http_response.aiter_bytes(chunk_size=64),
228
+ line_type=extract_type_arg(cast_to, 0),
229
+ http_response=self.http_response,
230
+ ),
231
+ )
232
+
233
+ if self._stream:
234
+ if to:
235
+ if not is_stream_class_type(to):
236
+ raise TypeError(f"Expected custom parse type to be a subclass of {Stream} or {AsyncStream}")
237
+
238
+ return cast(
239
+ _T,
240
+ to(
241
+ cast_to=extract_stream_chunk_type(
242
+ to,
243
+ failure_message="Expected custom stream type to be passed with a type argument, e.g. Stream[ChunkType]",
244
+ ),
245
+ response=self.http_response,
246
+ client=cast(Any, self._client),
247
+ options=self._options,
248
+ ),
249
+ )
250
+
251
+ if self._stream_cls:
252
+ return cast(
253
+ R,
254
+ self._stream_cls(
255
+ cast_to=extract_stream_chunk_type(self._stream_cls),
256
+ response=self.http_response,
257
+ client=cast(Any, self._client),
258
+ options=self._options,
259
+ ),
260
+ )
261
+
262
+ stream_cls = cast("type[Stream[Any]] | type[AsyncStream[Any]] | None", self._client._default_stream_cls)
263
+ if stream_cls is None:
264
+ raise MissingStreamClassError()
265
+
266
+ return cast(
267
+ R,
268
+ stream_cls(
269
+ cast_to=cast_to,
270
+ response=self.http_response,
271
+ client=cast(Any, self._client),
272
+ options=self._options,
273
+ ),
274
+ )
275
+
276
+ if cast_to is NoneType:
277
+ return cast(R, None)
278
+
279
+ response = self.http_response
280
+ if cast_to == str:
281
+ return cast(R, response.text)
282
+
283
+ if cast_to == int:
284
+ return cast(R, int(response.text))
285
+
286
+ if cast_to == float:
287
+ return cast(R, float(response.text))
288
+
289
+ if cast_to == bool:
290
+ return cast(R, response.text.lower() == "true")
291
+
292
+ if inspect.isclass(origin) and issubclass(origin, HttpxBinaryResponseContent):
293
+ return cast(R, cast_to(response)) # type: ignore
294
+
295
+ if origin == LegacyAPIResponse:
296
+ raise RuntimeError("Unexpected state - cast_to is `APIResponse`")
297
+
298
+ if inspect.isclass(
299
+ origin # pyright: ignore[reportUnknownArgumentType]
300
+ ) and issubclass(origin, httpx.Response):
301
+ # Because of the invariance of our ResponseT TypeVar, users can subclass httpx.Response
302
+ # and pass that class to our request functions. We cannot change the variance to be either
303
+ # covariant or contravariant as that makes our usage of ResponseT illegal. We could construct
304
+ # the response class ourselves but that is something that should be supported directly in httpx
305
+ # as it would be easy to incorrectly construct the Response object due to the multitude of arguments.
306
+ if cast_to != httpx.Response:
307
+ raise ValueError(f"Subclasses of httpx.Response cannot be passed to `cast_to`")
308
+ return cast(R, response)
309
+
310
+ if (
311
+ inspect.isclass(
312
+ origin # pyright: ignore[reportUnknownArgumentType]
313
+ )
314
+ and not issubclass(origin, BaseModel)
315
+ and issubclass(origin, pydantic.BaseModel)
316
+ ):
317
+ raise TypeError("Pydantic models must subclass our base model type, e.g. `from anthropic import BaseModel`")
318
+
319
+ if (
320
+ cast_to is not object
321
+ and not origin is list
322
+ and not origin is dict
323
+ and not origin is Union
324
+ and not issubclass(origin, BaseModel)
325
+ ):
326
+ raise RuntimeError(
327
+ f"Unsupported type, expected {cast_to} to be a subclass of {BaseModel}, {dict}, {list}, {Union}, {NoneType}, {str} or {httpx.Response}."
328
+ )
329
+
330
+ # split is required to handle cases where additional information is included
331
+ # in the response, e.g. application/json; charset=utf-8
332
+ content_type, *_ = response.headers.get("content-type", "*").split(";")
333
+ if not content_type.endswith("json"):
334
+ if is_basemodel(cast_to):
335
+ try:
336
+ data = response.json()
337
+ except Exception as exc:
338
+ log.debug("Could not read JSON from response data due to %s - %s", type(exc), exc)
339
+ else:
340
+ return self._client._process_response_data(
341
+ data=data,
342
+ cast_to=cast_to, # type: ignore
343
+ response=response,
344
+ )
345
+
346
+ if self._client._strict_response_validation:
347
+ raise APIResponseValidationError(
348
+ response=response,
349
+ message=f"Expected Content-Type response header to be `application/json` but received `{content_type}` instead.",
350
+ body=response.text,
351
+ )
352
+
353
+ # If the API responds with content that isn't JSON then we just return
354
+ # the (decoded) text without performing any parsing so that you can still
355
+ # handle the response however you need to.
356
+ return response.text # type: ignore
357
+
358
+ data = response.json()
359
+
360
+ return self._client._process_response_data(
361
+ data=data,
362
+ cast_to=cast_to, # type: ignore
363
+ response=response,
364
+ )
365
+
366
+ @override
367
+ def __repr__(self) -> str:
368
+ return f"<APIResponse [{self.status_code} {self.http_response.reason_phrase}] type={self._cast_to}>"
369
+
370
+
371
+ class MissingStreamClassError(TypeError):
372
+ def __init__(self) -> None:
373
+ super().__init__(
374
+ "The `stream` argument was set to `True` but the `stream_cls` argument was not given. See `anthropic._streaming` for reference",
375
+ )
376
+
377
+
378
+ def to_raw_response_wrapper(func: Callable[P, R]) -> Callable[P, LegacyAPIResponse[R]]:
379
+ """Higher order function that takes one of our bound API methods and wraps it
380
+ to support returning the raw `APIResponse` object directly.
381
+ """
382
+
383
+ @functools.wraps(func)
384
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> LegacyAPIResponse[R]:
385
+ extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
386
+ extra_headers[RAW_RESPONSE_HEADER] = "true"
387
+
388
+ kwargs["extra_headers"] = extra_headers
389
+
390
+ return cast(LegacyAPIResponse[R], func(*args, **kwargs))
391
+
392
+ return wrapped
393
+
394
+
395
+ def async_to_raw_response_wrapper(func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[LegacyAPIResponse[R]]]:
396
+ """Higher order function that takes one of our bound API methods and wraps it
397
+ to support returning the raw `APIResponse` object directly.
398
+ """
399
+
400
+ @functools.wraps(func)
401
+ async def wrapped(*args: P.args, **kwargs: P.kwargs) -> LegacyAPIResponse[R]:
402
+ extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
403
+ extra_headers[RAW_RESPONSE_HEADER] = "true"
404
+
405
+ kwargs["extra_headers"] = extra_headers
406
+
407
+ return cast(LegacyAPIResponse[R], await func(*args, **kwargs))
408
+
409
+ return wrapped
410
+
411
+
412
+ class HttpxBinaryResponseContent:
413
+ response: httpx.Response
414
+
415
+ def __init__(self, response: httpx.Response) -> None:
416
+ self.response = response
417
+
418
+ @property
419
+ def content(self) -> bytes:
420
+ return self.response.content
421
+
422
+ @property
423
+ def text(self) -> str:
424
+ return self.response.text
425
+
426
+ @property
427
+ def encoding(self) -> str | None:
428
+ return self.response.encoding
429
+
430
+ @property
431
+ def charset_encoding(self) -> str | None:
432
+ return self.response.charset_encoding
433
+
434
+ def json(self, **kwargs: Any) -> Any:
435
+ return self.response.json(**kwargs)
436
+
437
+ def read(self) -> bytes:
438
+ return self.response.read()
439
+
440
+ def iter_bytes(self, chunk_size: int | None = None) -> Iterator[bytes]:
441
+ return self.response.iter_bytes(chunk_size)
442
+
443
+ def iter_text(self, chunk_size: int | None = None) -> Iterator[str]:
444
+ return self.response.iter_text(chunk_size)
445
+
446
+ def iter_lines(self) -> Iterator[str]:
447
+ return self.response.iter_lines()
448
+
449
+ def iter_raw(self, chunk_size: int | None = None) -> Iterator[bytes]:
450
+ return self.response.iter_raw(chunk_size)
451
+
452
+ def write_to_file(
453
+ self,
454
+ file: str | os.PathLike[str],
455
+ ) -> None:
456
+ """Write the output to the given file.
457
+
458
+ Accepts a filename or any path-like object, e.g. pathlib.Path
459
+
460
+ Note: if you want to stream the data to the file instead of writing
461
+ all at once then you should use `.with_streaming_response` when making
462
+ the API request, e.g. `client.with_streaming_response.foo().stream_to_file('my_filename.txt')`
463
+ """
464
+ with open(file, mode="wb") as f:
465
+ for data in self.response.iter_bytes():
466
+ f.write(data)
467
+
468
+ @deprecated(
469
+ "Due to a bug, this method doesn't actually stream the response content, `.with_streaming_response.method()` should be used instead"
470
+ )
471
+ def stream_to_file(
472
+ self,
473
+ file: str | os.PathLike[str],
474
+ *,
475
+ chunk_size: int | None = None,
476
+ ) -> None:
477
+ with open(file, mode="wb") as f:
478
+ for data in self.response.iter_bytes(chunk_size):
479
+ f.write(data)
480
+
481
+ def close(self) -> None:
482
+ return self.response.close()
483
+
484
+ async def aread(self) -> bytes:
485
+ return await self.response.aread()
486
+
487
+ async def aiter_bytes(self, chunk_size: int | None = None) -> AsyncIterator[bytes]:
488
+ return self.response.aiter_bytes(chunk_size)
489
+
490
+ async def aiter_text(self, chunk_size: int | None = None) -> AsyncIterator[str]:
491
+ return self.response.aiter_text(chunk_size)
492
+
493
+ async def aiter_lines(self) -> AsyncIterator[str]:
494
+ return self.response.aiter_lines()
495
+
496
+ async def aiter_raw(self, chunk_size: int | None = None) -> AsyncIterator[bytes]:
497
+ return self.response.aiter_raw(chunk_size)
498
+
499
+ @deprecated(
500
+ "Due to a bug, this method doesn't actually stream the response content, `.with_streaming_response.method()` should be used instead"
501
+ )
502
+ async def astream_to_file(
503
+ self,
504
+ file: str | os.PathLike[str],
505
+ *,
506
+ chunk_size: int | None = None,
507
+ ) -> None:
508
+ path = anyio.Path(file)
509
+ async with await path.open(mode="wb") as f:
510
+ async for data in self.response.aiter_bytes(chunk_size):
511
+ await f.write(data)
512
+
513
+ async def aclose(self) -> None:
514
+ return await self.response.aclose()
data/miniconda3/lib/python3.13/site-packages/anthropic/_models.py ADDED
@@ -0,0 +1,918 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import inspect
5
+ import weakref
6
+ from typing import (
7
+ IO,
8
+ TYPE_CHECKING,
9
+ Any,
10
+ Type,
11
+ Union,
12
+ Generic,
13
+ TypeVar,
14
+ Callable,
15
+ Iterable,
16
+ Optional,
17
+ AsyncIterable,
18
+ cast,
19
+ )
20
+ from datetime import date, datetime
21
+ from typing_extensions import (
22
+ List,
23
+ Unpack,
24
+ Literal,
25
+ ClassVar,
26
+ Protocol,
27
+ Required,
28
+ ParamSpec,
29
+ TypedDict,
30
+ TypeGuard,
31
+ final,
32
+ override,
33
+ runtime_checkable,
34
+ )
35
+
36
+ import pydantic
37
+ from pydantic.fields import FieldInfo
38
+
39
+ from ._types import (
40
+ Body,
41
+ IncEx,
42
+ Query,
43
+ ModelT,
44
+ Headers,
45
+ Timeout,
46
+ NotGiven,
47
+ AnyMapping,
48
+ HttpxRequestFiles,
49
+ )
50
+ from ._utils import (
51
+ PropertyInfo,
52
+ is_list,
53
+ is_given,
54
+ json_safe,
55
+ lru_cache,
56
+ is_mapping,
57
+ parse_date,
58
+ coerce_boolean,
59
+ parse_datetime,
60
+ strip_not_given,
61
+ extract_type_arg,
62
+ is_annotated_type,
63
+ is_type_alias_type,
64
+ strip_annotated_type,
65
+ )
66
+ from ._compat import (
67
+ PYDANTIC_V1,
68
+ ConfigDict,
69
+ GenericModel as BaseGenericModel,
70
+ get_args,
71
+ is_union,
72
+ parse_obj,
73
+ get_origin,
74
+ is_literal_type,
75
+ get_model_config,
76
+ get_model_fields,
77
+ field_get_default,
78
+ )
79
+ from ._constants import RAW_RESPONSE_HEADER
80
+
81
+ if TYPE_CHECKING:
82
+ from pydantic_core.core_schema import ModelField, ModelSchema, LiteralSchema, ModelFieldsSchema
83
+
84
+ __all__ = ["BaseModel", "GenericModel"]
85
+
86
+ _T = TypeVar("_T")
87
+ _BaseModelT = TypeVar("_BaseModelT", bound="BaseModel")
88
+
89
+ P = ParamSpec("P")
90
+
91
+
92
+ @runtime_checkable
93
+ class _ConfigProtocol(Protocol):
94
+ allow_population_by_field_name: bool
95
+
96
+
97
+ class BaseModel(pydantic.BaseModel):
98
+ if PYDANTIC_V1:
99
+
100
+ @property
101
+ @override
102
+ def model_fields_set(self) -> set[str]:
103
+ # a forwards-compat shim for pydantic v2
104
+ return self.__fields_set__ # type: ignore
105
+
106
+ class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated]
107
+ extra: Any = pydantic.Extra.allow # type: ignore
108
+ else:
109
+ model_config: ClassVar[ConfigDict] = ConfigDict(
110
+ extra="allow", defer_build=coerce_boolean(os.environ.get("DEFER_PYDANTIC_BUILD", "true"))
111
+ )
112
+
113
+ if TYPE_CHECKING:
114
+ _request_id: Optional[str] = None
115
+ """The ID of the request, returned via the `request-id` header. Useful for debugging requests and reporting issues to Anthropic.
116
+ This will **only** be set for the top-level response object, it will not be defined for nested objects. For example:
117
+
118
+ ```py
119
+ message = await client.messages.create(...)
120
+ message._request_id # req_xxx
121
+ message.usage._request_id # raises `AttributeError`
122
+ ```
123
+
124
+ Note: unlike other properties that use an `_` prefix, this property
125
+ *is* public. Unless documented otherwise, all other `_` prefix properties,
126
+ methods and modules are *private*.
127
+ """
128
+
129
+ def to_dict(
130
+ self,
131
+ *,
132
+ mode: Literal["json", "python"] = "python",
133
+ use_api_names: bool = True,
134
+ exclude_unset: bool = True,
135
+ exclude_defaults: bool = False,
136
+ exclude_none: bool = False,
137
+ warnings: bool = True,
138
+ ) -> dict[str, object]:
139
+ """Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
140
+
141
+ By default, fields that were not set by the API will not be included,
142
+ and keys will match the API response, *not* the property names from the model.
143
+
144
+ For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
145
+ the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
146
+
147
+ Args:
148
+ mode:
149
+ If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
150
+ If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
151
+
152
+ use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
153
+ exclude_unset: Whether to exclude fields that have not been explicitly set.
154
+ exclude_defaults: Whether to exclude fields that are set to their default value from the output.
155
+ exclude_none: Whether to exclude fields that have a value of `None` from the output.
156
+ warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
157
+ """
158
+ return self.model_dump(
159
+ mode=mode,
160
+ by_alias=use_api_names,
161
+ exclude_unset=exclude_unset,
162
+ exclude_defaults=exclude_defaults,
163
+ exclude_none=exclude_none,
164
+ warnings=warnings,
165
+ )
166
+
167
+ def to_json(
168
+ self,
169
+ *,
170
+ indent: int | None = 2,
171
+ use_api_names: bool = True,
172
+ exclude_unset: bool = True,
173
+ exclude_defaults: bool = False,
174
+ exclude_none: bool = False,
175
+ warnings: bool = True,
176
+ ) -> str:
177
+ """Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
178
+
179
+ By default, fields that were not set by the API will not be included,
180
+ and keys will match the API response, *not* the property names from the model.
181
+
182
+ For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
183
+ the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
184
+
185
+ Args:
186
+ indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
187
+ use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
188
+ exclude_unset: Whether to exclude fields that have not been explicitly set.
189
+ exclude_defaults: Whether to exclude fields that have the default value.
190
+ exclude_none: Whether to exclude fields that have a value of `None`.
191
+ warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
192
+ """
193
+ return self.model_dump_json(
194
+ indent=indent,
195
+ by_alias=use_api_names,
196
+ exclude_unset=exclude_unset,
197
+ exclude_defaults=exclude_defaults,
198
+ exclude_none=exclude_none,
199
+ warnings=warnings,
200
+ )
201
+
202
+ @override
203
+ def __str__(self) -> str:
204
+ # mypy complains about an invalid self arg
205
+ return f"{self.__repr_name__()}({self.__repr_str__(', ')})" # type: ignore[misc]
206
+
207
+ # Override the 'construct' method in a way that supports recursive parsing without validation.
208
+ # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
209
+ @classmethod
210
+ @override
211
+ def construct( # pyright: ignore[reportIncompatibleMethodOverride]
212
+ __cls: Type[ModelT],
213
+ _fields_set: set[str] | None = None,
214
+ **values: object,
215
+ ) -> ModelT:
216
+ m = __cls.__new__(__cls)
217
+ fields_values: dict[str, object] = {}
218
+
219
+ config = get_model_config(__cls)
220
+ populate_by_name = (
221
+ config.allow_population_by_field_name
222
+ if isinstance(config, _ConfigProtocol)
223
+ else config.get("populate_by_name")
224
+ )
225
+
226
+ if _fields_set is None:
227
+ _fields_set = set()
228
+
229
+ model_fields = get_model_fields(__cls)
230
+ for name, field in model_fields.items():
231
+ key = field.alias
232
+ if key is None or (key not in values and populate_by_name):
233
+ key = name
234
+
235
+ if key in values:
236
+ fields_values[name] = _construct_field(value=values[key], field=field, key=key)
237
+ _fields_set.add(name)
238
+ else:
239
+ fields_values[name] = field_get_default(field)
240
+
241
+ extra_field_type = _get_extra_fields_type(__cls)
242
+
243
+ _extra = {}
244
+ for key, value in values.items():
245
+ if key not in model_fields:
246
+ parsed = construct_type(value=value, type_=extra_field_type) if extra_field_type is not None else value
247
+
248
+ if PYDANTIC_V1:
249
+ _fields_set.add(key)
250
+ fields_values[key] = parsed
251
+ else:
252
+ _extra[key] = parsed
253
+
254
+ object.__setattr__(m, "__dict__", fields_values)
255
+
256
+ if PYDANTIC_V1:
257
+ # init_private_attributes() does not exist in v2
258
+ m._init_private_attributes() # type: ignore
259
+
260
+ # copied from Pydantic v1's `construct()` method
261
+ object.__setattr__(m, "__fields_set__", _fields_set)
262
+ else:
263
+ # these properties are copied from Pydantic's `model_construct()` method
264
+ object.__setattr__(m, "__pydantic_private__", None)
265
+ object.__setattr__(m, "__pydantic_extra__", _extra)
266
+ object.__setattr__(m, "__pydantic_fields_set__", _fields_set)
267
+
268
+ return m
269
+
270
+ if not TYPE_CHECKING:
271
+ # type checkers incorrectly complain about this assignment
272
+ # because the type signatures are technically different
273
+ # although not in practice
274
+ model_construct = construct
275
+
276
+ if PYDANTIC_V1:
277
+ # we define aliases for some of the new pydantic v2 methods so
278
+ # that we can just document these methods without having to specify
279
+ # a specific pydantic version as some users may not know which
280
+ # pydantic version they are currently using
281
+
282
+ @override
283
+ def model_dump(
284
+ self,
285
+ *,
286
+ mode: Literal["json", "python"] | str = "python",
287
+ include: IncEx | None = None,
288
+ exclude: IncEx | None = None,
289
+ context: Any | None = None,
290
+ by_alias: bool | None = None,
291
+ exclude_unset: bool = False,
292
+ exclude_defaults: bool = False,
293
+ exclude_none: bool = False,
294
+ exclude_computed_fields: bool = False,
295
+ round_trip: bool = False,
296
+ warnings: bool | Literal["none", "warn", "error"] = True,
297
+ fallback: Callable[[Any], Any] | None = None,
298
+ serialize_as_any: bool = False,
299
+ ) -> dict[str, Any]:
300
+ """Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump
301
+
302
+ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
303
+
304
+ Args:
305
+ mode: The mode in which `to_python` should run.
306
+ If mode is 'json', the output will only contain JSON serializable types.
307
+ If mode is 'python', the output may contain non-JSON-serializable Python objects.
308
+ include: A set of fields to include in the output.
309
+ exclude: A set of fields to exclude from the output.
310
+ context: Additional context to pass to the serializer.
311
+ by_alias: Whether to use the field's alias in the dictionary key if defined.
312
+ exclude_unset: Whether to exclude fields that have not been explicitly set.
313
+ exclude_defaults: Whether to exclude fields that are set to their default value.
314
+ exclude_none: Whether to exclude fields that have a value of `None`.
315
+ exclude_computed_fields: Whether to exclude computed fields.
316
+ While this can be useful for round-tripping, it is usually recommended to use the dedicated
317
+ `round_trip` parameter instead.
318
+ round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
319
+ warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
320
+ "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
321
+ fallback: A function to call when an unknown value is encountered. If not provided,
322
+ a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
323
+ serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
324
+
325
+ Returns:
326
+ A dictionary representation of the model.
327
+ """
328
+ if mode not in {"json", "python"}:
329
+ raise ValueError("mode must be either 'json' or 'python'")
330
+ if round_trip != False:
331
+ raise ValueError("round_trip is only supported in Pydantic v2")
332
+ if warnings != True:
333
+ raise ValueError("warnings is only supported in Pydantic v2")
334
+ if context is not None:
335
+ raise ValueError("context is only supported in Pydantic v2")
336
+ if serialize_as_any != False:
337
+ raise ValueError("serialize_as_any is only supported in Pydantic v2")
338
+ if fallback is not None:
339
+ raise ValueError("fallback is only supported in Pydantic v2")
340
+ if exclude_computed_fields != False:
341
+ raise ValueError("exclude_computed_fields is only supported in Pydantic v2")
342
+ dumped = super().dict( # pyright: ignore[reportDeprecated]
343
+ include=include,
344
+ exclude=exclude,
345
+ by_alias=by_alias if by_alias is not None else False,
346
+ exclude_unset=exclude_unset,
347
+ exclude_defaults=exclude_defaults,
348
+ exclude_none=exclude_none,
349
+ )
350
+
351
+ return cast("dict[str, Any]", json_safe(dumped)) if mode == "json" else dumped
352
+
353
+ @override
354
+ def model_dump_json(
355
+ self,
356
+ *,
357
+ indent: int | None = None,
358
+ ensure_ascii: bool = False,
359
+ include: IncEx | None = None,
360
+ exclude: IncEx | None = None,
361
+ context: Any | None = None,
362
+ by_alias: bool | None = None,
363
+ exclude_unset: bool = False,
364
+ exclude_defaults: bool = False,
365
+ exclude_none: bool = False,
366
+ exclude_computed_fields: bool = False,
367
+ round_trip: bool = False,
368
+ warnings: bool | Literal["none", "warn", "error"] = True,
369
+ fallback: Callable[[Any], Any] | None = None,
370
+ serialize_as_any: bool = False,
371
+ ) -> str:
372
+ """Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump_json
373
+
374
+ Generates a JSON representation of the model using Pydantic's `to_json` method.
375
+
376
+ Args:
377
+ indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
378
+ include: Field(s) to include in the JSON output. Can take either a string or set of strings.
379
+ exclude: Field(s) to exclude from the JSON output. Can take either a string or set of strings.
380
+ by_alias: Whether to serialize using field aliases.
381
+ exclude_unset: Whether to exclude fields that have not been explicitly set.
382
+ exclude_defaults: Whether to exclude fields that have the default value.
383
+ exclude_none: Whether to exclude fields that have a value of `None`.
384
+ round_trip: Whether to use serialization/deserialization between JSON and class instance.
385
+ warnings: Whether to show any warnings that occurred during serialization.
386
+
387
+ Returns:
388
+ A JSON string representation of the model.
389
+ """
390
+ if round_trip != False:
391
+ raise ValueError("round_trip is only supported in Pydantic v2")
392
+ if warnings != True:
393
+ raise ValueError("warnings is only supported in Pydantic v2")
394
+ if context is not None:
395
+ raise ValueError("context is only supported in Pydantic v2")
396
+ if serialize_as_any != False:
397
+ raise ValueError("serialize_as_any is only supported in Pydantic v2")
398
+ if fallback is not None:
399
+ raise ValueError("fallback is only supported in Pydantic v2")
400
+ if ensure_ascii != False:
401
+ raise ValueError("ensure_ascii is only supported in Pydantic v2")
402
+ if exclude_computed_fields != False:
403
+ raise ValueError("exclude_computed_fields is only supported in Pydantic v2")
404
+ return super().json( # type: ignore[reportDeprecated]
405
+ indent=indent,
406
+ include=include,
407
+ exclude=exclude,
408
+ by_alias=by_alias if by_alias is not None else False,
409
+ exclude_unset=exclude_unset,
410
+ exclude_defaults=exclude_defaults,
411
+ exclude_none=exclude_none,
412
+ )
413
+
414
+
415
+ def _construct_field(value: object, field: FieldInfo, key: str) -> object:
416
+ if value is None:
417
+ return field_get_default(field)
418
+
419
+ if PYDANTIC_V1:
420
+ type_ = cast(type, field.outer_type_) # type: ignore
421
+ else:
422
+ type_ = field.annotation # type: ignore
423
+
424
+ if type_ is None:
425
+ raise RuntimeError(f"Unexpected field type is None for {key}")
426
+
427
+ return construct_type(value=value, type_=type_, metadata=getattr(field, "metadata", None))
428
+
429
+
430
+ def _get_extra_fields_type(cls: type[pydantic.BaseModel]) -> type | None:
431
+ if PYDANTIC_V1:
432
+ # TODO
433
+ return None
434
+
435
+ schema = cls.__pydantic_core_schema__
436
+ if schema["type"] == "model":
437
+ fields = schema["schema"]
438
+ if fields["type"] == "model-fields":
439
+ extras = fields.get("extras_schema")
440
+ if extras and "cls" in extras:
441
+ # mypy can't narrow the type
442
+ return extras["cls"] # type: ignore[no-any-return]
443
+
444
+ return None
445
+
446
+
447
+ def is_basemodel(type_: type) -> bool:
448
+ """Returns whether or not the given type is either a `BaseModel` or a union of `BaseModel`"""
449
+ if is_union(type_):
450
+ for variant in get_args(type_):
451
+ if is_basemodel(variant):
452
+ return True
453
+
454
+ return False
455
+
456
+ return is_basemodel_type(type_)
457
+
458
+
459
+ def is_basemodel_type(type_: type) -> TypeGuard[type[BaseModel] | type[GenericModel]]:
460
+ origin = get_origin(type_) or type_
461
+ if not inspect.isclass(origin):
462
+ return False
463
+ return issubclass(origin, BaseModel) or issubclass(origin, GenericModel)
464
+
465
+
466
+ def build(
467
+ base_model_cls: Callable[P, _BaseModelT],
468
+ *args: P.args,
469
+ **kwargs: P.kwargs,
470
+ ) -> _BaseModelT:
471
+ """Construct a BaseModel class without validation.
472
+
473
+ This is useful for cases where you need to instantiate a `BaseModel`
474
+ from an API response as this provides type-safe params which isn't supported
475
+ by helpers like `construct_type()`.
476
+
477
+ ```py
478
+ build(MyModel, my_field_a="foo", my_field_b=123)
479
+ ```
480
+ """
481
+ if args:
482
+ raise TypeError(
483
+ "Received positional arguments which are not supported; Keyword arguments must be used instead",
484
+ )
485
+
486
+ return cast(_BaseModelT, construct_type(type_=base_model_cls, value=kwargs))
487
+
488
+
489
+ def construct_type_unchecked(*, value: object, type_: type[_T]) -> _T:
490
+ """Loose coercion to the expected type with construction of nested values.
491
+
492
+ Note: the returned value from this function is not guaranteed to match the
493
+ given type.
494
+ """
495
+ return cast(_T, construct_type(value=value, type_=type_))
496
+
497
+
498
+ def construct_type(*, value: object, type_: object, metadata: Optional[List[Any]] = None) -> object:
499
+ """Loose coercion to the expected type with construction of nested values.
500
+
501
+ If the given value does not match the expected type then it is returned as-is.
502
+ """
503
+
504
+ # store a reference to the original type we were given before we extract any inner
505
+ # types so that we can properly resolve forward references in `TypeAliasType` annotations
506
+ original_type = None
507
+
508
+ # we allow `object` as the input type because otherwise, passing things like
509
+ # `Literal['value']` will be reported as a type error by type checkers
510
+ type_ = cast("type[object]", type_)
511
+ if is_type_alias_type(type_):
512
+ original_type = type_ # type: ignore[unreachable]
513
+ type_ = type_.__value__ # type: ignore[unreachable]
514
+
515
+ # unwrap `Annotated[T, ...]` -> `T`
516
+ if metadata is not None and len(metadata) > 0:
517
+ meta: tuple[Any, ...] = tuple(metadata)
518
+ elif is_annotated_type(type_):
519
+ meta = get_args(type_)[1:]
520
+ type_ = extract_type_arg(type_, 0)
521
+ else:
522
+ meta = tuple()
523
+
524
+ # we need to use the origin class for any types that are subscripted generics
525
+ # e.g. Dict[str, object]
526
+ origin = get_origin(type_) or type_
527
+ args = get_args(type_)
528
+
529
+ if is_union(origin):
530
+ try:
531
+ return validate_type(type_=cast("type[object]", original_type or type_), value=value)
532
+ except Exception:
533
+ pass
534
+
535
+ # if the type is a discriminated union then we want to construct the right variant
536
+ # in the union, even if the data doesn't match exactly, otherwise we'd break code
537
+ # that relies on the constructed class types, e.g.
538
+ #
539
+ # class FooType:
540
+ # kind: Literal['foo']
541
+ # value: str
542
+ #
543
+ # class BarType:
544
+ # kind: Literal['bar']
545
+ # value: int
546
+ #
547
+ # without this block, if the data we get is something like `{'kind': 'bar', 'value': 'foo'}` then
548
+ # we'd end up constructing `FooType` when it should be `BarType`.
549
+ discriminator = _build_discriminated_union_meta(union=type_, meta_annotations=meta)
550
+ if discriminator and is_mapping(value):
551
+ variant_value = value.get(discriminator.field_alias_from or discriminator.field_name)
552
+ if variant_value and isinstance(variant_value, str):
553
+ variant_type = discriminator.mapping.get(variant_value)
554
+ if variant_type:
555
+ return construct_type(type_=variant_type, value=value)
556
+
557
+ # if the data is not valid, use the first variant that doesn't fail while deserializing
558
+ for variant in args:
559
+ try:
560
+ return construct_type(value=value, type_=variant)
561
+ except Exception:
562
+ continue
563
+
564
+ raise RuntimeError(f"Could not convert data into a valid instance of {type_}")
565
+
566
+ if origin == dict:
567
+ if not is_mapping(value):
568
+ return value
569
+
570
+ _, items_type = get_args(type_) # Dict[_, items_type]
571
+ return {key: construct_type(value=item, type_=items_type) for key, item in value.items()}
572
+
573
+ if (
574
+ not is_literal_type(type_)
575
+ and inspect.isclass(origin)
576
+ and (issubclass(origin, BaseModel) or issubclass(origin, GenericModel))
577
+ ):
578
+ if is_list(value):
579
+ return [cast(Any, type_).construct(**entry) if is_mapping(entry) else entry for entry in value]
580
+
581
+ if is_mapping(value):
582
+ if issubclass(type_, BaseModel):
583
+ return type_.construct(**value) # type: ignore[arg-type]
584
+
585
+ return cast(Any, type_).construct(**value)
586
+
587
+ if origin == list:
588
+ if not is_list(value):
589
+ return value
590
+
591
+ inner_type = args[0] # List[inner_type]
592
+ return [construct_type(value=entry, type_=inner_type) for entry in value]
593
+
594
+ if origin == float:
595
+ if isinstance(value, int):
596
+ coerced = float(value)
597
+ if coerced != value:
598
+ return value
599
+ return coerced
600
+
601
+ return value
602
+
603
+ if type_ == datetime:
604
+ try:
605
+ return parse_datetime(value) # type: ignore
606
+ except Exception:
607
+ return value
608
+
609
+ if type_ == date:
610
+ try:
611
+ return parse_date(value) # type: ignore
612
+ except Exception:
613
+ return value
614
+
615
+ return value
616
+
617
+
618
+ @runtime_checkable
619
+ class CachedDiscriminatorType(Protocol):
620
+ __discriminator__: DiscriminatorDetails
621
+
622
+
623
+ DISCRIMINATOR_CACHE: weakref.WeakKeyDictionary[type, DiscriminatorDetails] = weakref.WeakKeyDictionary()
624
+
625
+
626
+ class DiscriminatorDetails:
627
+ field_name: str
628
+ """The name of the discriminator field in the variant class, e.g.
629
+
630
+ ```py
631
+ class Foo(BaseModel):
632
+ type: Literal['foo']
633
+ ```
634
+
635
+ Will result in field_name='type'
636
+ """
637
+
638
+ field_alias_from: str | None
639
+ """The name of the discriminator field in the API response, e.g.
640
+
641
+ ```py
642
+ class Foo(BaseModel):
643
+ type: Literal['foo'] = Field(alias='type_from_api')
644
+ ```
645
+
646
+ Will result in field_alias_from='type_from_api'
647
+ """
648
+
649
+ mapping: dict[str, type]
650
+ """Mapping of discriminator value to variant type, e.g.
651
+
652
+ {'foo': FooVariant, 'bar': BarVariant}
653
+ """
654
+
655
+ def __init__(
656
+ self,
657
+ *,
658
+ mapping: dict[str, type],
659
+ discriminator_field: str,
660
+ discriminator_alias: str | None,
661
+ ) -> None:
662
+ self.mapping = mapping
663
+ self.field_name = discriminator_field
664
+ self.field_alias_from = discriminator_alias
665
+
666
+
667
+ def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any, ...]) -> DiscriminatorDetails | None:
668
+ cached = DISCRIMINATOR_CACHE.get(union)
669
+ if cached is not None:
670
+ return cached
671
+
672
+ discriminator_field_name: str | None = None
673
+
674
+ for annotation in meta_annotations:
675
+ if isinstance(annotation, PropertyInfo) and annotation.discriminator is not None:
676
+ discriminator_field_name = annotation.discriminator
677
+ break
678
+
679
+ if not discriminator_field_name:
680
+ return None
681
+
682
+ mapping: dict[str, type] = {}
683
+ discriminator_alias: str | None = None
684
+
685
+ for variant in get_args(union):
686
+ variant = strip_annotated_type(variant)
687
+ if is_basemodel_type(variant):
688
+ if PYDANTIC_V1:
689
+ field_info = cast("dict[str, FieldInfo]", variant.__fields__).get(discriminator_field_name) # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
690
+ if not field_info:
691
+ continue
692
+
693
+ # Note: if one variant defines an alias then they all should
694
+ discriminator_alias = field_info.alias
695
+
696
+ if (annotation := getattr(field_info, "annotation", None)) and is_literal_type(annotation):
697
+ for entry in get_args(annotation):
698
+ if isinstance(entry, str):
699
+ mapping[entry] = variant
700
+ else:
701
+ field = _extract_field_schema_pv2(variant, discriminator_field_name)
702
+ if not field:
703
+ continue
704
+
705
+ # Note: if one variant defines an alias then they all should
706
+ discriminator_alias = field.get("serialization_alias")
707
+
708
+ field_schema = field["schema"]
709
+
710
+ if field_schema["type"] == "literal":
711
+ for entry in cast("LiteralSchema", field_schema)["expected"]:
712
+ if isinstance(entry, str):
713
+ mapping[entry] = variant
714
+
715
+ if not mapping:
716
+ return None
717
+
718
+ details = DiscriminatorDetails(
719
+ mapping=mapping,
720
+ discriminator_field=discriminator_field_name,
721
+ discriminator_alias=discriminator_alias,
722
+ )
723
+ DISCRIMINATOR_CACHE.setdefault(union, details)
724
+ return details
725
+
726
+
727
+ def _extract_field_schema_pv2(model: type[BaseModel], field_name: str) -> ModelField | None:
728
+ schema = model.__pydantic_core_schema__
729
+ if schema["type"] == "definitions":
730
+ schema = schema["schema"]
731
+
732
+ if schema["type"] != "model":
733
+ return None
734
+
735
+ schema = cast("ModelSchema", schema)
736
+ fields_schema = schema["schema"]
737
+ if fields_schema["type"] != "model-fields":
738
+ return None
739
+
740
+ fields_schema = cast("ModelFieldsSchema", fields_schema)
741
+ field = fields_schema["fields"].get(field_name)
742
+ if not field:
743
+ return None
744
+
745
+ return cast("ModelField", field) # pyright: ignore[reportUnnecessaryCast]
746
+
747
+
748
+ def validate_type(*, type_: type[_T], value: object) -> _T:
749
+ """Strict validation that the given value matches the expected type"""
750
+ if inspect.isclass(type_) and issubclass(type_, pydantic.BaseModel):
751
+ return cast(_T, parse_obj(type_, value))
752
+
753
+ return cast(_T, _validate_non_model_type(type_=type_, value=value))
754
+
755
+
756
+ def set_pydantic_config(typ: Any, config: pydantic.ConfigDict) -> None:
757
+ """Add a pydantic config for the given type.
758
+
759
+ Note: this is a no-op on Pydantic v1.
760
+ """
761
+ setattr(typ, "__pydantic_config__", config) # noqa: B010
762
+
763
+
764
+ def add_request_id(obj: BaseModel, request_id: str | None) -> None:
765
+ obj._request_id = request_id
766
+
767
+ # in Pydantic v1, using setattr like we do above causes the attribute
768
+ # to be included when serializing the model which we don't want in this
769
+ # case so we need to explicitly exclude it
770
+ if PYDANTIC_V1:
771
+ try:
772
+ exclude_fields = obj.__exclude_fields__ # type: ignore
773
+ except AttributeError:
774
+ cast(Any, obj).__exclude_fields__ = {"_request_id", "__exclude_fields__"}
775
+ else:
776
+ cast(Any, obj).__exclude_fields__ = {*(exclude_fields or {}), "_request_id", "__exclude_fields__"}
777
+
778
+
779
+ # our use of subclassing here causes weirdness for type checkers,
780
+ # so we just pretend that we don't subclass
781
+ if TYPE_CHECKING:
782
+ GenericModel = BaseModel
783
+ else:
784
+
785
+ class GenericModel(BaseGenericModel, BaseModel):
786
+ pass
787
+
788
+
789
+ if not PYDANTIC_V1:
790
+ from pydantic import TypeAdapter as _TypeAdapter, computed_field as computed_field
791
+
792
+ _CachedTypeAdapter = cast("TypeAdapter[object]", lru_cache(maxsize=None)(_TypeAdapter))
793
+
794
+ if TYPE_CHECKING:
795
+ from pydantic import TypeAdapter
796
+ else:
797
+ TypeAdapter = _CachedTypeAdapter
798
+
799
+ def _validate_non_model_type(*, type_: type[_T], value: object) -> _T:
800
+ return TypeAdapter(type_).validate_python(value)
801
+
802
+ elif not TYPE_CHECKING: # TODO: condition is weird
803
+
804
+ class RootModel(GenericModel, Generic[_T]):
805
+ """Used as a placeholder to easily convert runtime types to a Pydantic format
806
+ to provide validation.
807
+
808
+ For example:
809
+ ```py
810
+ validated = RootModel[int](__root__="5").__root__
811
+ # validated: 5
812
+ ```
813
+ """
814
+
815
+ __root__: _T
816
+
817
+ def _validate_non_model_type(*, type_: type[_T], value: object) -> _T:
818
+ model = _create_pydantic_model(type_).validate(value)
819
+ return cast(_T, model.__root__)
820
+
821
+ def _create_pydantic_model(type_: _T) -> Type[RootModel[_T]]:
822
+ return RootModel[type_] # type: ignore
823
+
824
+ def TypeAdapter(*_args: Any, **_kwargs: Any) -> Any:
825
+ raise RuntimeError("attempted to use TypeAdapter in pydantic v1")
826
+
827
+ def computed_field(func: Any | None = None, /, **__: Any) -> Any:
828
+ def _exc_func(*_: Any, **__: Any) -> Any:
829
+ raise RuntimeError("attempted to use computed_field in pydantic v1")
830
+
831
+ def _dec(*_: Any, **__: Any) -> Any:
832
+ return _exc_func
833
+
834
+ if func is not None:
835
+ return _dec(func)
836
+ else:
837
+ return _dec
838
+
839
+
840
+ class FinalRequestOptionsInput(TypedDict, total=False):
841
+ method: Required[str]
842
+ url: Required[str]
843
+ params: Query
844
+ headers: Headers
845
+ max_retries: int
846
+ timeout: float | Timeout | None
847
+ files: HttpxRequestFiles | None
848
+ idempotency_key: str
849
+ content: Union[bytes, bytearray, IO[bytes], Iterable[bytes], AsyncIterable[bytes], None]
850
+ json_data: Body
851
+ extra_json: AnyMapping
852
+ follow_redirects: bool
853
+
854
+
855
+ @final
856
+ class FinalRequestOptions(pydantic.BaseModel):
857
+ method: str
858
+ url: str
859
+ params: Query = {}
860
+ headers: Union[Headers, NotGiven] = NotGiven()
861
+ max_retries: Union[int, NotGiven] = NotGiven()
862
+ timeout: Union[float, Timeout, None, NotGiven] = NotGiven()
863
+ files: Union[HttpxRequestFiles, None] = None
864
+ idempotency_key: Union[str, None] = None
865
+ post_parser: Union[Callable[[Any], Any], NotGiven] = NotGiven()
866
+ follow_redirects: Union[bool, None] = None
867
+
868
+ content: Union[bytes, bytearray, IO[bytes], Iterable[bytes], AsyncIterable[bytes], None] = None
869
+ # It should be noted that we cannot use `json` here as that would override
870
+ # a BaseModel method in an incompatible fashion.
871
+ json_data: Union[Body, None] = None
872
+ extra_json: Union[AnyMapping, None] = None
873
+
874
+ if PYDANTIC_V1:
875
+
876
+ class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated]
877
+ arbitrary_types_allowed: bool = True
878
+ else:
879
+ model_config: ClassVar[ConfigDict] = ConfigDict(arbitrary_types_allowed=True)
880
+
881
+ def get_max_retries(self, max_retries: int) -> int:
882
+ if isinstance(self.max_retries, NotGiven):
883
+ return max_retries
884
+ return self.max_retries
885
+
886
+ def _strip_raw_response_header(self) -> None:
887
+ if not is_given(self.headers):
888
+ return
889
+
890
+ if self.headers.get(RAW_RESPONSE_HEADER):
891
+ self.headers = {**self.headers}
892
+ self.headers.pop(RAW_RESPONSE_HEADER)
893
+
894
+ # override the `construct` method so that we can run custom transformations.
895
+ # this is necessary as we don't want to do any actual runtime type checking
896
+ # (which means we can't use validators) but we do want to ensure that `NotGiven`
897
+ # values are not present
898
+ #
899
+ # type ignore required because we're adding explicit types to `**values`
900
+ @classmethod
901
+ def construct( # type: ignore
902
+ cls,
903
+ _fields_set: set[str] | None = None,
904
+ **values: Unpack[FinalRequestOptionsInput],
905
+ ) -> FinalRequestOptions:
906
+ kwargs: dict[str, Any] = {
907
+ # we unconditionally call `strip_not_given` on any value
908
+ # as it will just ignore any non-mapping types
909
+ key: strip_not_given(value)
910
+ for key, value in values.items()
911
+ }
912
+ if PYDANTIC_V1:
913
+ return cast(FinalRequestOptions, super().construct(_fields_set, **kwargs)) # pyright: ignore[reportDeprecated]
914
+ return super().model_construct(_fields_set, **kwargs)
915
+
916
+ if not TYPE_CHECKING:
917
+ # type checkers incorrectly complain about this assignment
918
+ model_construct = construct
data/miniconda3/lib/python3.13/site-packages/anthropic/_qs.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, List, Tuple, Union, Mapping, TypeVar
4
+ from urllib.parse import parse_qs, urlencode
5
+ from typing_extensions import Literal, get_args
6
+
7
+ from ._types import NotGiven, not_given
8
+ from ._utils import flatten
9
+
10
+ _T = TypeVar("_T")
11
+
12
+
13
+ ArrayFormat = Literal["comma", "repeat", "indices", "brackets"]
14
+ NestedFormat = Literal["dots", "brackets"]
15
+
16
+ PrimitiveData = Union[str, int, float, bool, None]
17
+ # this should be Data = Union[PrimitiveData, "List[Data]", "Tuple[Data]", "Mapping[str, Data]"]
18
+ # https://github.com/microsoft/pyright/issues/3555
19
+ Data = Union[PrimitiveData, List[Any], Tuple[Any], "Mapping[str, Any]"]
20
+ Params = Mapping[str, Data]
21
+
22
+
23
+ class Querystring:
24
+ array_format: ArrayFormat
25
+ nested_format: NestedFormat
26
+
27
+ def __init__(
28
+ self,
29
+ *,
30
+ array_format: ArrayFormat = "repeat",
31
+ nested_format: NestedFormat = "brackets",
32
+ ) -> None:
33
+ self.array_format = array_format
34
+ self.nested_format = nested_format
35
+
36
+ def parse(self, query: str) -> Mapping[str, object]:
37
+ # Note: custom format syntax is not supported yet
38
+ return parse_qs(query)
39
+
40
+ def stringify(
41
+ self,
42
+ params: Params,
43
+ *,
44
+ array_format: ArrayFormat | NotGiven = not_given,
45
+ nested_format: NestedFormat | NotGiven = not_given,
46
+ ) -> str:
47
+ return urlencode(
48
+ self.stringify_items(
49
+ params,
50
+ array_format=array_format,
51
+ nested_format=nested_format,
52
+ )
53
+ )
54
+
55
+ def stringify_items(
56
+ self,
57
+ params: Params,
58
+ *,
59
+ array_format: ArrayFormat | NotGiven = not_given,
60
+ nested_format: NestedFormat | NotGiven = not_given,
61
+ ) -> list[tuple[str, str]]:
62
+ opts = Options(
63
+ qs=self,
64
+ array_format=array_format,
65
+ nested_format=nested_format,
66
+ )
67
+ return flatten([self._stringify_item(key, value, opts) for key, value in params.items()])
68
+
69
+ def _stringify_item(
70
+ self,
71
+ key: str,
72
+ value: Data,
73
+ opts: Options,
74
+ ) -> list[tuple[str, str]]:
75
+ if isinstance(value, Mapping):
76
+ items: list[tuple[str, str]] = []
77
+ nested_format = opts.nested_format
78
+ for subkey, subvalue in value.items():
79
+ items.extend(
80
+ self._stringify_item(
81
+ # TODO: error if unknown format
82
+ f"{key}.{subkey}" if nested_format == "dots" else f"{key}[{subkey}]",
83
+ subvalue,
84
+ opts,
85
+ )
86
+ )
87
+ return items
88
+
89
+ if isinstance(value, (list, tuple)):
90
+ array_format = opts.array_format
91
+ if array_format == "comma":
92
+ return [
93
+ (
94
+ key,
95
+ ",".join(self._primitive_value_to_str(item) for item in value if item is not None),
96
+ ),
97
+ ]
98
+ elif array_format == "repeat":
99
+ items = []
100
+ for item in value:
101
+ items.extend(self._stringify_item(key, item, opts))
102
+ return items
103
+ elif array_format == "indices":
104
+ items = []
105
+ for i, item in enumerate(value):
106
+ items.extend(self._stringify_item(f"{key}[{i}]", item, opts))
107
+ return items
108
+ elif array_format == "brackets":
109
+ items = []
110
+ key = key + "[]"
111
+ for item in value:
112
+ items.extend(self._stringify_item(key, item, opts))
113
+ return items
114
+ else:
115
+ raise NotImplementedError(
116
+ f"Unknown array_format value: {array_format}, choose from {', '.join(get_args(ArrayFormat))}"
117
+ )
118
+
119
+ serialised = self._primitive_value_to_str(value)
120
+ if not serialised:
121
+ return []
122
+ return [(key, serialised)]
123
+
124
+ def _primitive_value_to_str(self, value: PrimitiveData) -> str:
125
+ # copied from httpx
126
+ if value is True:
127
+ return "true"
128
+ elif value is False:
129
+ return "false"
130
+ elif value is None:
131
+ return ""
132
+ return str(value)
133
+
134
+
135
+ _qs = Querystring()
136
+ parse = _qs.parse
137
+ stringify = _qs.stringify
138
+ stringify_items = _qs.stringify_items
139
+
140
+
141
+ class Options:
142
+ array_format: ArrayFormat
143
+ nested_format: NestedFormat
144
+
145
+ def __init__(
146
+ self,
147
+ qs: Querystring = _qs,
148
+ *,
149
+ array_format: ArrayFormat | NotGiven = not_given,
150
+ nested_format: NestedFormat | NotGiven = not_given,
151
+ ) -> None:
152
+ self.array_format = qs.array_format if isinstance(array_format, NotGiven) else array_format
153
+ self.nested_format = qs.nested_format if isinstance(nested_format, NotGiven) else nested_format
data/miniconda3/lib/python3.13/site-packages/anthropic/_resource.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+
7
+ import anyio
8
+
9
+ from ._base_client import SyncAPIClient, AsyncAPIClient
10
+
11
+
12
+ class SyncAPIResource:
13
+ _client: SyncAPIClient
14
+
15
+ def __init__(self, client: SyncAPIClient) -> None:
16
+ self._client = client
17
+ self._get = client.get
18
+ self._post = client.post
19
+ self._patch = client.patch
20
+ self._put = client.put
21
+ self._delete = client.delete
22
+ self._get_api_list = client.get_api_list
23
+
24
+ def _sleep(self, seconds: float) -> None:
25
+ time.sleep(seconds)
26
+
27
+
28
+ class AsyncAPIResource:
29
+ _client: AsyncAPIClient
30
+
31
+ def __init__(self, client: AsyncAPIClient) -> None:
32
+ self._client = client
33
+ self._get = client.get
34
+ self._post = client.post
35
+ self._patch = client.patch
36
+ self._put = client.put
37
+ self._delete = client.delete
38
+ self._get_api_list = client.get_api_list
39
+
40
+ async def _sleep(self, seconds: float) -> None:
41
+ await anyio.sleep(seconds)
data/miniconda3/lib/python3.13/site-packages/anthropic/_response.py ADDED
@@ -0,0 +1,875 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import inspect
5
+ import logging
6
+ import datetime
7
+ import functools
8
+ from types import TracebackType
9
+ from typing import (
10
+ TYPE_CHECKING,
11
+ Any,
12
+ Union,
13
+ Generic,
14
+ TypeVar,
15
+ Callable,
16
+ Iterator,
17
+ AsyncIterator,
18
+ cast,
19
+ overload,
20
+ )
21
+ from typing_extensions import Awaitable, ParamSpec, override, get_origin
22
+
23
+ import anyio
24
+ import httpx
25
+ import pydantic
26
+
27
+ from ._types import NoneType
28
+ from ._utils import is_given, extract_type_arg, is_annotated_type, is_type_alias_type, extract_type_var_from_base
29
+ from ._models import BaseModel, is_basemodel, add_request_id
30
+ from ._constants import RAW_RESPONSE_HEADER, OVERRIDE_CAST_TO_HEADER
31
+ from ._streaming import Stream, AsyncStream, is_stream_class_type, extract_stream_chunk_type
32
+ from ._exceptions import AnthropicError, APIResponseValidationError
33
+ from ._decoders.jsonl import JSONLDecoder, AsyncJSONLDecoder
34
+
35
+ if TYPE_CHECKING:
36
+ from ._models import FinalRequestOptions
37
+ from ._base_client import BaseClient
38
+
39
+
40
+ P = ParamSpec("P")
41
+ R = TypeVar("R")
42
+ _T = TypeVar("_T")
43
+ _APIResponseT = TypeVar("_APIResponseT", bound="APIResponse[Any]")
44
+ _AsyncAPIResponseT = TypeVar("_AsyncAPIResponseT", bound="AsyncAPIResponse[Any]")
45
+
46
+ log: logging.Logger = logging.getLogger(__name__)
47
+
48
+
49
+ class BaseAPIResponse(Generic[R]):
50
+ _cast_to: type[R]
51
+ _client: BaseClient[Any, Any]
52
+ _parsed_by_type: dict[type[Any], Any]
53
+ _is_sse_stream: bool
54
+ _stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None
55
+ _options: FinalRequestOptions
56
+
57
+ http_response: httpx.Response
58
+
59
+ retries_taken: int
60
+ """The number of retries made. If no retries happened this will be `0`"""
61
+
62
+ def __init__(
63
+ self,
64
+ *,
65
+ raw: httpx.Response,
66
+ cast_to: type[R],
67
+ client: BaseClient[Any, Any],
68
+ stream: bool,
69
+ stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None,
70
+ options: FinalRequestOptions,
71
+ retries_taken: int = 0,
72
+ ) -> None:
73
+ self._cast_to = cast_to
74
+ self._client = client
75
+ self._parsed_by_type = {}
76
+ self._is_sse_stream = stream
77
+ self._stream_cls = stream_cls
78
+ self._options = options
79
+ self.http_response = raw
80
+ self.retries_taken = retries_taken
81
+
82
+ @property
83
+ def headers(self) -> httpx.Headers:
84
+ return self.http_response.headers
85
+
86
+ @property
87
+ def http_request(self) -> httpx.Request:
88
+ """Returns the httpx Request instance associated with the current response."""
89
+ return self.http_response.request
90
+
91
+ @property
92
+ def status_code(self) -> int:
93
+ return self.http_response.status_code
94
+
95
+ @property
96
+ def url(self) -> httpx.URL:
97
+ """Returns the URL for which the request was made."""
98
+ return self.http_response.url
99
+
100
+ @property
101
+ def method(self) -> str:
102
+ return self.http_request.method
103
+
104
+ @property
105
+ def http_version(self) -> str:
106
+ return self.http_response.http_version
107
+
108
+ @property
109
+ def elapsed(self) -> datetime.timedelta:
110
+ """The time taken for the complete request/response cycle to complete."""
111
+ return self.http_response.elapsed
112
+
113
+ @property
114
+ def is_closed(self) -> bool:
115
+ """Whether or not the response body has been closed.
116
+
117
+ If this is False then there is response data that has not been read yet.
118
+ You must either fully consume the response body or call `.close()`
119
+ before discarding the response to prevent resource leaks.
120
+ """
121
+ return self.http_response.is_closed
122
+
123
+ @override
124
+ def __repr__(self) -> str:
125
+ return (
126
+ f"<{self.__class__.__name__} [{self.status_code} {self.http_response.reason_phrase}] type={self._cast_to}>"
127
+ )
128
+
129
+ def _parse(self, *, to: type[_T] | None = None) -> R | _T:
130
+ cast_to = to if to is not None else self._cast_to
131
+
132
+ # unwrap `TypeAlias('Name', T)` -> `T`
133
+ if is_type_alias_type(cast_to):
134
+ cast_to = cast_to.__value__ # type: ignore[unreachable]
135
+
136
+ # unwrap `Annotated[T, ...]` -> `T`
137
+ if cast_to and is_annotated_type(cast_to):
138
+ cast_to = extract_type_arg(cast_to, 0)
139
+
140
+ origin = get_origin(cast_to) or cast_to
141
+
142
+ if inspect.isclass(origin):
143
+ if issubclass(cast(Any, origin), JSONLDecoder):
144
+ return cast(
145
+ R,
146
+ cast("type[JSONLDecoder[Any]]", cast_to)(
147
+ raw_iterator=self.http_response.iter_bytes(chunk_size=64),
148
+ line_type=extract_type_arg(cast_to, 0),
149
+ http_response=self.http_response,
150
+ ),
151
+ )
152
+
153
+ if issubclass(cast(Any, origin), AsyncJSONLDecoder):
154
+ return cast(
155
+ R,
156
+ cast("type[AsyncJSONLDecoder[Any]]", cast_to)(
157
+ raw_iterator=self.http_response.aiter_bytes(chunk_size=64),
158
+ line_type=extract_type_arg(cast_to, 0),
159
+ http_response=self.http_response,
160
+ ),
161
+ )
162
+
163
+ if self._is_sse_stream:
164
+ if to:
165
+ if not is_stream_class_type(to):
166
+ raise TypeError(f"Expected custom parse type to be a subclass of {Stream} or {AsyncStream}")
167
+
168
+ return cast(
169
+ _T,
170
+ to(
171
+ cast_to=extract_stream_chunk_type(
172
+ to,
173
+ failure_message="Expected custom stream type to be passed with a type argument, e.g. Stream[ChunkType]",
174
+ ),
175
+ response=self.http_response,
176
+ client=cast(Any, self._client),
177
+ options=self._options,
178
+ ),
179
+ )
180
+
181
+ if self._stream_cls:
182
+ return cast(
183
+ R,
184
+ self._stream_cls(
185
+ cast_to=extract_stream_chunk_type(self._stream_cls),
186
+ response=self.http_response,
187
+ client=cast(Any, self._client),
188
+ options=self._options,
189
+ ),
190
+ )
191
+
192
+ stream_cls = cast("type[Stream[Any]] | type[AsyncStream[Any]] | None", self._client._default_stream_cls)
193
+ if stream_cls is None:
194
+ raise MissingStreamClassError()
195
+
196
+ return cast(
197
+ R,
198
+ stream_cls(
199
+ cast_to=cast_to,
200
+ response=self.http_response,
201
+ client=cast(Any, self._client),
202
+ options=self._options,
203
+ ),
204
+ )
205
+
206
+ if cast_to is NoneType:
207
+ return cast(R, None)
208
+
209
+ response = self.http_response
210
+ if cast_to == str:
211
+ return cast(R, response.text)
212
+
213
+ if cast_to == bytes:
214
+ return cast(R, response.content)
215
+
216
+ if cast_to == int:
217
+ return cast(R, int(response.text))
218
+
219
+ if cast_to == float:
220
+ return cast(R, float(response.text))
221
+
222
+ if cast_to == bool:
223
+ return cast(R, response.text.lower() == "true")
224
+
225
+ # handle the legacy binary response case
226
+ if inspect.isclass(cast_to) and cast_to.__name__ == "HttpxBinaryResponseContent":
227
+ return cast(R, cast_to(response)) # type: ignore
228
+
229
+ if origin == APIResponse:
230
+ raise RuntimeError("Unexpected state - cast_to is `APIResponse`")
231
+
232
+ if inspect.isclass(
233
+ origin # pyright: ignore[reportUnknownArgumentType]
234
+ ) and issubclass(origin, httpx.Response):
235
+ # Because of the invariance of our ResponseT TypeVar, users can subclass httpx.Response
236
+ # and pass that class to our request functions. We cannot change the variance to be either
237
+ # covariant or contravariant as that makes our usage of ResponseT illegal. We could construct
238
+ # the response class ourselves but that is something that should be supported directly in httpx
239
+ # as it would be easy to incorrectly construct the Response object due to the multitude of arguments.
240
+ if cast_to != httpx.Response:
241
+ raise ValueError(f"Subclasses of httpx.Response cannot be passed to `cast_to`")
242
+ return cast(R, response)
243
+
244
+ if (
245
+ inspect.isclass(
246
+ origin # pyright: ignore[reportUnknownArgumentType]
247
+ )
248
+ and not issubclass(origin, BaseModel)
249
+ and issubclass(origin, pydantic.BaseModel)
250
+ ):
251
+ raise TypeError("Pydantic models must subclass our base model type, e.g. `from anthropic import BaseModel`")
252
+
253
+ if (
254
+ cast_to is not object
255
+ and not origin is list
256
+ and not origin is dict
257
+ and not origin is Union
258
+ and not issubclass(origin, BaseModel)
259
+ ):
260
+ raise RuntimeError(
261
+ f"Unsupported type, expected {cast_to} to be a subclass of {BaseModel}, {dict}, {list}, {Union}, {NoneType}, {str} or {httpx.Response}."
262
+ )
263
+
264
+ # split is required to handle cases where additional information is included
265
+ # in the response, e.g. application/json; charset=utf-8
266
+ content_type, *_ = response.headers.get("content-type", "*").split(";")
267
+ if not content_type.endswith("json"):
268
+ if is_basemodel(cast_to):
269
+ try:
270
+ data = response.json()
271
+ except Exception as exc:
272
+ log.debug("Could not read JSON from response data due to %s - %s", type(exc), exc)
273
+ else:
274
+ return self._client._process_response_data(
275
+ data=data,
276
+ cast_to=cast_to, # type: ignore
277
+ response=response,
278
+ )
279
+
280
+ if self._client._strict_response_validation:
281
+ raise APIResponseValidationError(
282
+ response=response,
283
+ message=f"Expected Content-Type response header to be `application/json` but received `{content_type}` instead.",
284
+ body=response.text,
285
+ )
286
+
287
+ # If the API responds with content that isn't JSON then we just return
288
+ # the (decoded) text without performing any parsing so that you can still
289
+ # handle the response however you need to.
290
+ return response.text # type: ignore
291
+
292
+ data = response.json()
293
+
294
+ return self._client._process_response_data(
295
+ data=data,
296
+ cast_to=cast_to, # type: ignore
297
+ response=response,
298
+ )
299
+
300
+
301
+ class APIResponse(BaseAPIResponse[R]):
302
+ @property
303
+ def request_id(self) -> str | None:
304
+ return self.http_response.headers.get("request-id") # type: ignore[no-any-return]
305
+
306
+ @overload
307
+ def parse(self, *, to: type[_T]) -> _T: ...
308
+
309
+ @overload
310
+ def parse(self) -> R: ...
311
+
312
+ def parse(self, *, to: type[_T] | None = None) -> R | _T:
313
+ """Returns the rich python representation of this response's data.
314
+
315
+ For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`.
316
+
317
+ You can customise the type that the response is parsed into through
318
+ the `to` argument, e.g.
319
+
320
+ ```py
321
+ from anthropic import BaseModel
322
+
323
+
324
+ class MyModel(BaseModel):
325
+ foo: str
326
+
327
+
328
+ obj = response.parse(to=MyModel)
329
+ print(obj.foo)
330
+ ```
331
+
332
+ We support parsing:
333
+ - `BaseModel`
334
+ - `dict`
335
+ - `list`
336
+ - `Union`
337
+ - `str`
338
+ - `int`
339
+ - `float`
340
+ - `httpx.Response`
341
+ """
342
+ cache_key = to if to is not None else self._cast_to
343
+ cached = self._parsed_by_type.get(cache_key)
344
+ if cached is not None:
345
+ return cached # type: ignore[no-any-return]
346
+
347
+ if not self._is_sse_stream:
348
+ self.read()
349
+
350
+ parsed = self._parse(to=to)
351
+ if is_given(self._options.post_parser):
352
+ parsed = self._options.post_parser(parsed)
353
+
354
+ if isinstance(parsed, BaseModel):
355
+ add_request_id(parsed, self.request_id)
356
+
357
+ self._parsed_by_type[cache_key] = parsed
358
+ return cast(R, parsed)
359
+
360
+ def read(self) -> bytes:
361
+ """Read and return the binary response content."""
362
+ try:
363
+ return self.http_response.read()
364
+ except httpx.StreamConsumed as exc:
365
+ # The default error raised by httpx isn't very
366
+ # helpful in our case so we re-raise it with
367
+ # a different error message.
368
+ raise StreamAlreadyConsumed() from exc
369
+
370
+ def text(self) -> str:
371
+ """Read and decode the response content into a string."""
372
+ self.read()
373
+ return self.http_response.text
374
+
375
+ def json(self) -> object:
376
+ """Read and decode the JSON response content."""
377
+ self.read()
378
+ return self.http_response.json()
379
+
380
+ def close(self) -> None:
381
+ """Close the response and release the connection.
382
+
383
+ Automatically called if the response body is read to completion.
384
+ """
385
+ self.http_response.close()
386
+
387
+ def iter_bytes(self, chunk_size: int | None = None) -> Iterator[bytes]:
388
+ """
389
+ A byte-iterator over the decoded response content.
390
+
391
+ This automatically handles gzip, deflate and brotli encoded responses.
392
+ """
393
+ for chunk in self.http_response.iter_bytes(chunk_size):
394
+ yield chunk
395
+
396
+ def iter_text(self, chunk_size: int | None = None) -> Iterator[str]:
397
+ """A str-iterator over the decoded response content
398
+ that handles both gzip, deflate, etc but also detects the content's
399
+ string encoding.
400
+ """
401
+ for chunk in self.http_response.iter_text(chunk_size):
402
+ yield chunk
403
+
404
+ def iter_lines(self) -> Iterator[str]:
405
+ """Like `iter_text()` but will only yield chunks for each line"""
406
+ for chunk in self.http_response.iter_lines():
407
+ yield chunk
408
+
409
+
410
+ class AsyncAPIResponse(BaseAPIResponse[R]):
411
+ @property
412
+ def request_id(self) -> str | None:
413
+ return self.http_response.headers.get("request-id") # type: ignore[no-any-return]
414
+
415
+ @overload
416
+ async def parse(self, *, to: type[_T]) -> _T: ...
417
+
418
+ @overload
419
+ async def parse(self) -> R: ...
420
+
421
+ async def parse(self, *, to: type[_T] | None = None) -> R | _T:
422
+ """Returns the rich python representation of this response's data.
423
+
424
+ For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`.
425
+
426
+ You can customise the type that the response is parsed into through
427
+ the `to` argument, e.g.
428
+
429
+ ```py
430
+ from anthropic import BaseModel
431
+
432
+
433
+ class MyModel(BaseModel):
434
+ foo: str
435
+
436
+
437
+ obj = response.parse(to=MyModel)
438
+ print(obj.foo)
439
+ ```
440
+
441
+ We support parsing:
442
+ - `BaseModel`
443
+ - `dict`
444
+ - `list`
445
+ - `Union`
446
+ - `str`
447
+ - `httpx.Response`
448
+ """
449
+ cache_key = to if to is not None else self._cast_to
450
+ cached = self._parsed_by_type.get(cache_key)
451
+ if cached is not None:
452
+ return cached # type: ignore[no-any-return]
453
+
454
+ if not self._is_sse_stream:
455
+ await self.read()
456
+
457
+ parsed = self._parse(to=to)
458
+ if is_given(self._options.post_parser):
459
+ parsed = self._options.post_parser(parsed)
460
+
461
+ if isinstance(parsed, BaseModel):
462
+ add_request_id(parsed, self.request_id)
463
+
464
+ self._parsed_by_type[cache_key] = parsed
465
+ return cast(R, parsed)
466
+
467
+ async def read(self) -> bytes:
468
+ """Read and return the binary response content."""
469
+ try:
470
+ return await self.http_response.aread()
471
+ except httpx.StreamConsumed as exc:
472
+ # the default error raised by httpx isn't very
473
+ # helpful in our case so we re-raise it with
474
+ # a different error message
475
+ raise StreamAlreadyConsumed() from exc
476
+
477
+ async def text(self) -> str:
478
+ """Read and decode the response content into a string."""
479
+ await self.read()
480
+ return self.http_response.text
481
+
482
+ async def json(self) -> object:
483
+ """Read and decode the JSON response content."""
484
+ await self.read()
485
+ return self.http_response.json()
486
+
487
+ async def close(self) -> None:
488
+ """Close the response and release the connection.
489
+
490
+ Automatically called if the response body is read to completion.
491
+ """
492
+ await self.http_response.aclose()
493
+
494
+ async def iter_bytes(self, chunk_size: int | None = None) -> AsyncIterator[bytes]:
495
+ """
496
+ A byte-iterator over the decoded response content.
497
+
498
+ This automatically handles gzip, deflate and brotli encoded responses.
499
+ """
500
+ async for chunk in self.http_response.aiter_bytes(chunk_size):
501
+ yield chunk
502
+
503
+ async def iter_text(self, chunk_size: int | None = None) -> AsyncIterator[str]:
504
+ """A str-iterator over the decoded response content
505
+ that handles both gzip, deflate, etc but also detects the content's
506
+ string encoding.
507
+ """
508
+ async for chunk in self.http_response.aiter_text(chunk_size):
509
+ yield chunk
510
+
511
+ async def iter_lines(self) -> AsyncIterator[str]:
512
+ """Like `iter_text()` but will only yield chunks for each line"""
513
+ async for chunk in self.http_response.aiter_lines():
514
+ yield chunk
515
+
516
+
517
+ class BinaryAPIResponse(APIResponse[bytes]):
518
+ """Subclass of APIResponse providing helpers for dealing with binary data.
519
+
520
+ Note: If you want to stream the response data instead of eagerly reading it
521
+ all at once then you should use `.with_streaming_response` when making
522
+ the API request, e.g. `.with_streaming_response.get_binary_response()`
523
+ """
524
+
525
+ def write_to_file(
526
+ self,
527
+ file: str | os.PathLike[str],
528
+ ) -> None:
529
+ """Write the output to the given file.
530
+
531
+ Accepts a filename or any path-like object, e.g. pathlib.Path
532
+
533
+ Note: if you want to stream the data to the file instead of writing
534
+ all at once then you should use `.with_streaming_response` when making
535
+ the API request, e.g. `.with_streaming_response.get_binary_response()`
536
+ """
537
+ with open(file, mode="wb") as f:
538
+ for data in self.iter_bytes():
539
+ f.write(data)
540
+
541
+
542
+ class AsyncBinaryAPIResponse(AsyncAPIResponse[bytes]):
543
+ """Subclass of APIResponse providing helpers for dealing with binary data.
544
+
545
+ Note: If you want to stream the response data instead of eagerly reading it
546
+ all at once then you should use `.with_streaming_response` when making
547
+ the API request, e.g. `.with_streaming_response.get_binary_response()`
548
+ """
549
+
550
+ async def write_to_file(
551
+ self,
552
+ file: str | os.PathLike[str],
553
+ ) -> None:
554
+ """Write the output to the given file.
555
+
556
+ Accepts a filename or any path-like object, e.g. pathlib.Path
557
+
558
+ Note: if you want to stream the data to the file instead of writing
559
+ all at once then you should use `.with_streaming_response` when making
560
+ the API request, e.g. `.with_streaming_response.get_binary_response()`
561
+ """
562
+ path = anyio.Path(file)
563
+ async with await path.open(mode="wb") as f:
564
+ async for data in self.iter_bytes():
565
+ await f.write(data)
566
+
567
+
568
+ class StreamedBinaryAPIResponse(APIResponse[bytes]):
569
+ def stream_to_file(
570
+ self,
571
+ file: str | os.PathLike[str],
572
+ *,
573
+ chunk_size: int | None = None,
574
+ ) -> None:
575
+ """Streams the output to the given file.
576
+
577
+ Accepts a filename or any path-like object, e.g. pathlib.Path
578
+ """
579
+ with open(file, mode="wb") as f:
580
+ for data in self.iter_bytes(chunk_size):
581
+ f.write(data)
582
+
583
+
584
+ class AsyncStreamedBinaryAPIResponse(AsyncAPIResponse[bytes]):
585
+ async def stream_to_file(
586
+ self,
587
+ file: str | os.PathLike[str],
588
+ *,
589
+ chunk_size: int | None = None,
590
+ ) -> None:
591
+ """Streams the output to the given file.
592
+
593
+ Accepts a filename or any path-like object, e.g. pathlib.Path
594
+ """
595
+ path = anyio.Path(file)
596
+ async with await path.open(mode="wb") as f:
597
+ async for data in self.iter_bytes(chunk_size):
598
+ await f.write(data)
599
+
600
+
601
+ class MissingStreamClassError(TypeError):
602
+ def __init__(self) -> None:
603
+ super().__init__(
604
+ "The `stream` argument was set to `True` but the `stream_cls` argument was not given. See `anthropic._streaming` for reference",
605
+ )
606
+
607
+
608
+ class StreamAlreadyConsumed(AnthropicError):
609
+ """
610
+ Attempted to read or stream content, but the content has already
611
+ been streamed.
612
+
613
+ This can happen if you use a method like `.iter_lines()` and then attempt
614
+ to read th entire response body afterwards, e.g.
615
+
616
+ ```py
617
+ response = await client.post(...)
618
+ async for line in response.iter_lines():
619
+ ... # do something with `line`
620
+
621
+ content = await response.read()
622
+ # ^ error
623
+ ```
624
+
625
+ If you want this behaviour you'll need to either manually accumulate the response
626
+ content or call `await response.read()` before iterating over the stream.
627
+ """
628
+
629
+ def __init__(self) -> None:
630
+ message = (
631
+ "Attempted to read or stream some content, but the content has "
632
+ "already been streamed. "
633
+ "This could be due to attempting to stream the response "
634
+ "content more than once."
635
+ "\n\n"
636
+ "You can fix this by manually accumulating the response content while streaming "
637
+ "or by calling `.read()` before starting to stream."
638
+ )
639
+ super().__init__(message)
640
+
641
+
642
+ class ResponseContextManager(Generic[_APIResponseT]):
643
+ """Context manager for ensuring that a request is not made
644
+ until it is entered and that the response will always be closed
645
+ when the context manager exits
646
+ """
647
+
648
+ def __init__(self, request_func: Callable[[], _APIResponseT]) -> None:
649
+ self._request_func = request_func
650
+ self.__response: _APIResponseT | None = None
651
+
652
+ def __enter__(self) -> _APIResponseT:
653
+ self.__response = self._request_func()
654
+ return self.__response
655
+
656
+ def __exit__(
657
+ self,
658
+ exc_type: type[BaseException] | None,
659
+ exc: BaseException | None,
660
+ exc_tb: TracebackType | None,
661
+ ) -> None:
662
+ if self.__response is not None:
663
+ self.__response.close()
664
+
665
+
666
+ class AsyncResponseContextManager(Generic[_AsyncAPIResponseT]):
667
+ """Context manager for ensuring that a request is not made
668
+ until it is entered and that the response will always be closed
669
+ when the context manager exits
670
+ """
671
+
672
+ def __init__(self, api_request: Awaitable[_AsyncAPIResponseT]) -> None:
673
+ self._api_request = api_request
674
+ self.__response: _AsyncAPIResponseT | None = None
675
+
676
+ async def __aenter__(self) -> _AsyncAPIResponseT:
677
+ self.__response = await self._api_request
678
+ return self.__response
679
+
680
+ async def __aexit__(
681
+ self,
682
+ exc_type: type[BaseException] | None,
683
+ exc: BaseException | None,
684
+ exc_tb: TracebackType | None,
685
+ ) -> None:
686
+ if self.__response is not None:
687
+ await self.__response.close()
688
+
689
+
690
+ def to_streamed_response_wrapper(func: Callable[P, R]) -> Callable[P, ResponseContextManager[APIResponse[R]]]:
691
+ """Higher order function that takes one of our bound API methods and wraps it
692
+ to support streaming and returning the raw `APIResponse` object directly.
693
+ """
694
+
695
+ @functools.wraps(func)
696
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> ResponseContextManager[APIResponse[R]]:
697
+ extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
698
+ extra_headers[RAW_RESPONSE_HEADER] = "stream"
699
+
700
+ kwargs["extra_headers"] = extra_headers
701
+
702
+ make_request = functools.partial(func, *args, **kwargs)
703
+
704
+ return ResponseContextManager(cast(Callable[[], APIResponse[R]], make_request))
705
+
706
+ return wrapped
707
+
708
+
709
+ def async_to_streamed_response_wrapper(
710
+ func: Callable[P, Awaitable[R]],
711
+ ) -> Callable[P, AsyncResponseContextManager[AsyncAPIResponse[R]]]:
712
+ """Higher order function that takes one of our bound API methods and wraps it
713
+ to support streaming and returning the raw `APIResponse` object directly.
714
+ """
715
+
716
+ @functools.wraps(func)
717
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncResponseContextManager[AsyncAPIResponse[R]]:
718
+ extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
719
+ extra_headers[RAW_RESPONSE_HEADER] = "stream"
720
+
721
+ kwargs["extra_headers"] = extra_headers
722
+
723
+ make_request = func(*args, **kwargs)
724
+
725
+ return AsyncResponseContextManager(cast(Awaitable[AsyncAPIResponse[R]], make_request))
726
+
727
+ return wrapped
728
+
729
+
730
+ def to_custom_streamed_response_wrapper(
731
+ func: Callable[P, object],
732
+ response_cls: type[_APIResponseT],
733
+ ) -> Callable[P, ResponseContextManager[_APIResponseT]]:
734
+ """Higher order function that takes one of our bound API methods and an `APIResponse` class
735
+ and wraps the method to support streaming and returning the given response class directly.
736
+
737
+ Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])`
738
+ """
739
+
740
+ @functools.wraps(func)
741
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> ResponseContextManager[_APIResponseT]:
742
+ extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
743
+ extra_headers[RAW_RESPONSE_HEADER] = "stream"
744
+ extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls
745
+
746
+ kwargs["extra_headers"] = extra_headers
747
+
748
+ make_request = functools.partial(func, *args, **kwargs)
749
+
750
+ return ResponseContextManager(cast(Callable[[], _APIResponseT], make_request))
751
+
752
+ return wrapped
753
+
754
+
755
+ def async_to_custom_streamed_response_wrapper(
756
+ func: Callable[P, Awaitable[object]],
757
+ response_cls: type[_AsyncAPIResponseT],
758
+ ) -> Callable[P, AsyncResponseContextManager[_AsyncAPIResponseT]]:
759
+ """Higher order function that takes one of our bound API methods and an `APIResponse` class
760
+ and wraps the method to support streaming and returning the given response class directly.
761
+
762
+ Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])`
763
+ """
764
+
765
+ @functools.wraps(func)
766
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncResponseContextManager[_AsyncAPIResponseT]:
767
+ extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
768
+ extra_headers[RAW_RESPONSE_HEADER] = "stream"
769
+ extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls
770
+
771
+ kwargs["extra_headers"] = extra_headers
772
+
773
+ make_request = func(*args, **kwargs)
774
+
775
+ return AsyncResponseContextManager(cast(Awaitable[_AsyncAPIResponseT], make_request))
776
+
777
+ return wrapped
778
+
779
+
780
+ def to_raw_response_wrapper(func: Callable[P, R]) -> Callable[P, APIResponse[R]]:
781
+ """Higher order function that takes one of our bound API methods and wraps it
782
+ to support returning the raw `APIResponse` object directly.
783
+ """
784
+
785
+ @functools.wraps(func)
786
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> APIResponse[R]:
787
+ extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
788
+ extra_headers[RAW_RESPONSE_HEADER] = "raw"
789
+
790
+ kwargs["extra_headers"] = extra_headers
791
+
792
+ return cast(APIResponse[R], func(*args, **kwargs))
793
+
794
+ return wrapped
795
+
796
+
797
+ def async_to_raw_response_wrapper(func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[AsyncAPIResponse[R]]]:
798
+ """Higher order function that takes one of our bound API methods and wraps it
799
+ to support returning the raw `APIResponse` object directly.
800
+ """
801
+
802
+ @functools.wraps(func)
803
+ async def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncAPIResponse[R]:
804
+ extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
805
+ extra_headers[RAW_RESPONSE_HEADER] = "raw"
806
+
807
+ kwargs["extra_headers"] = extra_headers
808
+
809
+ return cast(AsyncAPIResponse[R], await func(*args, **kwargs))
810
+
811
+ return wrapped
812
+
813
+
814
+ def to_custom_raw_response_wrapper(
815
+ func: Callable[P, object],
816
+ response_cls: type[_APIResponseT],
817
+ ) -> Callable[P, _APIResponseT]:
818
+ """Higher order function that takes one of our bound API methods and an `APIResponse` class
819
+ and wraps the method to support returning the given response class directly.
820
+
821
+ Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])`
822
+ """
823
+
824
+ @functools.wraps(func)
825
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> _APIResponseT:
826
+ extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
827
+ extra_headers[RAW_RESPONSE_HEADER] = "raw"
828
+ extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls
829
+
830
+ kwargs["extra_headers"] = extra_headers
831
+
832
+ return cast(_APIResponseT, func(*args, **kwargs))
833
+
834
+ return wrapped
835
+
836
+
837
+ def async_to_custom_raw_response_wrapper(
838
+ func: Callable[P, Awaitable[object]],
839
+ response_cls: type[_AsyncAPIResponseT],
840
+ ) -> Callable[P, Awaitable[_AsyncAPIResponseT]]:
841
+ """Higher order function that takes one of our bound API methods and an `APIResponse` class
842
+ and wraps the method to support returning the given response class directly.
843
+
844
+ Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])`
845
+ """
846
+
847
+ @functools.wraps(func)
848
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> Awaitable[_AsyncAPIResponseT]:
849
+ extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
850
+ extra_headers[RAW_RESPONSE_HEADER] = "raw"
851
+ extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls
852
+
853
+ kwargs["extra_headers"] = extra_headers
854
+
855
+ return cast(Awaitable[_AsyncAPIResponseT], func(*args, **kwargs))
856
+
857
+ return wrapped
858
+
859
+
860
+ def extract_response_type(typ: type[BaseAPIResponse[Any]]) -> type:
861
+ """Given a type like `APIResponse[T]`, returns the generic type variable `T`.
862
+
863
+ This also handles the case where a concrete subclass is given, e.g.
864
+ ```py
865
+ class MyResponse(APIResponse[bytes]):
866
+ ...
867
+
868
+ extract_response_type(MyResponse) -> bytes
869
+ ```
870
+ """
871
+ return extract_type_var_from_base(
872
+ typ,
873
+ generic_bases=cast("tuple[type, ...]", (BaseAPIResponse, APIResponse, AsyncAPIResponse)),
874
+ index=0,
875
+ )
data/miniconda3/lib/python3.13/site-packages/anthropic/_streaming.py ADDED
@@ -0,0 +1,450 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Note: initially copied from https://github.com/florimondmanca/httpx-sse/blob/master/src/httpx_sse/_decoders.py
2
+ from __future__ import annotations
3
+
4
+ import abc
5
+ import json
6
+ import inspect
7
+ import warnings
8
+ from types import TracebackType
9
+ from typing import TYPE_CHECKING, Any, Generic, TypeVar, Iterator, Optional, AsyncIterator, cast
10
+ from typing_extensions import Self, Protocol, TypeGuard, override, get_origin, runtime_checkable
11
+
12
+ import httpx
13
+
14
+ from ._utils import is_dict, extract_type_var_from_base
15
+
16
+ if TYPE_CHECKING:
17
+ from ._client import Anthropic, AsyncAnthropic
18
+ from ._models import FinalRequestOptions
19
+
20
+
21
+ _T = TypeVar("_T")
22
+
23
+
24
+ class _SyncStreamMeta(abc.ABCMeta):
25
+ @override
26
+ def __instancecheck__(self, instance: Any) -> bool:
27
+ # we override the `isinstance()` check for `Stream`
28
+ # as a previous version of the `MessageStream` class
29
+ # inherited from `Stream` & without this workaround,
30
+ # changing it to not inherit would be a breaking change.
31
+
32
+ from .lib.streaming import MessageStream
33
+
34
+ if isinstance(instance, MessageStream):
35
+ warnings.warn(
36
+ "Using `isinstance()` to check if a `MessageStream` object is an instance of `Stream` is deprecated & will be removed in the next major version",
37
+ DeprecationWarning,
38
+ stacklevel=2,
39
+ )
40
+ return True
41
+
42
+ return False
43
+
44
+
45
+ class Stream(Generic[_T], metaclass=_SyncStreamMeta):
46
+ """Provides the core interface to iterate over a synchronous stream response."""
47
+
48
+ response: httpx.Response
49
+ _options: Optional[FinalRequestOptions] = None
50
+ _decoder: SSEBytesDecoder
51
+
52
+ def __init__(
53
+ self,
54
+ *,
55
+ cast_to: type[_T],
56
+ response: httpx.Response,
57
+ client: Anthropic,
58
+ options: Optional[FinalRequestOptions] = None,
59
+ ) -> None:
60
+ self.response = response
61
+ self._cast_to = cast_to
62
+ self._client = client
63
+ self._options = options
64
+ self._decoder = client._make_sse_decoder()
65
+ self._iterator = self.__stream__()
66
+
67
+ def __next__(self) -> _T:
68
+ return self._iterator.__next__()
69
+
70
+ def __iter__(self) -> Iterator[_T]:
71
+ for item in self._iterator:
72
+ yield item
73
+
74
+ def _iter_events(self) -> Iterator[ServerSentEvent]:
75
+ yield from self._decoder.iter_bytes(self.response.iter_bytes())
76
+
77
+ def __stream__(self) -> Iterator[_T]:
78
+ cast_to = cast(Any, self._cast_to)
79
+ response = self.response
80
+ process_data = self._client._process_response_data
81
+ iterator = self._iter_events()
82
+
83
+ try:
84
+ for sse in iterator:
85
+ if sse.event == "completion":
86
+ yield process_data(data=sse.json(), cast_to=cast_to, response=response)
87
+
88
+ if (
89
+ sse.event == "message_start"
90
+ or sse.event == "message_delta"
91
+ or sse.event == "message_stop"
92
+ or sse.event == "content_block_start"
93
+ or sse.event == "content_block_delta"
94
+ or sse.event == "content_block_stop"
95
+ or sse.event == "message"
96
+ ):
97
+ data = sse.json()
98
+ if is_dict(data) and "type" not in data:
99
+ data["type"] = sse.event
100
+
101
+ yield process_data(data=data, cast_to=cast_to, response=response)
102
+
103
+ if sse.event == "ping":
104
+ continue
105
+
106
+ if sse.event == "error":
107
+ body = sse.data
108
+
109
+ try:
110
+ body = sse.json()
111
+ err_msg = f"{body}"
112
+ except Exception:
113
+ err_msg = sse.data or f"Error code: {response.status_code}"
114
+
115
+ raise self._client._make_status_error(
116
+ err_msg,
117
+ body=body,
118
+ response=self.response,
119
+ )
120
+ finally:
121
+ # Ensure the response is closed even if the consumer doesn't read all data
122
+ response.close()
123
+
124
+ def __enter__(self) -> Self:
125
+ return self
126
+
127
+ def __exit__(
128
+ self,
129
+ exc_type: type[BaseException] | None,
130
+ exc: BaseException | None,
131
+ exc_tb: TracebackType | None,
132
+ ) -> None:
133
+ self.close()
134
+
135
+ def close(self) -> None:
136
+ """
137
+ Close the response and release the connection.
138
+
139
+ Automatically called if the response body is read to completion.
140
+ """
141
+ self.response.close()
142
+
143
+
144
+ class _AsyncStreamMeta(abc.ABCMeta):
145
+ @override
146
+ def __instancecheck__(self, instance: Any) -> bool:
147
+ # we override the `isinstance()` check for `AsyncStream`
148
+ # as a previous version of the `AsyncMessageStream` class
149
+ # inherited from `AsyncStream` & without this workaround,
150
+ # changing it to not inherit would be a breaking change.
151
+
152
+ from .lib.streaming import AsyncMessageStream
153
+
154
+ if isinstance(instance, AsyncMessageStream):
155
+ warnings.warn(
156
+ "Using `isinstance()` to check if a `AsyncMessageStream` object is an instance of `AsyncStream` is deprecated & will be removed in the next major version",
157
+ DeprecationWarning,
158
+ stacklevel=2,
159
+ )
160
+ return True
161
+
162
+ return False
163
+
164
+
165
+ class AsyncStream(Generic[_T], metaclass=_AsyncStreamMeta):
166
+ """Provides the core interface to iterate over an asynchronous stream response."""
167
+
168
+ response: httpx.Response
169
+ _options: Optional[FinalRequestOptions] = None
170
+ _decoder: SSEDecoder | SSEBytesDecoder
171
+
172
+ def __init__(
173
+ self,
174
+ *,
175
+ cast_to: type[_T],
176
+ response: httpx.Response,
177
+ client: AsyncAnthropic,
178
+ options: Optional[FinalRequestOptions] = None,
179
+ ) -> None:
180
+ self.response = response
181
+ self._cast_to = cast_to
182
+ self._client = client
183
+ self._options = options
184
+ self._decoder = client._make_sse_decoder()
185
+ self._iterator = self.__stream__()
186
+
187
+ async def __anext__(self) -> _T:
188
+ return await self._iterator.__anext__()
189
+
190
+ async def __aiter__(self) -> AsyncIterator[_T]:
191
+ async for item in self._iterator:
192
+ yield item
193
+
194
+ async def _iter_events(self) -> AsyncIterator[ServerSentEvent]:
195
+ async for sse in self._decoder.aiter_bytes(self.response.aiter_bytes()):
196
+ yield sse
197
+
198
+ async def __stream__(self) -> AsyncIterator[_T]:
199
+ cast_to = cast(Any, self._cast_to)
200
+ response = self.response
201
+ process_data = self._client._process_response_data
202
+ iterator = self._iter_events()
203
+
204
+ try:
205
+ async for sse in iterator:
206
+ if sse.event == "completion":
207
+ yield process_data(data=sse.json(), cast_to=cast_to, response=response)
208
+
209
+ if (
210
+ sse.event == "message_start"
211
+ or sse.event == "message_delta"
212
+ or sse.event == "message_stop"
213
+ or sse.event == "content_block_start"
214
+ or sse.event == "content_block_delta"
215
+ or sse.event == "content_block_stop"
216
+ or sse.event == "message"
217
+ ):
218
+ data = sse.json()
219
+ if is_dict(data) and "type" not in data:
220
+ data["type"] = sse.event
221
+
222
+ yield process_data(data=data, cast_to=cast_to, response=response)
223
+
224
+ if sse.event == "ping":
225
+ continue
226
+
227
+ if sse.event == "error":
228
+ body = sse.data
229
+
230
+ try:
231
+ body = sse.json()
232
+ err_msg = f"{body}"
233
+ except Exception:
234
+ err_msg = sse.data or f"Error code: {response.status_code}"
235
+
236
+ raise self._client._make_status_error(
237
+ err_msg,
238
+ body=body,
239
+ response=self.response,
240
+ )
241
+ finally:
242
+ # Ensure the response is closed even if the consumer doesn't read all data
243
+ await response.aclose()
244
+
245
+ async def __aenter__(self) -> Self:
246
+ return self
247
+
248
+ async def __aexit__(
249
+ self,
250
+ exc_type: type[BaseException] | None,
251
+ exc: BaseException | None,
252
+ exc_tb: TracebackType | None,
253
+ ) -> None:
254
+ await self.close()
255
+
256
+ async def close(self) -> None:
257
+ """
258
+ Close the response and release the connection.
259
+
260
+ Automatically called if the response body is read to completion.
261
+ """
262
+ await self.response.aclose()
263
+
264
+
265
+ class ServerSentEvent:
266
+ def __init__(
267
+ self,
268
+ *,
269
+ event: str | None = None,
270
+ data: str | None = None,
271
+ id: str | None = None,
272
+ retry: int | None = None,
273
+ ) -> None:
274
+ if data is None:
275
+ data = ""
276
+
277
+ self._id = id
278
+ self._data = data
279
+ self._event = event or None
280
+ self._retry = retry
281
+
282
+ @property
283
+ def event(self) -> str | None:
284
+ return self._event
285
+
286
+ @property
287
+ def id(self) -> str | None:
288
+ return self._id
289
+
290
+ @property
291
+ def retry(self) -> int | None:
292
+ return self._retry
293
+
294
+ @property
295
+ def data(self) -> str:
296
+ return self._data
297
+
298
+ def json(self) -> Any:
299
+ return json.loads(self.data)
300
+
301
+ @override
302
+ def __repr__(self) -> str:
303
+ return f"ServerSentEvent(event={self.event}, data={self.data}, id={self.id}, retry={self.retry})"
304
+
305
+
306
+ class SSEDecoder:
307
+ _data: list[str]
308
+ _event: str | None
309
+ _retry: int | None
310
+ _last_event_id: str | None
311
+
312
+ def __init__(self) -> None:
313
+ self._event = None
314
+ self._data = []
315
+ self._last_event_id = None
316
+ self._retry = None
317
+
318
+ def iter_bytes(self, iterator: Iterator[bytes]) -> Iterator[ServerSentEvent]:
319
+ """Given an iterator that yields raw binary data, iterate over it & yield every event encountered"""
320
+ for chunk in self._iter_chunks(iterator):
321
+ # Split before decoding so splitlines() only uses \r and \n
322
+ for raw_line in chunk.splitlines():
323
+ line = raw_line.decode("utf-8")
324
+ sse = self.decode(line)
325
+ if sse:
326
+ yield sse
327
+
328
+ def _iter_chunks(self, iterator: Iterator[bytes]) -> Iterator[bytes]:
329
+ """Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunks"""
330
+ data = b""
331
+ for chunk in iterator:
332
+ for line in chunk.splitlines(keepends=True):
333
+ data += line
334
+ if data.endswith((b"\r\r", b"\n\n", b"\r\n\r\n")):
335
+ yield data
336
+ data = b""
337
+ if data:
338
+ yield data
339
+
340
+ async def aiter_bytes(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[ServerSentEvent]:
341
+ """Given an iterator that yields raw binary data, iterate over it & yield every event encountered"""
342
+ async for chunk in self._aiter_chunks(iterator):
343
+ # Split before decoding so splitlines() only uses \r and \n
344
+ for raw_line in chunk.splitlines():
345
+ line = raw_line.decode("utf-8")
346
+ sse = self.decode(line)
347
+ if sse:
348
+ yield sse
349
+
350
+ async def _aiter_chunks(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[bytes]:
351
+ """Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunks"""
352
+ data = b""
353
+ async for chunk in iterator:
354
+ for line in chunk.splitlines(keepends=True):
355
+ data += line
356
+ if data.endswith((b"\r\r", b"\n\n", b"\r\n\r\n")):
357
+ yield data
358
+ data = b""
359
+ if data:
360
+ yield data
361
+
362
+ def decode(self, line: str) -> ServerSentEvent | None:
363
+ # See: https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation # noqa: E501
364
+
365
+ if not line:
366
+ if not self._event and not self._data and not self._last_event_id and self._retry is None:
367
+ return None
368
+
369
+ sse = ServerSentEvent(
370
+ event=self._event,
371
+ data="\n".join(self._data),
372
+ id=self._last_event_id,
373
+ retry=self._retry,
374
+ )
375
+
376
+ # NOTE: as per the SSE spec, do not reset last_event_id.
377
+ self._event = None
378
+ self._data = []
379
+ self._retry = None
380
+
381
+ return sse
382
+
383
+ if line.startswith(":"):
384
+ return None
385
+
386
+ fieldname, _, value = line.partition(":")
387
+
388
+ if value.startswith(" "):
389
+ value = value[1:]
390
+
391
+ if fieldname == "event":
392
+ self._event = value
393
+ elif fieldname == "data":
394
+ self._data.append(value)
395
+ elif fieldname == "id":
396
+ if "\0" in value:
397
+ pass
398
+ else:
399
+ self._last_event_id = value
400
+ elif fieldname == "retry":
401
+ try:
402
+ self._retry = int(value)
403
+ except (TypeError, ValueError):
404
+ pass
405
+ else:
406
+ pass # Field is ignored.
407
+
408
+ return None
409
+
410
+
411
+ @runtime_checkable
412
+ class SSEBytesDecoder(Protocol):
413
+ def iter_bytes(self, iterator: Iterator[bytes]) -> Iterator[ServerSentEvent]:
414
+ """Given an iterator that yields raw binary data, iterate over it & yield every event encountered"""
415
+ ...
416
+
417
+ def aiter_bytes(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[ServerSentEvent]:
418
+ """Given an async iterator that yields raw binary data, iterate over it & yield every event encountered"""
419
+ ...
420
+
421
+
422
+ def is_stream_class_type(typ: type) -> TypeGuard[type[Stream[object]] | type[AsyncStream[object]]]:
423
+ """TypeGuard for determining whether or not the given type is a subclass of `Stream` / `AsyncStream`"""
424
+ origin = get_origin(typ) or typ
425
+ return inspect.isclass(origin) and issubclass(origin, (Stream, AsyncStream))
426
+
427
+
428
+ def extract_stream_chunk_type(
429
+ stream_cls: type,
430
+ *,
431
+ failure_message: str | None = None,
432
+ ) -> type:
433
+ """Given a type like `Stream[T]`, returns the generic type variable `T`.
434
+
435
+ This also handles the case where a concrete subclass is given, e.g.
436
+ ```py
437
+ class MyStream(Stream[bytes]):
438
+ ...
439
+
440
+ extract_stream_chunk_type(MyStream) -> bytes
441
+ ```
442
+ """
443
+ from ._base_client import Stream, AsyncStream
444
+
445
+ return extract_type_var_from_base(
446
+ stream_cls,
447
+ index=0,
448
+ generic_bases=cast("tuple[type, ...]", (Stream, AsyncStream)),
449
+ failure_message=failure_message,
450
+ )
data/miniconda3/lib/python3.13/site-packages/anthropic/_types.py ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from os import PathLike
4
+ from typing import (
5
+ IO,
6
+ TYPE_CHECKING,
7
+ Any,
8
+ Dict,
9
+ List,
10
+ Type,
11
+ Tuple,
12
+ Union,
13
+ Mapping,
14
+ TypeVar,
15
+ Callable,
16
+ Iterable,
17
+ Iterator,
18
+ Optional,
19
+ Sequence,
20
+ AsyncIterable,
21
+ )
22
+ from typing_extensions import (
23
+ Set,
24
+ Literal,
25
+ Protocol,
26
+ TypeAlias,
27
+ TypedDict,
28
+ SupportsIndex,
29
+ overload,
30
+ override,
31
+ runtime_checkable,
32
+ )
33
+
34
+ import httpx
35
+ import pydantic
36
+ from httpx import URL, Proxy, Timeout, Response, BaseTransport, AsyncBaseTransport
37
+
38
+ if TYPE_CHECKING:
39
+ from ._models import BaseModel
40
+ from ._response import APIResponse, AsyncAPIResponse
41
+ from ._legacy_response import HttpxBinaryResponseContent
42
+
43
+ Transport = BaseTransport
44
+ AsyncTransport = AsyncBaseTransport
45
+ Query = Mapping[str, object]
46
+ Body = object
47
+ AnyMapping = Mapping[str, object]
48
+ ModelT = TypeVar("ModelT", bound=pydantic.BaseModel)
49
+ _T = TypeVar("_T")
50
+
51
+
52
+ # Approximates httpx internal ProxiesTypes and RequestFiles types
53
+ # while adding support for `PathLike` instances
54
+ ProxiesDict = Dict["str | URL", Union[None, str, URL, Proxy]]
55
+ ProxiesTypes = Union[str, Proxy, ProxiesDict]
56
+ if TYPE_CHECKING:
57
+ Base64FileInput = Union[IO[bytes], PathLike[str]]
58
+ FileContent = Union[IO[bytes], bytes, PathLike[str]]
59
+ else:
60
+ Base64FileInput = Union[IO[bytes], PathLike]
61
+ FileContent = Union[IO[bytes], bytes, PathLike] # PathLike is not subscriptable in Python 3.8.
62
+
63
+
64
+ # Used for sending raw binary data / streaming data in request bodies
65
+ # e.g. for file uploads without multipart encoding
66
+ BinaryTypes = Union[bytes, bytearray, IO[bytes], Iterable[bytes]]
67
+ AsyncBinaryTypes = Union[bytes, bytearray, IO[bytes], AsyncIterable[bytes]]
68
+
69
+ FileTypes = Union[
70
+ # file (or bytes)
71
+ FileContent,
72
+ # (filename, file (or bytes))
73
+ Tuple[Optional[str], FileContent],
74
+ # (filename, file (or bytes), content_type)
75
+ Tuple[Optional[str], FileContent, Optional[str]],
76
+ # (filename, file (or bytes), content_type, headers)
77
+ Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]],
78
+ ]
79
+ RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]]
80
+
81
+ # duplicate of the above but without our custom file support
82
+ HttpxFileContent = Union[IO[bytes], bytes]
83
+ HttpxFileTypes = Union[
84
+ # file (or bytes)
85
+ HttpxFileContent,
86
+ # (filename, file (or bytes))
87
+ Tuple[Optional[str], HttpxFileContent],
88
+ # (filename, file (or bytes), content_type)
89
+ Tuple[Optional[str], HttpxFileContent, Optional[str]],
90
+ # (filename, file (or bytes), content_type, headers)
91
+ Tuple[Optional[str], HttpxFileContent, Optional[str], Mapping[str, str]],
92
+ ]
93
+ HttpxRequestFiles = Union[Mapping[str, HttpxFileTypes], Sequence[Tuple[str, HttpxFileTypes]]]
94
+
95
+ # Workaround to support (cast_to: Type[ResponseT]) -> ResponseT
96
+ # where ResponseT includes `None`. In order to support directly
97
+ # passing `None`, overloads would have to be defined for every
98
+ # method that uses `ResponseT` which would lead to an unacceptable
99
+ # amount of code duplication and make it unreadable. See _base_client.py
100
+ # for example usage.
101
+ #
102
+ # This unfortunately means that you will either have
103
+ # to import this type and pass it explicitly:
104
+ #
105
+ # from anthropic import NoneType
106
+ # client.get('/foo', cast_to=NoneType)
107
+ #
108
+ # or build it yourself:
109
+ #
110
+ # client.get('/foo', cast_to=type(None))
111
+ if TYPE_CHECKING:
112
+ NoneType: Type[None]
113
+ else:
114
+ NoneType = type(None)
115
+
116
+
117
+ class RequestOptions(TypedDict, total=False):
118
+ headers: Headers
119
+ max_retries: int
120
+ timeout: float | Timeout | None
121
+ params: Query
122
+ extra_json: AnyMapping
123
+ idempotency_key: str
124
+ follow_redirects: bool
125
+
126
+
127
+ # Sentinel class used until PEP 0661 is accepted
128
+ class NotGiven:
129
+ """
130
+ For parameters with a meaningful None value, we need to distinguish between
131
+ the user explicitly passing None, and the user not passing the parameter at
132
+ all.
133
+
134
+ User code shouldn't need to use not_given directly.
135
+
136
+ For example:
137
+
138
+ ```py
139
+ def create(timeout: Timeout | None | NotGiven = not_given): ...
140
+
141
+
142
+ create(timeout=1) # 1s timeout
143
+ create(timeout=None) # No timeout
144
+ create() # Default timeout behavior
145
+ ```
146
+ """
147
+
148
+ def __bool__(self) -> Literal[False]:
149
+ return False
150
+
151
+ @override
152
+ def __repr__(self) -> str:
153
+ return "NOT_GIVEN"
154
+
155
+
156
+ not_given = NotGiven()
157
+ # for backwards compatibility:
158
+ NOT_GIVEN = NotGiven()
159
+
160
+
161
+ class Omit:
162
+ """
163
+ To explicitly omit something from being sent in a request, use `omit`.
164
+
165
+ ```py
166
+ # as the default `Content-Type` header is `application/json` that will be sent
167
+ client.post("/upload/files", files={"file": b"my raw file content"})
168
+
169
+ # you can't explicitly override the header as it has to be dynamically generated
170
+ # to look something like: 'multipart/form-data; boundary=0d8382fcf5f8c3be01ca2e11002d2983'
171
+ client.post(..., headers={"Content-Type": "multipart/form-data"})
172
+
173
+ # instead you can remove the default `application/json` header by passing omit
174
+ client.post(..., headers={"Content-Type": omit})
175
+ ```
176
+ """
177
+
178
+ def __bool__(self) -> Literal[False]:
179
+ return False
180
+
181
+
182
+ omit = Omit()
183
+
184
+
185
+ @runtime_checkable
186
+ class ModelBuilderProtocol(Protocol):
187
+ @classmethod
188
+ def build(
189
+ cls: type[_T],
190
+ *,
191
+ response: Response,
192
+ data: object,
193
+ ) -> _T: ...
194
+
195
+
196
+ Headers = Mapping[str, Union[str, Omit]]
197
+
198
+
199
+ class HeadersLikeProtocol(Protocol):
200
+ def get(self, __key: str) -> str | None: ...
201
+
202
+
203
+ HeadersLike = Union[Headers, HeadersLikeProtocol]
204
+
205
+ ResponseT = TypeVar(
206
+ "ResponseT",
207
+ bound=Union[
208
+ object,
209
+ str,
210
+ None,
211
+ "BaseModel",
212
+ List[Any],
213
+ Dict[str, Any],
214
+ Response,
215
+ ModelBuilderProtocol,
216
+ "APIResponse[Any]",
217
+ "AsyncAPIResponse[Any]",
218
+ "HttpxBinaryResponseContent",
219
+ ],
220
+ )
221
+
222
+ StrBytesIntFloat = Union[str, bytes, int, float]
223
+
224
+ # Note: copied from Pydantic
225
+ # https://github.com/pydantic/pydantic/blob/6f31f8f68ef011f84357330186f603ff295312fd/pydantic/main.py#L79
226
+ IncEx: TypeAlias = Union[Set[int], Set[str], Mapping[int, Union["IncEx", bool]], Mapping[str, Union["IncEx", bool]]]
227
+
228
+ PostParser = Callable[[Any], Any]
229
+
230
+
231
+ @runtime_checkable
232
+ class InheritsGeneric(Protocol):
233
+ """Represents a type that has inherited from `Generic`
234
+
235
+ The `__orig_bases__` property can be used to determine the resolved
236
+ type variable for a given base class.
237
+ """
238
+
239
+ __orig_bases__: tuple[_GenericAlias]
240
+
241
+
242
+ class _GenericAlias(Protocol):
243
+ __origin__: type[object]
244
+
245
+
246
+ class HttpxSendArgs(TypedDict, total=False):
247
+ auth: httpx.Auth
248
+ follow_redirects: bool
249
+
250
+
251
+ _T_co = TypeVar("_T_co", covariant=True)
252
+
253
+
254
+ if TYPE_CHECKING:
255
+ # This works because str.__contains__ does not accept object (either in typeshed or at runtime)
256
+ # https://github.com/hauntsaninja/useful_types/blob/5e9710f3875107d068e7679fd7fec9cfab0eff3b/useful_types/__init__.py#L285
257
+ #
258
+ # Note: index() and count() methods are intentionally omitted to allow pyright to properly
259
+ # infer TypedDict types when dict literals are used in lists assigned to SequenceNotStr.
260
+ class SequenceNotStr(Protocol[_T_co]):
261
+ @overload
262
+ def __getitem__(self, index: SupportsIndex, /) -> _T_co: ...
263
+ @overload
264
+ def __getitem__(self, index: slice, /) -> Sequence[_T_co]: ...
265
+ def __contains__(self, value: object, /) -> bool: ...
266
+ def __len__(self) -> int: ...
267
+ def __iter__(self) -> Iterator[_T_co]: ...
268
+ def __reversed__(self) -> Iterator[_T_co]: ...
269
+ else:
270
+ # just point this to a normal `Sequence` at runtime to avoid having to special case
271
+ # deserializing our custom sequence type
272
+ SequenceNotStr = Sequence
data/miniconda3/lib/python3.13/site-packages/anthropic/_version.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ __title__ = "anthropic"
4
+ __version__ = "0.94.0" # x-release-please-version
data/miniconda3/lib/python3.13/site-packages/anthropic/pagination.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from typing import List, Generic, TypeVar, Optional
4
+ from typing_extensions import override
5
+
6
+ from ._base_client import BasePage, PageInfo, BaseSyncPage, BaseAsyncPage
7
+
8
+ __all__ = ["SyncPage", "AsyncPage", "SyncTokenPage", "AsyncTokenPage", "SyncPageCursor", "AsyncPageCursor"]
9
+
10
+ _T = TypeVar("_T")
11
+
12
+
13
+ class SyncPage(BaseSyncPage[_T], BasePage[_T], Generic[_T]):
14
+ data: List[_T]
15
+ has_more: Optional[bool] = None
16
+ first_id: Optional[str] = None
17
+ last_id: Optional[str] = None
18
+
19
+ @override
20
+ def _get_page_items(self) -> List[_T]:
21
+ data = self.data
22
+ if not data:
23
+ return []
24
+ return data
25
+
26
+ @override
27
+ def has_next_page(self) -> bool:
28
+ has_more = self.has_more
29
+ if has_more is not None and has_more is False:
30
+ return False
31
+
32
+ return super().has_next_page()
33
+
34
+ @override
35
+ def next_page_info(self) -> Optional[PageInfo]:
36
+ if self._options.params.get("before_id"):
37
+ first_id = self.first_id
38
+ if not first_id:
39
+ return None
40
+
41
+ return PageInfo(params={"before_id": first_id})
42
+
43
+ last_id = self.last_id
44
+ if not last_id:
45
+ return None
46
+
47
+ return PageInfo(params={"after_id": last_id})
48
+
49
+
50
+ class AsyncPage(BaseAsyncPage[_T], BasePage[_T], Generic[_T]):
51
+ data: List[_T]
52
+ has_more: Optional[bool] = None
53
+ first_id: Optional[str] = None
54
+ last_id: Optional[str] = None
55
+
56
+ @override
57
+ def _get_page_items(self) -> List[_T]:
58
+ data = self.data
59
+ if not data:
60
+ return []
61
+ return data
62
+
63
+ @override
64
+ def has_next_page(self) -> bool:
65
+ has_more = self.has_more
66
+ if has_more is not None and has_more is False:
67
+ return False
68
+
69
+ return super().has_next_page()
70
+
71
+ @override
72
+ def next_page_info(self) -> Optional[PageInfo]:
73
+ if self._options.params.get("before_id"):
74
+ first_id = self.first_id
75
+ if not first_id:
76
+ return None
77
+
78
+ return PageInfo(params={"before_id": first_id})
79
+
80
+ last_id = self.last_id
81
+ if not last_id:
82
+ return None
83
+
84
+ return PageInfo(params={"after_id": last_id})
85
+
86
+
87
+ class SyncTokenPage(BaseSyncPage[_T], BasePage[_T], Generic[_T]):
88
+ data: List[_T]
89
+ has_more: Optional[bool] = None
90
+ next_page: Optional[str] = None
91
+
92
+ @override
93
+ def _get_page_items(self) -> List[_T]:
94
+ data = self.data
95
+ if not data:
96
+ return []
97
+ return data
98
+
99
+ @override
100
+ def has_next_page(self) -> bool:
101
+ has_more = self.has_more
102
+ if has_more is not None and has_more is False:
103
+ return False
104
+
105
+ return super().has_next_page()
106
+
107
+ @override
108
+ def next_page_info(self) -> Optional[PageInfo]:
109
+ next_page = self.next_page
110
+ if not next_page:
111
+ return None
112
+
113
+ return PageInfo(params={"page_token": next_page})
114
+
115
+
116
+ class AsyncTokenPage(BaseAsyncPage[_T], BasePage[_T], Generic[_T]):
117
+ data: List[_T]
118
+ has_more: Optional[bool] = None
119
+ next_page: Optional[str] = None
120
+
121
+ @override
122
+ def _get_page_items(self) -> List[_T]:
123
+ data = self.data
124
+ if not data:
125
+ return []
126
+ return data
127
+
128
+ @override
129
+ def has_next_page(self) -> bool:
130
+ has_more = self.has_more
131
+ if has_more is not None and has_more is False:
132
+ return False
133
+
134
+ return super().has_next_page()
135
+
136
+ @override
137
+ def next_page_info(self) -> Optional[PageInfo]:
138
+ next_page = self.next_page
139
+ if not next_page:
140
+ return None
141
+
142
+ return PageInfo(params={"page_token": next_page})
143
+
144
+
145
+ class SyncPageCursor(BaseSyncPage[_T], BasePage[_T], Generic[_T]):
146
+ data: List[_T]
147
+ next_page: Optional[str] = None
148
+
149
+ @override
150
+ def _get_page_items(self) -> List[_T]:
151
+ data = self.data
152
+ if not data:
153
+ return []
154
+ return data
155
+
156
+ @override
157
+ def next_page_info(self) -> Optional[PageInfo]:
158
+ next_page = self.next_page
159
+ if not next_page:
160
+ return None
161
+
162
+ return PageInfo(params={"page": next_page})
163
+
164
+
165
+ class AsyncPageCursor(BaseAsyncPage[_T], BasePage[_T], Generic[_T]):
166
+ data: List[_T]
167
+ next_page: Optional[str] = None
168
+
169
+ @override
170
+ def _get_page_items(self) -> List[_T]:
171
+ data = self.data
172
+ if not data:
173
+ return []
174
+ return data
175
+
176
+ @override
177
+ def next_page_info(self) -> Optional[PageInfo]:
178
+ next_page = self.next_page
179
+ if not next_page:
180
+ return None
181
+
182
+ return PageInfo(params={"page": next_page})
data/miniconda3/lib/python3.13/site-packages/anthropic/py.typed ADDED
File without changes
data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/METADATA ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: anyio
3
+ Version: 4.13.0
4
+ Summary: High-level concurrency and networking framework on top of asyncio or Trio
5
+ Author-email: Alex Grönholm <alex.gronholm@nextday.fi>
6
+ License-Expression: MIT
7
+ Project-URL: Documentation, https://anyio.readthedocs.io/en/latest/
8
+ Project-URL: Changelog, https://anyio.readthedocs.io/en/stable/versionhistory.html
9
+ Project-URL: Source code, https://github.com/agronholm/anyio
10
+ Project-URL: Issue tracker, https://github.com/agronholm/anyio/issues
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Framework :: AnyIO
14
+ Classifier: Typing :: Typed
15
+ Classifier: Programming Language :: Python
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/x-rst
24
+ License-File: LICENSE
25
+ Requires-Dist: exceptiongroup>=1.0.2; python_version < "3.11"
26
+ Requires-Dist: idna>=2.8
27
+ Requires-Dist: typing_extensions>=4.5; python_version < "3.13"
28
+ Provides-Extra: trio
29
+ Requires-Dist: trio>=0.32.0; extra == "trio"
30
+ Dynamic: license-file
31
+
32
+ .. image:: https://github.com/agronholm/anyio/actions/workflows/test.yml/badge.svg
33
+ :target: https://github.com/agronholm/anyio/actions/workflows/test.yml
34
+ :alt: Build Status
35
+ .. image:: https://coveralls.io/repos/github/agronholm/anyio/badge.svg?branch=master
36
+ :target: https://coveralls.io/github/agronholm/anyio?branch=master
37
+ :alt: Code Coverage
38
+ .. image:: https://readthedocs.org/projects/anyio/badge/?version=latest
39
+ :target: https://anyio.readthedocs.io/en/latest/?badge=latest
40
+ :alt: Documentation
41
+ .. image:: https://badges.gitter.im/gitterHQ/gitter.svg
42
+ :target: https://gitter.im/python-trio/AnyIO
43
+ :alt: Gitter chat
44
+ .. image:: https://tidelift.com/badges/package/pypi/anyio
45
+ :target: https://tidelift.com/subscription/pkg/pypi-anyio
46
+ :alt: Tidelift
47
+
48
+ AnyIO is an asynchronous networking and concurrency library that works on top of either asyncio_ or
49
+ Trio_. It implements Trio-like `structured concurrency`_ (SC) on top of asyncio and works in harmony
50
+ with the native SC of Trio itself.
51
+
52
+ Applications and libraries written against AnyIO's API will run unmodified on either asyncio_ or
53
+ Trio_. AnyIO can also be adopted into a library or application incrementally – bit by bit, no full
54
+ refactoring necessary. It will blend in with the native libraries of your chosen backend.
55
+
56
+ To find out why you might want to use AnyIO's APIs instead of asyncio's, you can read about it
57
+ `here <https://anyio.readthedocs.io/en/stable/why.html>`_.
58
+
59
+ Documentation
60
+ -------------
61
+
62
+ View full documentation at: https://anyio.readthedocs.io/
63
+
64
+ Features
65
+ --------
66
+
67
+ AnyIO offers the following functionality:
68
+
69
+ * Task groups (nurseries_ in trio terminology)
70
+ * High-level networking (TCP, UDP and UNIX sockets)
71
+
72
+ * `Happy eyeballs`_ algorithm for TCP connections (more robust than that of asyncio on Python
73
+ 3.8)
74
+ * async/await style UDP sockets (unlike asyncio where you still have to use Transports and
75
+ Protocols)
76
+
77
+ * A versatile API for byte streams and object streams
78
+ * Inter-task synchronization and communication (locks, conditions, events, semaphores, object
79
+ streams)
80
+ * Worker threads
81
+ * Subprocesses
82
+ * Subinterpreter support for code parallelization (on Python 3.13 and later)
83
+ * Asynchronous file I/O (using worker threads)
84
+ * Signal handling
85
+ * Asynchronous version of the functools_ module
86
+
87
+ AnyIO also comes with its own pytest_ plugin which also supports asynchronous fixtures.
88
+ It even works with the popular Hypothesis_ library.
89
+
90
+ .. _asyncio: https://docs.python.org/3/library/asyncio.html
91
+ .. _Trio: https://github.com/python-trio/trio
92
+ .. _structured concurrency: https://en.wikipedia.org/wiki/Structured_concurrency
93
+ .. _nurseries: https://trio.readthedocs.io/en/stable/reference-core.html#nurseries-and-spawning
94
+ .. _Happy eyeballs: https://en.wikipedia.org/wiki/Happy_Eyeballs
95
+ .. _pytest: https://docs.pytest.org/en/latest/
96
+ .. _functools: https://docs.python.org/3/library/functools.html
97
+ .. _Hypothesis: https://hypothesis.works/
98
+
99
+ Security contact information
100
+ ----------------------------
101
+
102
+ To report a security vulnerability, please use the `Tidelift security contact`_.
103
+ Tidelift will coordinate the fix and disclosure.
104
+
105
+ .. _Tidelift security contact: https://tidelift.com/security
data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/RECORD ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ anyio-4.13.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ anyio-4.13.0.dist-info/METADATA,sha256=F0EYfiPlmTRwmJN2JktNxJg1GNnl0wHhzOWmz7pFvjM,4513
3
+ anyio-4.13.0.dist-info/RECORD,,
4
+ anyio-4.13.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
5
+ anyio-4.13.0.dist-info/entry_points.txt,sha256=_d6Yu6uiaZmNe0CydowirE9Cmg7zUL2g08tQpoS3Qvc,39
6
+ anyio-4.13.0.dist-info/licenses/LICENSE,sha256=U2GsncWPLvX9LpsJxoKXwX8ElQkJu8gCO9uC6s8iwrA,1081
7
+ anyio-4.13.0.dist-info/top_level.txt,sha256=QglSMiWX8_5dpoVAEIHdEYzvqFMdSYWmCj6tYw2ITkQ,6
8
+ anyio/__init__.py,sha256=7iDVqMUprUuKNY91FuoKqayAhR-OY136YDPI6P78HHk,6170
9
+ anyio/__pycache__/__init__.cpython-313.pyc,,
10
+ anyio/__pycache__/from_thread.cpython-313.pyc,,
11
+ anyio/__pycache__/functools.cpython-313.pyc,,
12
+ anyio/__pycache__/lowlevel.cpython-313.pyc,,
13
+ anyio/__pycache__/pytest_plugin.cpython-313.pyc,,
14
+ anyio/__pycache__/to_interpreter.cpython-313.pyc,,
15
+ anyio/__pycache__/to_process.cpython-313.pyc,,
16
+ anyio/__pycache__/to_thread.cpython-313.pyc,,
17
+ anyio/_backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
+ anyio/_backends/__pycache__/__init__.cpython-313.pyc,,
19
+ anyio/_backends/__pycache__/_asyncio.cpython-313.pyc,,
20
+ anyio/_backends/__pycache__/_trio.cpython-313.pyc,,
21
+ anyio/_backends/_asyncio.py,sha256=kuqlg2sBUsFdgY80xSDAw60Gx_4WNCl9iSL5XlY6lCU,99476
22
+ anyio/_backends/_trio.py,sha256=l9U-TsKRxzmTQxSMvOhn0bNeFn_iRx3Ho30jvR5Bdu0,41366
23
+ anyio/_core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
24
+ anyio/_core/__pycache__/__init__.cpython-313.pyc,,
25
+ anyio/_core/__pycache__/_asyncio_selector_thread.cpython-313.pyc,,
26
+ anyio/_core/__pycache__/_contextmanagers.cpython-313.pyc,,
27
+ anyio/_core/__pycache__/_eventloop.cpython-313.pyc,,
28
+ anyio/_core/__pycache__/_exceptions.cpython-313.pyc,,
29
+ anyio/_core/__pycache__/_fileio.cpython-313.pyc,,
30
+ anyio/_core/__pycache__/_resources.cpython-313.pyc,,
31
+ anyio/_core/__pycache__/_signals.cpython-313.pyc,,
32
+ anyio/_core/__pycache__/_sockets.cpython-313.pyc,,
33
+ anyio/_core/__pycache__/_streams.cpython-313.pyc,,
34
+ anyio/_core/__pycache__/_subprocesses.cpython-313.pyc,,
35
+ anyio/_core/__pycache__/_synchronization.cpython-313.pyc,,
36
+ anyio/_core/__pycache__/_tasks.cpython-313.pyc,,
37
+ anyio/_core/__pycache__/_tempfile.cpython-313.pyc,,
38
+ anyio/_core/__pycache__/_testing.cpython-313.pyc,,
39
+ anyio/_core/__pycache__/_typedattr.cpython-313.pyc,,
40
+ anyio/_core/_asyncio_selector_thread.py,sha256=2PdxFM3cs02Kp6BSppbvmRT7q7asreTW5FgBxEsflBo,5626
41
+ anyio/_core/_contextmanagers.py,sha256=YInBCabiEeS-UaP_Jdxa1CaFC71ETPW8HZTHIM8Rsc8,7215
42
+ anyio/_core/_eventloop.py,sha256=c2EdcBX-xnKwxPcC4Pjn3_qG9I-x4IWFO2R9RqCGjM4,6448
43
+ anyio/_core/_exceptions.py,sha256=Y3aq-Wxd7Q2HqwSg7nZPvRsHEuGazv_qeet6gqEBdPk,4407
44
+ anyio/_core/_fileio.py,sha256=CKi1gFNiW2G4knWeBE7He7-rptQwgYjDUWfG8DSlvLs,25665
45
+ anyio/_core/_resources.py,sha256=NbmU5O5UX3xEyACnkmYX28Fmwdl-f-ny0tHym26e0w0,435
46
+ anyio/_core/_signals.py,sha256=mjTBB2hTKNPRlU0IhnijeQedpWOGERDiMjSlJQsFrug,1016
47
+ anyio/_core/_sockets.py,sha256=RBXHcUqZt5gg_-OOfgHVv8uq2FSKk1uVUzTdpjBoI1o,34977
48
+ anyio/_core/_streams.py,sha256=FczFwIgDpnkK0bODWJXMpsUJYdvAD04kaUaGzJU8DK0,1806
49
+ anyio/_core/_subprocesses.py,sha256=tkmkPKEkEaiMD8C9WRZBlmgjOYRDRbZdte6e-unay2E,7916
50
+ anyio/_core/_synchronization.py,sha256=9G3fvRsPNrrWJ_Z6gD_80wXq8I8qgAyhwM8PvHQnT2c,21061
51
+ anyio/_core/_tasks.py,sha256=pVB7K6AAulzUM8YgXAeqNZG44nSyZ1bYJjH8GznC00I,5435
52
+ anyio/_core/_tempfile.py,sha256=jE2w59FRF3yRo4vjkjfZF2YcqsBZvc66VWRwrJGDYGk,19624
53
+ anyio/_core/_testing.py,sha256=u7MPqGXwpTxqI7hclSdNA30z2GH1Nw258uwKvy_RfBg,2340
54
+ anyio/_core/_typedattr.py,sha256=P4ozZikn3-DbpoYcvyghS_FOYAgbmUxeoU8-L_07pZM,2508
55
+ anyio/abc/__init__.py,sha256=6mWhcl_pGXhrgZVHP_TCfMvIXIOp9mroEFM90fYCU_U,2869
56
+ anyio/abc/__pycache__/__init__.cpython-313.pyc,,
57
+ anyio/abc/__pycache__/_eventloop.cpython-313.pyc,,
58
+ anyio/abc/__pycache__/_resources.cpython-313.pyc,,
59
+ anyio/abc/__pycache__/_sockets.cpython-313.pyc,,
60
+ anyio/abc/__pycache__/_streams.cpython-313.pyc,,
61
+ anyio/abc/__pycache__/_subprocesses.cpython-313.pyc,,
62
+ anyio/abc/__pycache__/_tasks.cpython-313.pyc,,
63
+ anyio/abc/__pycache__/_testing.cpython-313.pyc,,
64
+ anyio/abc/_eventloop.py,sha256=39lYnmtvoHaZw22sWBKOTA_zv7bamOnr8O49PqgDXdw,10629
65
+ anyio/abc/_resources.py,sha256=DrYvkNN1hH6Uvv5_5uKySvDsnknGVDe8FCKfko0VtN8,783
66
+ anyio/abc/_sockets.py,sha256=OmVDrfemVvF9c5K1tpBgQyV6fn5v0XyCExLAqBOGz9o,13124
67
+ anyio/abc/_streams.py,sha256=HYvna1iZbWcwLROTO6IhLX79RTRLPShZMWe0sG1q54I,7481
68
+ anyio/abc/_subprocesses.py,sha256=cumAPJTktOQtw63IqG0lDpyZqu_l1EElvQHMiwJgL08,2067
69
+ anyio/abc/_tasks.py,sha256=KC7wrciE48AINOI-AhPutnFhe1ewfP7QnamFlDzqesQ,3721
70
+ anyio/abc/_testing.py,sha256=tBJUzkSfOXJw23fe8qSJ03kJlShOYjjaEyFB6k6MYT8,1821
71
+ anyio/from_thread.py,sha256=L-0w1HxJ6BSb-KuVi57k5Tkc3yzQrx3QK5tAxMPcY-0,19141
72
+ anyio/functools.py,sha256=5AWM1iYTKkTzptvUhQDdLSh5GvbBW-vcs-SAUfIfA9A,12076
73
+ anyio/lowlevel.py,sha256=AyKLVK3LaWSoK39LkCKxE4_GDMLKZBNqTrLUgk63y80,5158
74
+ anyio/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
75
+ anyio/pytest_plugin.py,sha256=t6h4KJstqIxfxwTZ1YO8vpUVuB99nfCLltn0NHfatHo,12775
76
+ anyio/streams/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
77
+ anyio/streams/__pycache__/__init__.cpython-313.pyc,,
78
+ anyio/streams/__pycache__/buffered.cpython-313.pyc,,
79
+ anyio/streams/__pycache__/file.cpython-313.pyc,,
80
+ anyio/streams/__pycache__/memory.cpython-313.pyc,,
81
+ anyio/streams/__pycache__/stapled.cpython-313.pyc,,
82
+ anyio/streams/__pycache__/text.cpython-313.pyc,,
83
+ anyio/streams/__pycache__/tls.cpython-313.pyc,,
84
+ anyio/streams/buffered.py,sha256=2R3PeJhe4EXrdYqz44Y6-Eg9R6DrmlsYrP36Ir43-po,6263
85
+ anyio/streams/file.py,sha256=msnrotVKGMQomUu_Rj2qz9MvIdUp6d3JGr7MOEO8kV4,4428
86
+ anyio/streams/memory.py,sha256=F0zwzvFJKAhX_LRZGoKzzqDC2oMM-f-yyTBrEYEGOaU,10740
87
+ anyio/streams/stapled.py,sha256=T8Xqwf8K6EgURPxbt1N4i7A8BAk-gScv-GRhjLXIf_o,4390
88
+ anyio/streams/text.py,sha256=BcVAGJw1VRvtIqnv-o0Rb0pwH7p8vwlvl21xHq522ag,5765
89
+ anyio/streams/tls.py,sha256=DQVkXUvsTEYKkBO8dlVU7j_5H8QOtLy4sGi1Wrjqevo,15303
90
+ anyio/to_interpreter.py,sha256=_mLngrMy97TMR6VbW4Y6YzDUk9ZuPcQMPlkuyRh3C9k,7100
91
+ anyio/to_process.py,sha256=J7gAA_YOuoHqnpDAf5fm1Qu6kOmTzdFbiDNvnV755vk,9798
92
+ anyio/to_thread.py,sha256=f6h_k2d743GBv9FhAnhM_YpTvWgIrzBy9cOE0eJ1UJw,2693
data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/entry_points.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [pytest11]
2
+ anyio = anyio.pytest_plugin
data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ anyio
data/miniconda3/lib/python3.13/site-packages/charset_normalizer/__init__.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Charset-Normalizer
3
+ ~~~~~~~~~~~~~~
4
+ The Real First Universal Charset Detector.
5
+ A library that helps you read text from an unknown charset encoding.
6
+ Motivated by chardet, This package is trying to resolve the issue by taking a new approach.
7
+ All IANA character set names for which the Python core library provides codecs are supported.
8
+
9
+ Basic usage:
10
+ >>> from charset_normalizer import from_bytes
11
+ >>> results = from_bytes('Bсеки човек има право на образование. Oбразованието!'.encode('utf_8'))
12
+ >>> best_guess = results.best()
13
+ >>> str(best_guess)
14
+ 'Bсеки човек има право на образование. Oбразованието!'
15
+
16
+ Others methods and usages are available - see the full documentation
17
+ at <https://github.com/Ousret/charset_normalizer>.
18
+ :copyright: (c) 2021 by Ahmed TAHRI
19
+ :license: MIT, see LICENSE for more details.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import logging
25
+
26
+ from .api import from_bytes, from_fp, from_path, is_binary
27
+ from .legacy import detect
28
+ from .models import CharsetMatch, CharsetMatches
29
+ from .utils import set_logging_handler
30
+ from .version import VERSION, __version__
31
+
32
+ __all__ = (
33
+ "from_fp",
34
+ "from_path",
35
+ "from_bytes",
36
+ "is_binary",
37
+ "detect",
38
+ "CharsetMatch",
39
+ "CharsetMatches",
40
+ "__version__",
41
+ "VERSION",
42
+ "set_logging_handler",
43
+ )
44
+
45
+ # Attach a NullHandler to the top level logger by default
46
+ # https://docs.python.org/3.3/howto/logging.html#configuring-logging-for-a-library
47
+
48
+ logging.getLogger("charset_normalizer").addHandler(logging.NullHandler())
data/miniconda3/lib/python3.13/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/miniconda3/lib/python3.13/site-packages/charset_normalizer/api.py ADDED
@@ -0,0 +1,669 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from os import PathLike
5
+ from typing import BinaryIO
6
+
7
+ from .cd import (
8
+ coherence_ratio,
9
+ encoding_languages,
10
+ mb_encoding_languages,
11
+ merge_coherence_ratios,
12
+ )
13
+ from .constant import IANA_SUPPORTED, TOO_BIG_SEQUENCE, TOO_SMALL_SEQUENCE, TRACE
14
+ from .md import mess_ratio
15
+ from .models import CharsetMatch, CharsetMatches
16
+ from .utils import (
17
+ any_specified_encoding,
18
+ cut_sequence_chunks,
19
+ iana_name,
20
+ identify_sig_or_bom,
21
+ is_cp_similar,
22
+ is_multi_byte_encoding,
23
+ should_strip_sig_or_bom,
24
+ )
25
+
26
+ logger = logging.getLogger("charset_normalizer")
27
+ explain_handler = logging.StreamHandler()
28
+ explain_handler.setFormatter(
29
+ logging.Formatter("%(asctime)s | %(levelname)s | %(message)s")
30
+ )
31
+
32
+
33
+ def from_bytes(
34
+ sequences: bytes | bytearray,
35
+ steps: int = 5,
36
+ chunk_size: int = 512,
37
+ threshold: float = 0.2,
38
+ cp_isolation: list[str] | None = None,
39
+ cp_exclusion: list[str] | None = None,
40
+ preemptive_behaviour: bool = True,
41
+ explain: bool = False,
42
+ language_threshold: float = 0.1,
43
+ enable_fallback: bool = True,
44
+ ) -> CharsetMatches:
45
+ """
46
+ Given a raw bytes sequence, return the best possibles charset usable to render str objects.
47
+ If there is no results, it is a strong indicator that the source is binary/not text.
48
+ By default, the process will extract 5 blocks of 512o each to assess the mess and coherence of a given sequence.
49
+ And will give up a particular code page after 20% of measured mess. Those criteria are customizable at will.
50
+
51
+ The preemptive behavior DOES NOT replace the traditional detection workflow, it prioritize a particular code page
52
+ but never take it for granted. Can improve the performance.
53
+
54
+ You may want to focus your attention to some code page or/and not others, use cp_isolation and cp_exclusion for that
55
+ purpose.
56
+
57
+ This function will strip the SIG in the payload/sequence every time except on UTF-16, UTF-32.
58
+ By default the library does not setup any handler other than the NullHandler, if you choose to set the 'explain'
59
+ toggle to True it will alter the logger configuration to add a StreamHandler that is suitable for debugging.
60
+ Custom logging format and handler can be set manually.
61
+ """
62
+
63
+ if not isinstance(sequences, (bytearray, bytes)):
64
+ raise TypeError(
65
+ "Expected object of type bytes or bytearray, got: {}".format(
66
+ type(sequences)
67
+ )
68
+ )
69
+
70
+ if explain:
71
+ previous_logger_level: int = logger.level
72
+ logger.addHandler(explain_handler)
73
+ logger.setLevel(TRACE)
74
+
75
+ length: int = len(sequences)
76
+
77
+ if length == 0:
78
+ logger.debug("Encoding detection on empty bytes, assuming utf_8 intention.")
79
+ if explain: # Defensive: ensure exit path clean handler
80
+ logger.removeHandler(explain_handler)
81
+ logger.setLevel(previous_logger_level or logging.WARNING)
82
+ return CharsetMatches([CharsetMatch(sequences, "utf_8", 0.0, False, [], "")])
83
+
84
+ if cp_isolation is not None:
85
+ logger.log(
86
+ TRACE,
87
+ "cp_isolation is set. use this flag for debugging purpose. "
88
+ "limited list of encoding allowed : %s.",
89
+ ", ".join(cp_isolation),
90
+ )
91
+ cp_isolation = [iana_name(cp, False) for cp in cp_isolation]
92
+ else:
93
+ cp_isolation = []
94
+
95
+ if cp_exclusion is not None:
96
+ logger.log(
97
+ TRACE,
98
+ "cp_exclusion is set. use this flag for debugging purpose. "
99
+ "limited list of encoding excluded : %s.",
100
+ ", ".join(cp_exclusion),
101
+ )
102
+ cp_exclusion = [iana_name(cp, False) for cp in cp_exclusion]
103
+ else:
104
+ cp_exclusion = []
105
+
106
+ if length <= (chunk_size * steps):
107
+ logger.log(
108
+ TRACE,
109
+ "override steps (%i) and chunk_size (%i) as content does not fit (%i byte(s) given) parameters.",
110
+ steps,
111
+ chunk_size,
112
+ length,
113
+ )
114
+ steps = 1
115
+ chunk_size = length
116
+
117
+ if steps > 1 and length / steps < chunk_size:
118
+ chunk_size = int(length / steps)
119
+
120
+ is_too_small_sequence: bool = len(sequences) < TOO_SMALL_SEQUENCE
121
+ is_too_large_sequence: bool = len(sequences) >= TOO_BIG_SEQUENCE
122
+
123
+ if is_too_small_sequence:
124
+ logger.log(
125
+ TRACE,
126
+ "Trying to detect encoding from a tiny portion of ({}) byte(s).".format(
127
+ length
128
+ ),
129
+ )
130
+ elif is_too_large_sequence:
131
+ logger.log(
132
+ TRACE,
133
+ "Using lazy str decoding because the payload is quite large, ({}) byte(s).".format(
134
+ length
135
+ ),
136
+ )
137
+
138
+ prioritized_encodings: list[str] = []
139
+
140
+ specified_encoding: str | None = (
141
+ any_specified_encoding(sequences) if preemptive_behaviour else None
142
+ )
143
+
144
+ if specified_encoding is not None:
145
+ prioritized_encodings.append(specified_encoding)
146
+ logger.log(
147
+ TRACE,
148
+ "Detected declarative mark in sequence. Priority +1 given for %s.",
149
+ specified_encoding,
150
+ )
151
+
152
+ tested: set[str] = set()
153
+ tested_but_hard_failure: list[str] = []
154
+ tested_but_soft_failure: list[str] = []
155
+
156
+ fallback_ascii: CharsetMatch | None = None
157
+ fallback_u8: CharsetMatch | None = None
158
+ fallback_specified: CharsetMatch | None = None
159
+
160
+ results: CharsetMatches = CharsetMatches()
161
+
162
+ early_stop_results: CharsetMatches = CharsetMatches()
163
+
164
+ sig_encoding, sig_payload = identify_sig_or_bom(sequences)
165
+
166
+ if sig_encoding is not None:
167
+ prioritized_encodings.append(sig_encoding)
168
+ logger.log(
169
+ TRACE,
170
+ "Detected a SIG or BOM mark on first %i byte(s). Priority +1 given for %s.",
171
+ len(sig_payload),
172
+ sig_encoding,
173
+ )
174
+
175
+ prioritized_encodings.append("ascii")
176
+
177
+ if "utf_8" not in prioritized_encodings:
178
+ prioritized_encodings.append("utf_8")
179
+
180
+ for encoding_iana in prioritized_encodings + IANA_SUPPORTED:
181
+ if cp_isolation and encoding_iana not in cp_isolation:
182
+ continue
183
+
184
+ if cp_exclusion and encoding_iana in cp_exclusion:
185
+ continue
186
+
187
+ if encoding_iana in tested:
188
+ continue
189
+
190
+ tested.add(encoding_iana)
191
+
192
+ decoded_payload: str | None = None
193
+ bom_or_sig_available: bool = sig_encoding == encoding_iana
194
+ strip_sig_or_bom: bool = bom_or_sig_available and should_strip_sig_or_bom(
195
+ encoding_iana
196
+ )
197
+
198
+ if encoding_iana in {"utf_16", "utf_32"} and not bom_or_sig_available:
199
+ logger.log(
200
+ TRACE,
201
+ "Encoding %s won't be tested as-is because it require a BOM. Will try some sub-encoder LE/BE.",
202
+ encoding_iana,
203
+ )
204
+ continue
205
+ if encoding_iana in {"utf_7"} and not bom_or_sig_available:
206
+ logger.log(
207
+ TRACE,
208
+ "Encoding %s won't be tested as-is because detection is unreliable without BOM/SIG.",
209
+ encoding_iana,
210
+ )
211
+ continue
212
+
213
+ try:
214
+ is_multi_byte_decoder: bool = is_multi_byte_encoding(encoding_iana)
215
+ except (ModuleNotFoundError, ImportError):
216
+ logger.log(
217
+ TRACE,
218
+ "Encoding %s does not provide an IncrementalDecoder",
219
+ encoding_iana,
220
+ )
221
+ continue
222
+
223
+ try:
224
+ if is_too_large_sequence and is_multi_byte_decoder is False:
225
+ str(
226
+ (
227
+ sequences[: int(50e4)]
228
+ if strip_sig_or_bom is False
229
+ else sequences[len(sig_payload) : int(50e4)]
230
+ ),
231
+ encoding=encoding_iana,
232
+ )
233
+ else:
234
+ decoded_payload = str(
235
+ (
236
+ sequences
237
+ if strip_sig_or_bom is False
238
+ else sequences[len(sig_payload) :]
239
+ ),
240
+ encoding=encoding_iana,
241
+ )
242
+ except (UnicodeDecodeError, LookupError) as e:
243
+ if not isinstance(e, LookupError):
244
+ logger.log(
245
+ TRACE,
246
+ "Code page %s does not fit given bytes sequence at ALL. %s",
247
+ encoding_iana,
248
+ str(e),
249
+ )
250
+ tested_but_hard_failure.append(encoding_iana)
251
+ continue
252
+
253
+ similar_soft_failure_test: bool = False
254
+
255
+ for encoding_soft_failed in tested_but_soft_failure:
256
+ if is_cp_similar(encoding_iana, encoding_soft_failed):
257
+ similar_soft_failure_test = True
258
+ break
259
+
260
+ if similar_soft_failure_test:
261
+ logger.log(
262
+ TRACE,
263
+ "%s is deemed too similar to code page %s and was consider unsuited already. Continuing!",
264
+ encoding_iana,
265
+ encoding_soft_failed,
266
+ )
267
+ continue
268
+
269
+ r_ = range(
270
+ 0 if not bom_or_sig_available else len(sig_payload),
271
+ length,
272
+ int(length / steps),
273
+ )
274
+
275
+ multi_byte_bonus: bool = (
276
+ is_multi_byte_decoder
277
+ and decoded_payload is not None
278
+ and len(decoded_payload) < length
279
+ )
280
+
281
+ if multi_byte_bonus:
282
+ logger.log(
283
+ TRACE,
284
+ "Code page %s is a multi byte encoding table and it appear that at least one character "
285
+ "was encoded using n-bytes.",
286
+ encoding_iana,
287
+ )
288
+
289
+ max_chunk_gave_up: int = int(len(r_) / 4)
290
+
291
+ max_chunk_gave_up = max(max_chunk_gave_up, 2)
292
+ early_stop_count: int = 0
293
+ lazy_str_hard_failure = False
294
+
295
+ md_chunks: list[str] = []
296
+ md_ratios = []
297
+
298
+ try:
299
+ for chunk in cut_sequence_chunks(
300
+ sequences,
301
+ encoding_iana,
302
+ r_,
303
+ chunk_size,
304
+ bom_or_sig_available,
305
+ strip_sig_or_bom,
306
+ sig_payload,
307
+ is_multi_byte_decoder,
308
+ decoded_payload,
309
+ ):
310
+ md_chunks.append(chunk)
311
+
312
+ md_ratios.append(
313
+ mess_ratio(
314
+ chunk,
315
+ threshold,
316
+ explain is True and 1 <= len(cp_isolation) <= 2,
317
+ )
318
+ )
319
+
320
+ if md_ratios[-1] >= threshold:
321
+ early_stop_count += 1
322
+
323
+ if (early_stop_count >= max_chunk_gave_up) or (
324
+ bom_or_sig_available and strip_sig_or_bom is False
325
+ ):
326
+ break
327
+ except (
328
+ UnicodeDecodeError
329
+ ) as e: # Lazy str loading may have missed something there
330
+ logger.log(
331
+ TRACE,
332
+ "LazyStr Loading: After MD chunk decode, code page %s does not fit given bytes sequence at ALL. %s",
333
+ encoding_iana,
334
+ str(e),
335
+ )
336
+ early_stop_count = max_chunk_gave_up
337
+ lazy_str_hard_failure = True
338
+
339
+ # We might want to check the sequence again with the whole content
340
+ # Only if initial MD tests passes
341
+ if (
342
+ not lazy_str_hard_failure
343
+ and is_too_large_sequence
344
+ and not is_multi_byte_decoder
345
+ ):
346
+ try:
347
+ sequences[int(50e3) :].decode(encoding_iana, errors="strict")
348
+ except UnicodeDecodeError as e:
349
+ logger.log(
350
+ TRACE,
351
+ "LazyStr Loading: After final lookup, code page %s does not fit given bytes sequence at ALL. %s",
352
+ encoding_iana,
353
+ str(e),
354
+ )
355
+ tested_but_hard_failure.append(encoding_iana)
356
+ continue
357
+
358
+ mean_mess_ratio: float = sum(md_ratios) / len(md_ratios) if md_ratios else 0.0
359
+ if mean_mess_ratio >= threshold or early_stop_count >= max_chunk_gave_up:
360
+ tested_but_soft_failure.append(encoding_iana)
361
+ logger.log(
362
+ TRACE,
363
+ "%s was excluded because of initial chaos probing. Gave up %i time(s). "
364
+ "Computed mean chaos is %f %%.",
365
+ encoding_iana,
366
+ early_stop_count,
367
+ round(mean_mess_ratio * 100, ndigits=3),
368
+ )
369
+ # Preparing those fallbacks in case we got nothing.
370
+ if (
371
+ enable_fallback
372
+ and encoding_iana
373
+ in ["ascii", "utf_8", specified_encoding, "utf_16", "utf_32"]
374
+ and not lazy_str_hard_failure
375
+ ):
376
+ fallback_entry = CharsetMatch(
377
+ sequences,
378
+ encoding_iana,
379
+ threshold,
380
+ bom_or_sig_available,
381
+ [],
382
+ decoded_payload,
383
+ preemptive_declaration=specified_encoding,
384
+ )
385
+ if encoding_iana == specified_encoding:
386
+ fallback_specified = fallback_entry
387
+ elif encoding_iana == "ascii":
388
+ fallback_ascii = fallback_entry
389
+ else:
390
+ fallback_u8 = fallback_entry
391
+ continue
392
+
393
+ logger.log(
394
+ TRACE,
395
+ "%s passed initial chaos probing. Mean measured chaos is %f %%",
396
+ encoding_iana,
397
+ round(mean_mess_ratio * 100, ndigits=3),
398
+ )
399
+
400
+ if not is_multi_byte_decoder:
401
+ target_languages: list[str] = encoding_languages(encoding_iana)
402
+ else:
403
+ target_languages = mb_encoding_languages(encoding_iana)
404
+
405
+ if target_languages:
406
+ logger.log(
407
+ TRACE,
408
+ "{} should target any language(s) of {}".format(
409
+ encoding_iana, str(target_languages)
410
+ ),
411
+ )
412
+
413
+ cd_ratios = []
414
+
415
+ # We shall skip the CD when its about ASCII
416
+ # Most of the time its not relevant to run "language-detection" on it.
417
+ if encoding_iana != "ascii":
418
+ for chunk in md_chunks:
419
+ chunk_languages = coherence_ratio(
420
+ chunk,
421
+ language_threshold,
422
+ ",".join(target_languages) if target_languages else None,
423
+ )
424
+
425
+ cd_ratios.append(chunk_languages)
426
+
427
+ cd_ratios_merged = merge_coherence_ratios(cd_ratios)
428
+
429
+ if cd_ratios_merged:
430
+ logger.log(
431
+ TRACE,
432
+ "We detected language {} using {}".format(
433
+ cd_ratios_merged, encoding_iana
434
+ ),
435
+ )
436
+
437
+ current_match = CharsetMatch(
438
+ sequences,
439
+ encoding_iana,
440
+ mean_mess_ratio,
441
+ bom_or_sig_available,
442
+ cd_ratios_merged,
443
+ (
444
+ decoded_payload
445
+ if (
446
+ is_too_large_sequence is False
447
+ or encoding_iana in [specified_encoding, "ascii", "utf_8"]
448
+ )
449
+ else None
450
+ ),
451
+ preemptive_declaration=specified_encoding,
452
+ )
453
+
454
+ results.append(current_match)
455
+
456
+ if (
457
+ encoding_iana in [specified_encoding, "ascii", "utf_8"]
458
+ and mean_mess_ratio < 0.1
459
+ ):
460
+ # If md says nothing to worry about, then... stop immediately!
461
+ if mean_mess_ratio == 0.0:
462
+ logger.debug(
463
+ "Encoding detection: %s is most likely the one.",
464
+ current_match.encoding,
465
+ )
466
+ if explain: # Defensive: ensure exit path clean handler
467
+ logger.removeHandler(explain_handler)
468
+ logger.setLevel(previous_logger_level)
469
+ return CharsetMatches([current_match])
470
+
471
+ early_stop_results.append(current_match)
472
+
473
+ if (
474
+ len(early_stop_results)
475
+ and (specified_encoding is None or specified_encoding in tested)
476
+ and "ascii" in tested
477
+ and "utf_8" in tested
478
+ ):
479
+ probable_result: CharsetMatch = early_stop_results.best() # type: ignore[assignment]
480
+ logger.debug(
481
+ "Encoding detection: %s is most likely the one.",
482
+ probable_result.encoding,
483
+ )
484
+ if explain: # Defensive: ensure exit path clean handler
485
+ logger.removeHandler(explain_handler)
486
+ logger.setLevel(previous_logger_level)
487
+
488
+ return CharsetMatches([probable_result])
489
+
490
+ if encoding_iana == sig_encoding:
491
+ logger.debug(
492
+ "Encoding detection: %s is most likely the one as we detected a BOM or SIG within "
493
+ "the beginning of the sequence.",
494
+ encoding_iana,
495
+ )
496
+ if explain: # Defensive: ensure exit path clean handler
497
+ logger.removeHandler(explain_handler)
498
+ logger.setLevel(previous_logger_level)
499
+ return CharsetMatches([results[encoding_iana]])
500
+
501
+ if len(results) == 0:
502
+ if fallback_u8 or fallback_ascii or fallback_specified:
503
+ logger.log(
504
+ TRACE,
505
+ "Nothing got out of the detection process. Using ASCII/UTF-8/Specified fallback.",
506
+ )
507
+
508
+ if fallback_specified:
509
+ logger.debug(
510
+ "Encoding detection: %s will be used as a fallback match",
511
+ fallback_specified.encoding,
512
+ )
513
+ results.append(fallback_specified)
514
+ elif (
515
+ (fallback_u8 and fallback_ascii is None)
516
+ or (
517
+ fallback_u8
518
+ and fallback_ascii
519
+ and fallback_u8.fingerprint != fallback_ascii.fingerprint
520
+ )
521
+ or (fallback_u8 is not None)
522
+ ):
523
+ logger.debug("Encoding detection: utf_8 will be used as a fallback match")
524
+ results.append(fallback_u8)
525
+ elif fallback_ascii:
526
+ logger.debug("Encoding detection: ascii will be used as a fallback match")
527
+ results.append(fallback_ascii)
528
+
529
+ if results:
530
+ logger.debug(
531
+ "Encoding detection: Found %s as plausible (best-candidate) for content. With %i alternatives.",
532
+ results.best().encoding, # type: ignore
533
+ len(results) - 1,
534
+ )
535
+ else:
536
+ logger.debug("Encoding detection: Unable to determine any suitable charset.")
537
+
538
+ if explain:
539
+ logger.removeHandler(explain_handler)
540
+ logger.setLevel(previous_logger_level)
541
+
542
+ return results
543
+
544
+
545
+ def from_fp(
546
+ fp: BinaryIO,
547
+ steps: int = 5,
548
+ chunk_size: int = 512,
549
+ threshold: float = 0.20,
550
+ cp_isolation: list[str] | None = None,
551
+ cp_exclusion: list[str] | None = None,
552
+ preemptive_behaviour: bool = True,
553
+ explain: bool = False,
554
+ language_threshold: float = 0.1,
555
+ enable_fallback: bool = True,
556
+ ) -> CharsetMatches:
557
+ """
558
+ Same thing than the function from_bytes but using a file pointer that is already ready.
559
+ Will not close the file pointer.
560
+ """
561
+ return from_bytes(
562
+ fp.read(),
563
+ steps,
564
+ chunk_size,
565
+ threshold,
566
+ cp_isolation,
567
+ cp_exclusion,
568
+ preemptive_behaviour,
569
+ explain,
570
+ language_threshold,
571
+ enable_fallback,
572
+ )
573
+
574
+
575
+ def from_path(
576
+ path: str | bytes | PathLike, # type: ignore[type-arg]
577
+ steps: int = 5,
578
+ chunk_size: int = 512,
579
+ threshold: float = 0.20,
580
+ cp_isolation: list[str] | None = None,
581
+ cp_exclusion: list[str] | None = None,
582
+ preemptive_behaviour: bool = True,
583
+ explain: bool = False,
584
+ language_threshold: float = 0.1,
585
+ enable_fallback: bool = True,
586
+ ) -> CharsetMatches:
587
+ """
588
+ Same thing than the function from_bytes but with one extra step. Opening and reading given file path in binary mode.
589
+ Can raise IOError.
590
+ """
591
+ with open(path, "rb") as fp:
592
+ return from_fp(
593
+ fp,
594
+ steps,
595
+ chunk_size,
596
+ threshold,
597
+ cp_isolation,
598
+ cp_exclusion,
599
+ preemptive_behaviour,
600
+ explain,
601
+ language_threshold,
602
+ enable_fallback,
603
+ )
604
+
605
+
606
+ def is_binary(
607
+ fp_or_path_or_payload: PathLike | str | BinaryIO | bytes, # type: ignore[type-arg]
608
+ steps: int = 5,
609
+ chunk_size: int = 512,
610
+ threshold: float = 0.20,
611
+ cp_isolation: list[str] | None = None,
612
+ cp_exclusion: list[str] | None = None,
613
+ preemptive_behaviour: bool = True,
614
+ explain: bool = False,
615
+ language_threshold: float = 0.1,
616
+ enable_fallback: bool = False,
617
+ ) -> bool:
618
+ """
619
+ Detect if the given input (file, bytes, or path) points to a binary file. aka. not a string.
620
+ Based on the same main heuristic algorithms and default kwargs at the sole exception that fallbacks match
621
+ are disabled to be stricter around ASCII-compatible but unlikely to be a string.
622
+ """
623
+ if isinstance(fp_or_path_or_payload, (str, PathLike)):
624
+ guesses = from_path(
625
+ fp_or_path_or_payload,
626
+ steps=steps,
627
+ chunk_size=chunk_size,
628
+ threshold=threshold,
629
+ cp_isolation=cp_isolation,
630
+ cp_exclusion=cp_exclusion,
631
+ preemptive_behaviour=preemptive_behaviour,
632
+ explain=explain,
633
+ language_threshold=language_threshold,
634
+ enable_fallback=enable_fallback,
635
+ )
636
+ elif isinstance(
637
+ fp_or_path_or_payload,
638
+ (
639
+ bytes,
640
+ bytearray,
641
+ ),
642
+ ):
643
+ guesses = from_bytes(
644
+ fp_or_path_or_payload,
645
+ steps=steps,
646
+ chunk_size=chunk_size,
647
+ threshold=threshold,
648
+ cp_isolation=cp_isolation,
649
+ cp_exclusion=cp_exclusion,
650
+ preemptive_behaviour=preemptive_behaviour,
651
+ explain=explain,
652
+ language_threshold=language_threshold,
653
+ enable_fallback=enable_fallback,
654
+ )
655
+ else:
656
+ guesses = from_fp(
657
+ fp_or_path_or_payload,
658
+ steps=steps,
659
+ chunk_size=chunk_size,
660
+ threshold=threshold,
661
+ cp_isolation=cp_isolation,
662
+ cp_exclusion=cp_exclusion,
663
+ preemptive_behaviour=preemptive_behaviour,
664
+ explain=explain,
665
+ language_threshold=language_threshold,
666
+ enable_fallback=enable_fallback,
667
+ )
668
+
669
+ return not guesses
data/miniconda3/lib/python3.13/site-packages/charset_normalizer/cd.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import importlib
4
+ from codecs import IncrementalDecoder
5
+ from collections import Counter
6
+ from functools import lru_cache
7
+ from typing import Counter as TypeCounter
8
+
9
+ from .constant import (
10
+ FREQUENCIES,
11
+ KO_NAMES,
12
+ LANGUAGE_SUPPORTED_COUNT,
13
+ TOO_SMALL_SEQUENCE,
14
+ ZH_NAMES,
15
+ )
16
+ from .md import is_suspiciously_successive_range
17
+ from .models import CoherenceMatches
18
+ from .utils import (
19
+ is_accentuated,
20
+ is_latin,
21
+ is_multi_byte_encoding,
22
+ is_unicode_range_secondary,
23
+ unicode_range,
24
+ )
25
+
26
+
27
+ def encoding_unicode_range(iana_name: str) -> list[str]:
28
+ """
29
+ Return associated unicode ranges in a single byte code page.
30
+ """
31
+ if is_multi_byte_encoding(iana_name):
32
+ raise OSError("Function not supported on multi-byte code page")
33
+
34
+ decoder = importlib.import_module(f"encodings.{iana_name}").IncrementalDecoder
35
+
36
+ p: IncrementalDecoder = decoder(errors="ignore")
37
+ seen_ranges: dict[str, int] = {}
38
+ character_count: int = 0
39
+
40
+ for i in range(0x40, 0xFF):
41
+ chunk: str = p.decode(bytes([i]))
42
+
43
+ if chunk:
44
+ character_range: str | None = unicode_range(chunk)
45
+
46
+ if character_range is None:
47
+ continue
48
+
49
+ if is_unicode_range_secondary(character_range) is False:
50
+ if character_range not in seen_ranges:
51
+ seen_ranges[character_range] = 0
52
+ seen_ranges[character_range] += 1
53
+ character_count += 1
54
+
55
+ return sorted(
56
+ [
57
+ character_range
58
+ for character_range in seen_ranges
59
+ if seen_ranges[character_range] / character_count >= 0.15
60
+ ]
61
+ )
62
+
63
+
64
+ def unicode_range_languages(primary_range: str) -> list[str]:
65
+ """
66
+ Return inferred languages used with a unicode range.
67
+ """
68
+ languages: list[str] = []
69
+
70
+ for language, characters in FREQUENCIES.items():
71
+ for character in characters:
72
+ if unicode_range(character) == primary_range:
73
+ languages.append(language)
74
+ break
75
+
76
+ return languages
77
+
78
+
79
+ @lru_cache()
80
+ def encoding_languages(iana_name: str) -> list[str]:
81
+ """
82
+ Single-byte encoding language association. Some code page are heavily linked to particular language(s).
83
+ This function does the correspondence.
84
+ """
85
+ unicode_ranges: list[str] = encoding_unicode_range(iana_name)
86
+ primary_range: str | None = None
87
+
88
+ for specified_range in unicode_ranges:
89
+ if "Latin" not in specified_range:
90
+ primary_range = specified_range
91
+ break
92
+
93
+ if primary_range is None:
94
+ return ["Latin Based"]
95
+
96
+ return unicode_range_languages(primary_range)
97
+
98
+
99
+ @lru_cache()
100
+ def mb_encoding_languages(iana_name: str) -> list[str]:
101
+ """
102
+ Multi-byte encoding language association. Some code page are heavily linked to particular language(s).
103
+ This function does the correspondence.
104
+ """
105
+ if (
106
+ iana_name.startswith("shift_")
107
+ or iana_name.startswith("iso2022_jp")
108
+ or iana_name.startswith("euc_j")
109
+ or iana_name == "cp932"
110
+ ):
111
+ return ["Japanese"]
112
+ if iana_name.startswith("gb") or iana_name in ZH_NAMES:
113
+ return ["Chinese"]
114
+ if iana_name.startswith("iso2022_kr") or iana_name in KO_NAMES:
115
+ return ["Korean"]
116
+
117
+ return []
118
+
119
+
120
+ @lru_cache(maxsize=LANGUAGE_SUPPORTED_COUNT)
121
+ def get_target_features(language: str) -> tuple[bool, bool]:
122
+ """
123
+ Determine main aspects from a supported language if it contains accents and if is pure Latin.
124
+ """
125
+ target_have_accents: bool = False
126
+ target_pure_latin: bool = True
127
+
128
+ for character in FREQUENCIES[language]:
129
+ if not target_have_accents and is_accentuated(character):
130
+ target_have_accents = True
131
+ if target_pure_latin and is_latin(character) is False:
132
+ target_pure_latin = False
133
+
134
+ return target_have_accents, target_pure_latin
135
+
136
+
137
+ def alphabet_languages(
138
+ characters: list[str], ignore_non_latin: bool = False
139
+ ) -> list[str]:
140
+ """
141
+ Return associated languages associated to given characters.
142
+ """
143
+ languages: list[tuple[str, float]] = []
144
+
145
+ source_have_accents = any(is_accentuated(character) for character in characters)
146
+
147
+ for language, language_characters in FREQUENCIES.items():
148
+ target_have_accents, target_pure_latin = get_target_features(language)
149
+
150
+ if ignore_non_latin and target_pure_latin is False:
151
+ continue
152
+
153
+ if target_have_accents is False and source_have_accents:
154
+ continue
155
+
156
+ character_count: int = len(language_characters)
157
+
158
+ character_match_count: int = len(
159
+ [c for c in language_characters if c in characters]
160
+ )
161
+
162
+ ratio: float = character_match_count / character_count
163
+
164
+ if ratio >= 0.2:
165
+ languages.append((language, ratio))
166
+
167
+ languages = sorted(languages, key=lambda x: x[1], reverse=True)
168
+
169
+ return [compatible_language[0] for compatible_language in languages]
170
+
171
+
172
+ def characters_popularity_compare(
173
+ language: str, ordered_characters: list[str]
174
+ ) -> float:
175
+ """
176
+ Determine if a ordered characters list (by occurrence from most appearance to rarest) match a particular language.
177
+ The result is a ratio between 0. (absolutely no correspondence) and 1. (near perfect fit).
178
+ Beware that is function is not strict on the match in order to ease the detection. (Meaning close match is 1.)
179
+ """
180
+ if language not in FREQUENCIES:
181
+ raise ValueError(f"{language} not available")
182
+
183
+ character_approved_count: int = 0
184
+ FREQUENCIES_language_set = set(FREQUENCIES[language])
185
+
186
+ ordered_characters_count: int = len(ordered_characters)
187
+ target_language_characters_count: int = len(FREQUENCIES[language])
188
+
189
+ large_alphabet: bool = target_language_characters_count > 26
190
+
191
+ for character, character_rank in zip(
192
+ ordered_characters, range(0, ordered_characters_count)
193
+ ):
194
+ if character not in FREQUENCIES_language_set:
195
+ continue
196
+
197
+ character_rank_in_language: int = FREQUENCIES[language].index(character)
198
+ expected_projection_ratio: float = (
199
+ target_language_characters_count / ordered_characters_count
200
+ )
201
+ character_rank_projection: int = int(character_rank * expected_projection_ratio)
202
+
203
+ if (
204
+ large_alphabet is False
205
+ and abs(character_rank_projection - character_rank_in_language) > 4
206
+ ):
207
+ continue
208
+
209
+ if (
210
+ large_alphabet is True
211
+ and abs(character_rank_projection - character_rank_in_language)
212
+ < target_language_characters_count / 3
213
+ ):
214
+ character_approved_count += 1
215
+ continue
216
+
217
+ characters_before_source: list[str] = FREQUENCIES[language][
218
+ 0:character_rank_in_language
219
+ ]
220
+ characters_after_source: list[str] = FREQUENCIES[language][
221
+ character_rank_in_language:
222
+ ]
223
+ characters_before: list[str] = ordered_characters[0:character_rank]
224
+ characters_after: list[str] = ordered_characters[character_rank:]
225
+
226
+ before_match_count: int = len(
227
+ set(characters_before) & set(characters_before_source)
228
+ )
229
+
230
+ after_match_count: int = len(
231
+ set(characters_after) & set(characters_after_source)
232
+ )
233
+
234
+ if len(characters_before_source) == 0 and before_match_count <= 4:
235
+ character_approved_count += 1
236
+ continue
237
+
238
+ if len(characters_after_source) == 0 and after_match_count <= 4:
239
+ character_approved_count += 1
240
+ continue
241
+
242
+ if (
243
+ before_match_count / len(characters_before_source) >= 0.4
244
+ or after_match_count / len(characters_after_source) >= 0.4
245
+ ):
246
+ character_approved_count += 1
247
+ continue
248
+
249
+ return character_approved_count / len(ordered_characters)
250
+
251
+
252
+ def alpha_unicode_split(decoded_sequence: str) -> list[str]:
253
+ """
254
+ Given a decoded text sequence, return a list of str. Unicode range / alphabet separation.
255
+ Ex. a text containing English/Latin with a bit a Hebrew will return two items in the resulting list;
256
+ One containing the latin letters and the other hebrew.
257
+ """
258
+ layers: dict[str, str] = {}
259
+
260
+ for character in decoded_sequence:
261
+ if character.isalpha() is False:
262
+ continue
263
+
264
+ character_range: str | None = unicode_range(character)
265
+
266
+ if character_range is None:
267
+ continue
268
+
269
+ layer_target_range: str | None = None
270
+
271
+ for discovered_range in layers:
272
+ if (
273
+ is_suspiciously_successive_range(discovered_range, character_range)
274
+ is False
275
+ ):
276
+ layer_target_range = discovered_range
277
+ break
278
+
279
+ if layer_target_range is None:
280
+ layer_target_range = character_range
281
+
282
+ if layer_target_range not in layers:
283
+ layers[layer_target_range] = character.lower()
284
+ continue
285
+
286
+ layers[layer_target_range] += character.lower()
287
+
288
+ return list(layers.values())
289
+
290
+
291
+ def merge_coherence_ratios(results: list[CoherenceMatches]) -> CoherenceMatches:
292
+ """
293
+ This function merge results previously given by the function coherence_ratio.
294
+ The return type is the same as coherence_ratio.
295
+ """
296
+ per_language_ratios: dict[str, list[float]] = {}
297
+ for result in results:
298
+ for sub_result in result:
299
+ language, ratio = sub_result
300
+ if language not in per_language_ratios:
301
+ per_language_ratios[language] = [ratio]
302
+ continue
303
+ per_language_ratios[language].append(ratio)
304
+
305
+ merge = [
306
+ (
307
+ language,
308
+ round(
309
+ sum(per_language_ratios[language]) / len(per_language_ratios[language]),
310
+ 4,
311
+ ),
312
+ )
313
+ for language in per_language_ratios
314
+ ]
315
+
316
+ return sorted(merge, key=lambda x: x[1], reverse=True)
317
+
318
+
319
+ def filter_alt_coherence_matches(results: CoherenceMatches) -> CoherenceMatches:
320
+ """
321
+ We shall NOT return "English—" in CoherenceMatches because it is an alternative
322
+ of "English". This function only keeps the best match and remove the em-dash in it.
323
+ """
324
+ index_results: dict[str, list[float]] = dict()
325
+
326
+ for result in results:
327
+ language, ratio = result
328
+ no_em_name: str = language.replace("—", "")
329
+
330
+ if no_em_name not in index_results:
331
+ index_results[no_em_name] = []
332
+
333
+ index_results[no_em_name].append(ratio)
334
+
335
+ if any(len(index_results[e]) > 1 for e in index_results):
336
+ filtered_results: CoherenceMatches = []
337
+
338
+ for language in index_results:
339
+ filtered_results.append((language, max(index_results[language])))
340
+
341
+ return filtered_results
342
+
343
+ return results
344
+
345
+
346
+ @lru_cache(maxsize=2048)
347
+ def coherence_ratio(
348
+ decoded_sequence: str, threshold: float = 0.1, lg_inclusion: str | None = None
349
+ ) -> CoherenceMatches:
350
+ """
351
+ Detect ANY language that can be identified in given sequence. The sequence will be analysed by layers.
352
+ A layer = Character extraction by alphabets/ranges.
353
+ """
354
+
355
+ results: list[tuple[str, float]] = []
356
+ ignore_non_latin: bool = False
357
+
358
+ sufficient_match_count: int = 0
359
+
360
+ lg_inclusion_list = lg_inclusion.split(",") if lg_inclusion is not None else []
361
+ if "Latin Based" in lg_inclusion_list:
362
+ ignore_non_latin = True
363
+ lg_inclusion_list.remove("Latin Based")
364
+
365
+ for layer in alpha_unicode_split(decoded_sequence):
366
+ sequence_frequencies: TypeCounter[str] = Counter(layer)
367
+ most_common = sequence_frequencies.most_common()
368
+
369
+ character_count: int = sum(o for c, o in most_common)
370
+
371
+ if character_count <= TOO_SMALL_SEQUENCE:
372
+ continue
373
+
374
+ popular_character_ordered: list[str] = [c for c, o in most_common]
375
+
376
+ for language in lg_inclusion_list or alphabet_languages(
377
+ popular_character_ordered, ignore_non_latin
378
+ ):
379
+ ratio: float = characters_popularity_compare(
380
+ language, popular_character_ordered
381
+ )
382
+
383
+ if ratio < threshold:
384
+ continue
385
+ elif ratio >= 0.8:
386
+ sufficient_match_count += 1
387
+
388
+ results.append((language, round(ratio, 4)))
389
+
390
+ if sufficient_match_count >= 3:
391
+ break
392
+
393
+ return sorted(
394
+ filter_alt_coherence_matches(results), key=lambda x: x[1], reverse=True
395
+ )
data/miniconda3/lib/python3.13/site-packages/charset_normalizer/constant.py ADDED
@@ -0,0 +1,2015 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ b"\x2b\x2f\x76\x38\x2d",
17
+ ],
18
+ "gb18030": b"\x84\x31\x95\x33",
19
+ "utf_32": [BOM_UTF32_BE, BOM_UTF32_LE],
20
+ "utf_16": [BOM_UTF16_BE, BOM_UTF16_LE],
21
+ }
22
+
23
+ TOO_SMALL_SEQUENCE: int = 32
24
+ TOO_BIG_SEQUENCE: int = int(10e6)
25
+
26
+ UTF8_MAXIMAL_ALLOCATION: int = 1_112_064
27
+
28
+ # Up-to-date Unicode ucd/15.0.0
29
+ UNICODE_RANGES_COMBINED: dict[str, range] = {
30
+ "Control character": range(32),
31
+ "Basic Latin": range(32, 128),
32
+ "Latin-1 Supplement": range(128, 256),
33
+ "Latin Extended-A": range(256, 384),
34
+ "Latin Extended-B": range(384, 592),
35
+ "IPA Extensions": range(592, 688),
36
+ "Spacing Modifier Letters": range(688, 768),
37
+ "Combining Diacritical Marks": range(768, 880),
38
+ "Greek and Coptic": range(880, 1024),
39
+ "Cyrillic": range(1024, 1280),
40
+ "Cyrillic Supplement": range(1280, 1328),
41
+ "Armenian": range(1328, 1424),
42
+ "Hebrew": range(1424, 1536),
43
+ "Arabic": range(1536, 1792),
44
+ "Syriac": range(1792, 1872),
45
+ "Arabic Supplement": range(1872, 1920),
46
+ "Thaana": range(1920, 1984),
47
+ "NKo": range(1984, 2048),
48
+ "Samaritan": range(2048, 2112),
49
+ "Mandaic": range(2112, 2144),
50
+ "Syriac Supplement": range(2144, 2160),
51
+ "Arabic Extended-B": range(2160, 2208),
52
+ "Arabic Extended-A": range(2208, 2304),
53
+ "Devanagari": range(2304, 2432),
54
+ "Bengali": range(2432, 2560),
55
+ "Gurmukhi": range(2560, 2688),
56
+ "Gujarati": range(2688, 2816),
57
+ "Oriya": range(2816, 2944),
58
+ "Tamil": range(2944, 3072),
59
+ "Telugu": range(3072, 3200),
60
+ "Kannada": range(3200, 3328),
61
+ "Malayalam": range(3328, 3456),
62
+ "Sinhala": range(3456, 3584),
63
+ "Thai": range(3584, 3712),
64
+ "Lao": range(3712, 3840),
65
+ "Tibetan": range(3840, 4096),
66
+ "Myanmar": range(4096, 4256),
67
+ "Georgian": range(4256, 4352),
68
+ "Hangul Jamo": range(4352, 4608),
69
+ "Ethiopic": range(4608, 4992),
70
+ "Ethiopic Supplement": range(4992, 5024),
71
+ "Cherokee": range(5024, 5120),
72
+ "Unified Canadian Aboriginal Syllabics": range(5120, 5760),
73
+ "Ogham": range(5760, 5792),
74
+ "Runic": range(5792, 5888),
75
+ "Tagalog": range(5888, 5920),
76
+ "Hanunoo": range(5920, 5952),
77
+ "Buhid": range(5952, 5984),
78
+ "Tagbanwa": range(5984, 6016),
79
+ "Khmer": range(6016, 6144),
80
+ "Mongolian": range(6144, 6320),
81
+ "Unified Canadian Aboriginal Syllabics Extended": range(6320, 6400),
82
+ "Limbu": range(6400, 6480),
83
+ "Tai Le": range(6480, 6528),
84
+ "New Tai Lue": range(6528, 6624),
85
+ "Khmer Symbols": range(6624, 6656),
86
+ "Buginese": range(6656, 6688),
87
+ "Tai Tham": range(6688, 6832),
88
+ "Combining Diacritical Marks Extended": range(6832, 6912),
89
+ "Balinese": range(6912, 7040),
90
+ "Sundanese": range(7040, 7104),
91
+ "Batak": range(7104, 7168),
92
+ "Lepcha": range(7168, 7248),
93
+ "Ol Chiki": range(7248, 7296),
94
+ "Cyrillic Extended-C": range(7296, 7312),
95
+ "Georgian Extended": range(7312, 7360),
96
+ "Sundanese Supplement": range(7360, 7376),
97
+ "Vedic Extensions": range(7376, 7424),
98
+ "Phonetic Extensions": range(7424, 7552),
99
+ "Phonetic Extensions Supplement": range(7552, 7616),
100
+ "Combining Diacritical Marks Supplement": range(7616, 7680),
101
+ "Latin Extended Additional": range(7680, 7936),
102
+ "Greek Extended": range(7936, 8192),
103
+ "General Punctuation": range(8192, 8304),
104
+ "Superscripts and Subscripts": range(8304, 8352),
105
+ "Currency Symbols": range(8352, 8400),
106
+ "Combining Diacritical Marks for Symbols": range(8400, 8448),
107
+ "Letterlike Symbols": range(8448, 8528),
108
+ "Number Forms": range(8528, 8592),
109
+ "Arrows": range(8592, 8704),
110
+ "Mathematical Operators": range(8704, 8960),
111
+ "Miscellaneous Technical": range(8960, 9216),
112
+ "Control Pictures": range(9216, 9280),
113
+ "Optical Character Recognition": range(9280, 9312),
114
+ "Enclosed Alphanumerics": range(9312, 9472),
115
+ "Box Drawing": range(9472, 9600),
116
+ "Block Elements": range(9600, 9632),
117
+ "Geometric Shapes": range(9632, 9728),
118
+ "Miscellaneous Symbols": range(9728, 9984),
119
+ "Dingbats": range(9984, 10176),
120
+ "Miscellaneous Mathematical Symbols-A": range(10176, 10224),
121
+ "Supplemental Arrows-A": range(10224, 10240),
122
+ "Braille Patterns": range(10240, 10496),
123
+ "Supplemental Arrows-B": range(10496, 10624),
124
+ "Miscellaneous Mathematical Symbols-B": range(10624, 10752),
125
+ "Supplemental Mathematical Operators": range(10752, 11008),
126
+ "Miscellaneous Symbols and Arrows": range(11008, 11264),
127
+ "Glagolitic": range(11264, 11360),
128
+ "Latin Extended-C": range(11360, 11392),
129
+ "Coptic": range(11392, 11520),
130
+ "Georgian Supplement": range(11520, 11568),
131
+ "Tifinagh": range(11568, 11648),
132
+ "Ethiopic Extended": range(11648, 11744),
133
+ "Cyrillic Extended-A": range(11744, 11776),
134
+ "Supplemental Punctuation": range(11776, 11904),
135
+ "CJK Radicals Supplement": range(11904, 12032),
136
+ "Kangxi Radicals": range(12032, 12256),
137
+ "Ideographic Description Characters": range(12272, 12288),
138
+ "CJK Symbols and Punctuation": range(12288, 12352),
139
+ "Hiragana": range(12352, 12448),
140
+ "Katakana": range(12448, 12544),
141
+ "Bopomofo": range(12544, 12592),
142
+ "Hangul Compatibility Jamo": range(12592, 12688),
143
+ "Kanbun": range(12688, 12704),
144
+ "Bopomofo Extended": range(12704, 12736),
145
+ "CJK Strokes": range(12736, 12784),
146
+ "Katakana Phonetic Extensions": range(12784, 12800),
147
+ "Enclosed CJK Letters and Months": range(12800, 13056),
148
+ "CJK Compatibility": range(13056, 13312),
149
+ "CJK Unified Ideographs Extension A": range(13312, 19904),
150
+ "Yijing Hexagram Symbols": range(19904, 19968),
151
+ "CJK Unified Ideographs": range(19968, 40960),
152
+ "Yi Syllables": range(40960, 42128),
153
+ "Yi Radicals": range(42128, 42192),
154
+ "Lisu": range(42192, 42240),
155
+ "Vai": range(42240, 42560),
156
+ "Cyrillic Extended-B": range(42560, 42656),
157
+ "Bamum": range(42656, 42752),
158
+ "Modifier Tone Letters": range(42752, 42784),
159
+ "Latin Extended-D": range(42784, 43008),
160
+ "Syloti Nagri": range(43008, 43056),
161
+ "Common Indic Number Forms": range(43056, 43072),
162
+ "Phags-pa": range(43072, 43136),
163
+ "Saurashtra": range(43136, 43232),
164
+ "Devanagari Extended": range(43232, 43264),
165
+ "Kayah Li": range(43264, 43312),
166
+ "Rejang": range(43312, 43360),
167
+ "Hangul Jamo Extended-A": range(43360, 43392),
168
+ "Javanese": range(43392, 43488),
169
+ "Myanmar Extended-B": range(43488, 43520),
170
+ "Cham": range(43520, 43616),
171
+ "Myanmar Extended-A": range(43616, 43648),
172
+ "Tai Viet": range(43648, 43744),
173
+ "Meetei Mayek Extensions": range(43744, 43776),
174
+ "Ethiopic Extended-A": range(43776, 43824),
175
+ "Latin Extended-E": range(43824, 43888),
176
+ "Cherokee Supplement": range(43888, 43968),
177
+ "Meetei Mayek": range(43968, 44032),
178
+ "Hangul Syllables": range(44032, 55216),
179
+ "Hangul Jamo Extended-B": range(55216, 55296),
180
+ "High Surrogates": range(55296, 56192),
181
+ "High Private Use Surrogates": range(56192, 56320),
182
+ "Low Surrogates": range(56320, 57344),
183
+ "Private Use Area": range(57344, 63744),
184
+ "CJK Compatibility Ideographs": range(63744, 64256),
185
+ "Alphabetic Presentation Forms": range(64256, 64336),
186
+ "Arabic Presentation Forms-A": range(64336, 65024),
187
+ "Variation Selectors": range(65024, 65040),
188
+ "Vertical Forms": range(65040, 65056),
189
+ "Combining Half Marks": range(65056, 65072),
190
+ "CJK Compatibility Forms": range(65072, 65104),
191
+ "Small Form Variants": range(65104, 65136),
192
+ "Arabic Presentation Forms-B": range(65136, 65280),
193
+ "Halfwidth and Fullwidth Forms": range(65280, 65520),
194
+ "Specials": range(65520, 65536),
195
+ "Linear B Syllabary": range(65536, 65664),
196
+ "Linear B Ideograms": range(65664, 65792),
197
+ "Aegean Numbers": range(65792, 65856),
198
+ "Ancient Greek Numbers": range(65856, 65936),
199
+ "Ancient Symbols": range(65936, 66000),
200
+ "Phaistos Disc": range(66000, 66048),
201
+ "Lycian": range(66176, 66208),
202
+ "Carian": range(66208, 66272),
203
+ "Coptic Epact Numbers": range(66272, 66304),
204
+ "Old Italic": range(66304, 66352),
205
+ "Gothic": range(66352, 66384),
206
+ "Old Permic": range(66384, 66432),
207
+ "Ugaritic": range(66432, 66464),
208
+ "Old Persian": range(66464, 66528),
209
+ "Deseret": range(66560, 66640),
210
+ "Shavian": range(66640, 66688),
211
+ "Osmanya": range(66688, 66736),
212
+ "Osage": range(66736, 66816),
213
+ "Elbasan": range(66816, 66864),
214
+ "Caucasian Albanian": range(66864, 66928),
215
+ "Vithkuqi": range(66928, 67008),
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
+ "Meroitic Hieroglyphs": range(67968, 68000),
226
+ "Meroitic Cursive": range(68000, 68096),
227
+ "Kharoshthi": range(68096, 68192),
228
+ "Old South Arabian": range(68192, 68224),
229
+ "Old North Arabian": range(68224, 68256),
230
+ "Manichaean": range(68288, 68352),
231
+ "Avestan": range(68352, 68416),
232
+ "Inscriptional Parthian": range(68416, 68448),
233
+ "Inscriptional Pahlavi": range(68448, 68480),
234
+ "Psalter Pahlavi": range(68480, 68528),
235
+ "Old Turkic": range(68608, 68688),
236
+ "Old Hungarian": range(68736, 68864),
237
+ "Hanifi Rohingya": range(68864, 68928),
238
+ "Rumi Numeral Symbols": range(69216, 69248),
239
+ "Yezidi": range(69248, 69312),
240
+ "Arabic Extended-C": range(69312, 69376),
241
+ "Old Sogdian": range(69376, 69424),
242
+ "Sogdian": range(69424, 69488),
243
+ "Old Uyghur": range(69488, 69552),
244
+ "Chorasmian": range(69552, 69600),
245
+ "Elymaic": range(69600, 69632),
246
+ "Brahmi": range(69632, 69760),
247
+ "Kaithi": range(69760, 69840),
248
+ "Sora Sompeng": range(69840, 69888),
249
+ "Chakma": range(69888, 69968),
250
+ "Mahajani": range(69968, 70016),
251
+ "Sharada": range(70016, 70112),
252
+ "Sinhala Archaic Numbers": range(70112, 70144),
253
+ "Khojki": range(70144, 70224),
254
+ "Multani": range(70272, 70320),
255
+ "Khudawadi": range(70320, 70400),
256
+ "Grantha": range(70400, 70528),
257
+ "Newa": range(70656, 70784),
258
+ "Tirhuta": range(70784, 70880),
259
+ "Siddham": range(71040, 71168),
260
+ "Modi": range(71168, 71264),
261
+ "Mongolian Supplement": range(71264, 71296),
262
+ "Takri": range(71296, 71376),
263
+ "Ahom": range(71424, 71504),
264
+ "Dogra": range(71680, 71760),
265
+ "Warang Citi": range(71840, 71936),
266
+ "Dives Akuru": range(71936, 72032),
267
+ "Nandinagari": range(72096, 72192),
268
+ "Zanabazar Square": range(72192, 72272),
269
+ "Soyombo": range(72272, 72368),
270
+ "Unified Canadian Aboriginal Syllabics Extended-A": range(72368, 72384),
271
+ "Pau Cin Hau": range(72384, 72448),
272
+ "Devanagari Extended-A": range(72448, 72544),
273
+ "Bhaiksuki": range(72704, 72816),
274
+ "Marchen": range(72816, 72896),
275
+ "Masaram Gondi": range(72960, 73056),
276
+ "Gunjala Gondi": range(73056, 73136),
277
+ "Makasar": range(73440, 73472),
278
+ "Kawi": range(73472, 73568),
279
+ "Lisu Supplement": range(73648, 73664),
280
+ "Tamil Supplement": range(73664, 73728),
281
+ "Cuneiform": range(73728, 74752),
282
+ "Cuneiform Numbers and Punctuation": range(74752, 74880),
283
+ "Early Dynastic Cuneiform": range(74880, 75088),
284
+ "Cypro-Minoan": range(77712, 77824),
285
+ "Egyptian Hieroglyphs": range(77824, 78896),
286
+ "Egyptian Hieroglyph Format Controls": range(78896, 78944),
287
+ "Anatolian Hieroglyphs": range(82944, 83584),
288
+ "Bamum Supplement": range(92160, 92736),
289
+ "Mro": range(92736, 92784),
290
+ "Tangsa": range(92784, 92880),
291
+ "Bassa Vah": range(92880, 92928),
292
+ "Pahawh Hmong": range(92928, 93072),
293
+ "Medefaidrin": range(93760, 93856),
294
+ "Miao": range(93952, 94112),
295
+ "Ideographic Symbols and Punctuation": range(94176, 94208),
296
+ "Tangut": range(94208, 100352),
297
+ "Tangut Components": range(100352, 101120),
298
+ "Khitan Small Script": range(101120, 101632),
299
+ "Tangut Supplement": range(101632, 101760),
300
+ "Kana Extended-B": range(110576, 110592),
301
+ "Kana Supplement": range(110592, 110848),
302
+ "Kana Extended-A": range(110848, 110896),
303
+ "Small Kana Extension": range(110896, 110960),
304
+ "Nushu": range(110960, 111360),
305
+ "Duployan": range(113664, 113824),
306
+ "Shorthand Format Controls": range(113824, 113840),
307
+ "Znamenny Musical Notation": range(118528, 118736),
308
+ "Byzantine Musical Symbols": range(118784, 119040),
309
+ "Musical Symbols": range(119040, 119296),
310
+ "Ancient Greek Musical Notation": range(119296, 119376),
311
+ "Kaktovik Numerals": range(119488, 119520),
312
+ "Mayan Numerals": range(119520, 119552),
313
+ "Tai Xuan Jing Symbols": range(119552, 119648),
314
+ "Counting Rod Numerals": range(119648, 119680),
315
+ "Mathematical Alphanumeric Symbols": range(119808, 120832),
316
+ "Sutton SignWriting": range(120832, 121520),
317
+ "Latin Extended-G": range(122624, 122880),
318
+ "Glagolitic Supplement": range(122880, 122928),
319
+ "Cyrillic Extended-D": range(122928, 123024),
320
+ "Nyiakeng Puachue Hmong": range(123136, 123216),
321
+ "Toto": range(123536, 123584),
322
+ "Wancho": range(123584, 123648),
323
+ "Nag Mundari": range(124112, 124160),
324
+ "Ethiopic Extended-B": range(124896, 124928),
325
+ "Mende Kikakui": range(124928, 125152),
326
+ "Adlam": range(125184, 125280),
327
+ "Indic Siyaq Numbers": range(126064, 126144),
328
+ "Ottoman Siyaq Numbers": range(126208, 126288),
329
+ "Arabic Mathematical Alphabetic Symbols": range(126464, 126720),
330
+ "Mahjong Tiles": range(126976, 127024),
331
+ "Domino Tiles": range(127024, 127136),
332
+ "Playing Cards": range(127136, 127232),
333
+ "Enclosed Alphanumeric Supplement": range(127232, 127488),
334
+ "Enclosed Ideographic Supplement": range(127488, 127744),
335
+ "Miscellaneous Symbols and Pictographs": range(127744, 128512),
336
+ "Emoticons range(Emoji)": range(128512, 128592),
337
+ "Ornamental Dingbats": range(128592, 128640),
338
+ "Transport and Map Symbols": range(128640, 128768),
339
+ "Alchemical Symbols": range(128768, 128896),
340
+ "Geometric Shapes Extended": range(128896, 129024),
341
+ "Supplemental Arrows-C": range(129024, 129280),
342
+ "Supplemental Symbols and Pictographs": range(129280, 129536),
343
+ "Chess Symbols": range(129536, 129648),
344
+ "Symbols and Pictographs Extended-A": range(129648, 129792),
345
+ "Symbols for Legacy Computing": range(129792, 130048),
346
+ "CJK Unified Ideographs Extension B": range(131072, 173792),
347
+ "CJK Unified Ideographs Extension C": range(173824, 177984),
348
+ "CJK Unified Ideographs Extension D": range(177984, 178208),
349
+ "CJK Unified Ideographs Extension E": range(178208, 183984),
350
+ "CJK Unified Ideographs Extension F": range(183984, 191472),
351
+ "CJK Compatibility Ideographs Supplement": range(194560, 195104),
352
+ "CJK Unified Ideographs Extension G": range(196608, 201552),
353
+ "CJK Unified Ideographs Extension H": range(201552, 205744),
354
+ "Tags": range(917504, 917632),
355
+ "Variation Selectors Supplement": range(917760, 918000),
356
+ "Supplementary Private Use Area-A": range(983040, 1048576),
357
+ "Supplementary Private Use Area-B": range(1048576, 1114112),
358
+ }
359
+
360
+
361
+ UNICODE_SECONDARY_RANGE_KEYWORD: list[str] = [
362
+ "Supplement",
363
+ "Extended",
364
+ "Extensions",
365
+ "Modifier",
366
+ "Marks",
367
+ "Punctuation",
368
+ "Symbols",
369
+ "Forms",
370
+ "Operators",
371
+ "Miscellaneous",
372
+ "Drawing",
373
+ "Block",
374
+ "Shapes",
375
+ "Supplemental",
376
+ "Tags",
377
+ ]
378
+
379
+ RE_POSSIBLE_ENCODING_INDICATION = re_compile(
380
+ r"(?:(?:encoding)|(?:charset)|(?:coding))(?:[\:= ]{1,10})(?:[\"\']?)([a-zA-Z0-9\-_]+)(?:[\"\']?)",
381
+ IGNORECASE,
382
+ )
383
+
384
+ IANA_NO_ALIASES = [
385
+ "cp720",
386
+ "cp737",
387
+ "cp856",
388
+ "cp874",
389
+ "cp875",
390
+ "cp1006",
391
+ "koi8_r",
392
+ "koi8_t",
393
+ "koi8_u",
394
+ ]
395
+
396
+ IANA_SUPPORTED: list[str] = sorted(
397
+ filter(
398
+ lambda x: x.endswith("_codec") is False
399
+ and x not in {"rot_13", "tactis", "mbcs"},
400
+ list(set(aliases.values())) + IANA_NO_ALIASES,
401
+ )
402
+ )
403
+
404
+ IANA_SUPPORTED_COUNT: int = len(IANA_SUPPORTED)
405
+
406
+ # pre-computed code page that are similar using the function cp_similarity.
407
+ IANA_SUPPORTED_SIMILAR: dict[str, list[str]] = {
408
+ "cp037": ["cp1026", "cp1140", "cp273", "cp500"],
409
+ "cp1026": ["cp037", "cp1140", "cp273", "cp500"],
410
+ "cp1125": ["cp866"],
411
+ "cp1140": ["cp037", "cp1026", "cp273", "cp500"],
412
+ "cp1250": ["iso8859_2"],
413
+ "cp1251": ["kz1048", "ptcp154"],
414
+ "cp1252": ["iso8859_15", "iso8859_9", "latin_1"],
415
+ "cp1253": ["iso8859_7"],
416
+ "cp1254": ["iso8859_15", "iso8859_9", "latin_1"],
417
+ "cp1257": ["iso8859_13"],
418
+ "cp273": ["cp037", "cp1026", "cp1140", "cp500"],
419
+ "cp437": ["cp850", "cp858", "cp860", "cp861", "cp862", "cp863", "cp865"],
420
+ "cp500": ["cp037", "cp1026", "cp1140", "cp273"],
421
+ "cp850": ["cp437", "cp857", "cp858", "cp865"],
422
+ "cp857": ["cp850", "cp858", "cp865"],
423
+ "cp858": ["cp437", "cp850", "cp857", "cp865"],
424
+ "cp860": ["cp437", "cp861", "cp862", "cp863", "cp865"],
425
+ "cp861": ["cp437", "cp860", "cp862", "cp863", "cp865"],
426
+ "cp862": ["cp437", "cp860", "cp861", "cp863", "cp865"],
427
+ "cp863": ["cp437", "cp860", "cp861", "cp862", "cp865"],
428
+ "cp865": ["cp437", "cp850", "cp857", "cp858", "cp860", "cp861", "cp862", "cp863"],
429
+ "cp866": ["cp1125"],
430
+ "iso8859_10": ["iso8859_14", "iso8859_15", "iso8859_4", "iso8859_9", "latin_1"],
431
+ "iso8859_11": ["tis_620"],
432
+ "iso8859_13": ["cp1257"],
433
+ "iso8859_14": [
434
+ "iso8859_10",
435
+ "iso8859_15",
436
+ "iso8859_16",
437
+ "iso8859_3",
438
+ "iso8859_9",
439
+ "latin_1",
440
+ ],
441
+ "iso8859_15": [
442
+ "cp1252",
443
+ "cp1254",
444
+ "iso8859_10",
445
+ "iso8859_14",
446
+ "iso8859_16",
447
+ "iso8859_3",
448
+ "iso8859_9",
449
+ "latin_1",
450
+ ],
451
+ "iso8859_16": [
452
+ "iso8859_14",
453
+ "iso8859_15",
454
+ "iso8859_2",
455
+ "iso8859_3",
456
+ "iso8859_9",
457
+ "latin_1",
458
+ ],
459
+ "iso8859_2": ["cp1250", "iso8859_16", "iso8859_4"],
460
+ "iso8859_3": ["iso8859_14", "iso8859_15", "iso8859_16", "iso8859_9", "latin_1"],
461
+ "iso8859_4": ["iso8859_10", "iso8859_2", "iso8859_9", "latin_1"],
462
+ "iso8859_7": ["cp1253"],
463
+ "iso8859_9": [
464
+ "cp1252",
465
+ "cp1254",
466
+ "cp1258",
467
+ "iso8859_10",
468
+ "iso8859_14",
469
+ "iso8859_15",
470
+ "iso8859_16",
471
+ "iso8859_3",
472
+ "iso8859_4",
473
+ "latin_1",
474
+ ],
475
+ "kz1048": ["cp1251", "ptcp154"],
476
+ "latin_1": [
477
+ "cp1252",
478
+ "cp1254",
479
+ "cp1258",
480
+ "iso8859_10",
481
+ "iso8859_14",
482
+ "iso8859_15",
483
+ "iso8859_16",
484
+ "iso8859_3",
485
+ "iso8859_4",
486
+ "iso8859_9",
487
+ ],
488
+ "mac_iceland": ["mac_roman", "mac_turkish"],
489
+ "mac_roman": ["mac_iceland", "mac_turkish"],
490
+ "mac_turkish": ["mac_iceland", "mac_roman"],
491
+ "ptcp154": ["cp1251", "kz1048"],
492
+ "tis_620": ["iso8859_11"],
493
+ }
494
+
495
+
496
+ CHARDET_CORRESPONDENCE: dict[str, str] = {
497
+ "iso2022_kr": "ISO-2022-KR",
498
+ "iso2022_jp": "ISO-2022-JP",
499
+ "euc_kr": "EUC-KR",
500
+ "tis_620": "TIS-620",
501
+ "utf_32": "UTF-32",
502
+ "euc_jp": "EUC-JP",
503
+ "koi8_r": "KOI8-R",
504
+ "iso8859_1": "ISO-8859-1",
505
+ "iso8859_2": "ISO-8859-2",
506
+ "iso8859_5": "ISO-8859-5",
507
+ "iso8859_6": "ISO-8859-6",
508
+ "iso8859_7": "ISO-8859-7",
509
+ "iso8859_8": "ISO-8859-8",
510
+ "utf_16": "UTF-16",
511
+ "cp855": "IBM855",
512
+ "mac_cyrillic": "MacCyrillic",
513
+ "gb2312": "GB2312",
514
+ "gb18030": "GB18030",
515
+ "cp932": "CP932",
516
+ "cp866": "IBM866",
517
+ "utf_8": "utf-8",
518
+ "utf_8_sig": "UTF-8-SIG",
519
+ "shift_jis": "SHIFT_JIS",
520
+ "big5": "Big5",
521
+ "cp1250": "windows-1250",
522
+ "cp1251": "windows-1251",
523
+ "cp1252": "Windows-1252",
524
+ "cp1253": "windows-1253",
525
+ "cp1255": "windows-1255",
526
+ "cp1256": "windows-1256",
527
+ "cp1254": "Windows-1254",
528
+ "cp949": "CP949",
529
+ }
530
+
531
+
532
+ COMMON_SAFE_ASCII_CHARACTERS: set[str] = {
533
+ "<",
534
+ ">",
535
+ "=",
536
+ ":",
537
+ "/",
538
+ "&",
539
+ ";",
540
+ "{",
541
+ "}",
542
+ "[",
543
+ "]",
544
+ ",",
545
+ "|",
546
+ '"',
547
+ "-",
548
+ "(",
549
+ ")",
550
+ }
551
+
552
+ # Sample character sets — replace with full lists if needed
553
+ COMMON_CHINESE_CHARACTERS = "的一是在不了有和人这中大为上个国我以要他时来用们生到作地于出就分对成会可主发年动同工也能下过子说产种面而方后多定行学法所民得经十三之进着等部度家电力里如水化高自二理起小物现实加量都两体制机当使点从业本去把性好应开它合还因由其些然前外天政四日那社义事平形相全表间样与关各重新线内数正心反你明看原又么利比或但质气第向道命此变条只没结解问意建月公无系军很情者最立代想已通并提直题党程展五果料象员革位入常文总次品式活设及管特件长求老头基资边流路级少图山统接知较将组见计别她手角期根论运农指几九区强放决西被干做必战先回则任取据处队南给色光门即保治北造百规热领七海口东导器压志世金增争济阶油思术极交受联什认六共权收证改清己美再采转更单风切打白教速花带安场身车例真务具万每目至达走积示议声报斗完类八离华名确才科张信马节话米整空元况今集温传土许步群广石记需段研界拉林律叫且究观越织装影算低持音众书布复容儿须际商非验连断深难近矿千周委素技备半办青省列习响约支般史感劳便团往酸历市克何除消构府太准精值号率族维划选标写存候毛亲快效斯院查江型眼王按格养易置派层片始却专状育厂京识适属圆包火住调满县局照参红细引听该铁价严龙飞"
554
+
555
+ COMMON_JAPANESE_CHARACTERS = "日一国年大十二本中長出三時行見月分後前生五間上東四今金九入学高円子外八六下来気小七山話女北午百書先名川千水半男西電校語土木聞食車何南万毎白天母火右読友左休父雨"
556
+
557
+ COMMON_KOREAN_CHARACTERS = "一二三四五六七八九十百千萬上下左右中人女子大小山川日月火水木金土父母天地國名年時文校學生"
558
+
559
+ # Combine all into a set
560
+ COMMON_CJK_CHARACTERS = set(
561
+ "".join(
562
+ [
563
+ COMMON_CHINESE_CHARACTERS,
564
+ COMMON_JAPANESE_CHARACTERS,
565
+ COMMON_KOREAN_CHARACTERS,
566
+ ]
567
+ )
568
+ )
569
+
570
+ KO_NAMES: set[str] = {"johab", "cp949", "euc_kr"}
571
+ ZH_NAMES: set[str] = {"big5", "cp950", "big5hkscs", "hz"}
572
+
573
+ # Logging LEVEL below DEBUG
574
+ TRACE: int = 5
575
+
576
+
577
+ # Language label that contain the em dash "—"
578
+ # character are to be considered alternative seq to origin
579
+ FREQUENCIES: dict[str, list[str]] = {
580
+ "English": [
581
+ "e",
582
+ "a",
583
+ "t",
584
+ "i",
585
+ "o",
586
+ "n",
587
+ "s",
588
+ "r",
589
+ "h",
590
+ "l",
591
+ "d",
592
+ "c",
593
+ "u",
594
+ "m",
595
+ "f",
596
+ "p",
597
+ "g",
598
+ "w",
599
+ "y",
600
+ "b",
601
+ "v",
602
+ "k",
603
+ "x",
604
+ "j",
605
+ "z",
606
+ "q",
607
+ ],
608
+ "English—": [
609
+ "e",
610
+ "a",
611
+ "t",
612
+ "i",
613
+ "o",
614
+ "n",
615
+ "s",
616
+ "r",
617
+ "h",
618
+ "l",
619
+ "d",
620
+ "c",
621
+ "m",
622
+ "u",
623
+ "f",
624
+ "p",
625
+ "g",
626
+ "w",
627
+ "b",
628
+ "y",
629
+ "v",
630
+ "k",
631
+ "j",
632
+ "x",
633
+ "z",
634
+ "q",
635
+ ],
636
+ "German": [
637
+ "e",
638
+ "n",
639
+ "i",
640
+ "r",
641
+ "s",
642
+ "t",
643
+ "a",
644
+ "d",
645
+ "h",
646
+ "u",
647
+ "l",
648
+ "g",
649
+ "o",
650
+ "c",
651
+ "m",
652
+ "b",
653
+ "f",
654
+ "k",
655
+ "w",
656
+ "z",
657
+ "p",
658
+ "v",
659
+ "ü",
660
+ "ä",
661
+ "ö",
662
+ "j",
663
+ ],
664
+ "French": [
665
+ "e",
666
+ "a",
667
+ "s",
668
+ "n",
669
+ "i",
670
+ "t",
671
+ "r",
672
+ "l",
673
+ "u",
674
+ "o",
675
+ "d",
676
+ "c",
677
+ "p",
678
+ "m",
679
+ "é",
680
+ "v",
681
+ "g",
682
+ "f",
683
+ "b",
684
+ "h",
685
+ "q",
686
+ "à",
687
+ "x",
688
+ "è",
689
+ "y",
690
+ "j",
691
+ ],
692
+ "Dutch": [
693
+ "e",
694
+ "n",
695
+ "a",
696
+ "i",
697
+ "r",
698
+ "t",
699
+ "o",
700
+ "d",
701
+ "s",
702
+ "l",
703
+ "g",
704
+ "h",
705
+ "v",
706
+ "m",
707
+ "u",
708
+ "k",
709
+ "c",
710
+ "p",
711
+ "b",
712
+ "w",
713
+ "j",
714
+ "z",
715
+ "f",
716
+ "y",
717
+ "x",
718
+ "ë",
719
+ ],
720
+ "Italian": [
721
+ "e",
722
+ "i",
723
+ "a",
724
+ "o",
725
+ "n",
726
+ "l",
727
+ "t",
728
+ "r",
729
+ "s",
730
+ "c",
731
+ "d",
732
+ "u",
733
+ "p",
734
+ "m",
735
+ "g",
736
+ "v",
737
+ "f",
738
+ "b",
739
+ "z",
740
+ "h",
741
+ "q",
742
+ "è",
743
+ "à",
744
+ "k",
745
+ "y",
746
+ "ò",
747
+ ],
748
+ "Polish": [
749
+ "a",
750
+ "i",
751
+ "o",
752
+ "e",
753
+ "n",
754
+ "r",
755
+ "z",
756
+ "w",
757
+ "s",
758
+ "c",
759
+ "t",
760
+ "k",
761
+ "y",
762
+ "d",
763
+ "p",
764
+ "m",
765
+ "u",
766
+ "l",
767
+ "j",
768
+ "ł",
769
+ "g",
770
+ "b",
771
+ "h",
772
+ "ą",
773
+ "ę",
774
+ "ó",
775
+ ],
776
+ "Spanish": [
777
+ "e",
778
+ "a",
779
+ "o",
780
+ "n",
781
+ "s",
782
+ "r",
783
+ "i",
784
+ "l",
785
+ "d",
786
+ "t",
787
+ "c",
788
+ "u",
789
+ "m",
790
+ "p",
791
+ "b",
792
+ "g",
793
+ "v",
794
+ "f",
795
+ "y",
796
+ "ó",
797
+ "h",
798
+ "q",
799
+ "í",
800
+ "j",
801
+ "z",
802
+ "á",
803
+ ],
804
+ "Russian": [
805
+ "о",
806
+ "а",
807
+ "е",
808
+ "и",
809
+ "н",
810
+ "с",
811
+ "т",
812
+ "р",
813
+ "в",
814
+ "л",
815
+ "к",
816
+ "м",
817
+ "д",
818
+ "п",
819
+ "у",
820
+ "г",
821
+ "я",
822
+ "ы",
823
+ "з",
824
+ "б",
825
+ "й",
826
+ "ь",
827
+ "ч",
828
+ "х",
829
+ "ж",
830
+ "ц",
831
+ ],
832
+ # Jap-Kanji
833
+ "Japanese": [
834
+ "人",
835
+ "一",
836
+ "大",
837
+ "亅",
838
+ "丁",
839
+ "丨",
840
+ "竹",
841
+ "笑",
842
+ "口",
843
+ "日",
844
+ "今",
845
+ "二",
846
+ "彳",
847
+ "行",
848
+ "十",
849
+ "土",
850
+ "丶",
851
+ "寸",
852
+ "寺",
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
+ "自",
934
+ ],
935
+ # Jap-Katakana
936
+ "Japanese—": [
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
+ "ヺ",
1033
+ ],
1034
+ # Jap-Hiragana
1035
+ "Japanese——": [
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
+ "ゖ",
1129
+ ],
1130
+ "Portuguese": [
1131
+ "a",
1132
+ "e",
1133
+ "o",
1134
+ "s",
1135
+ "i",
1136
+ "r",
1137
+ "d",
1138
+ "n",
1139
+ "t",
1140
+ "m",
1141
+ "u",
1142
+ "c",
1143
+ "l",
1144
+ "p",
1145
+ "g",
1146
+ "v",
1147
+ "b",
1148
+ "f",
1149
+ "h",
1150
+ "ã",
1151
+ "q",
1152
+ "é",
1153
+ "ç",
1154
+ "á",
1155
+ "z",
1156
+ "í",
1157
+ ],
1158
+ "Swedish": [
1159
+ "e",
1160
+ "a",
1161
+ "n",
1162
+ "r",
1163
+ "t",
1164
+ "s",
1165
+ "i",
1166
+ "l",
1167
+ "d",
1168
+ "o",
1169
+ "m",
1170
+ "k",
1171
+ "g",
1172
+ "v",
1173
+ "h",
1174
+ "f",
1175
+ "u",
1176
+ "p",
1177
+ "ä",
1178
+ "c",
1179
+ "b",
1180
+ "ö",
1181
+ "å",
1182
+ "y",
1183
+ "j",
1184
+ "x",
1185
+ ],
1186
+ "Chinese": [
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
+ "实",
1287
+ ],
1288
+ "Ukrainian": [
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
+ "ї",
1315
+ ],
1316
+ "Norwegian": [
1317
+ "e",
1318
+ "r",
1319
+ "n",
1320
+ "t",
1321
+ "a",
1322
+ "s",
1323
+ "i",
1324
+ "o",
1325
+ "l",
1326
+ "d",
1327
+ "g",
1328
+ "k",
1329
+ "m",
1330
+ "v",
1331
+ "f",
1332
+ "p",
1333
+ "u",
1334
+ "b",
1335
+ "h",
1336
+ "å",
1337
+ "y",
1338
+ "j",
1339
+ "ø",
1340
+ "c",
1341
+ "æ",
1342
+ "w",
1343
+ ],
1344
+ "Finnish": [
1345
+ "a",
1346
+ "i",
1347
+ "n",
1348
+ "t",
1349
+ "e",
1350
+ "s",
1351
+ "l",
1352
+ "o",
1353
+ "u",
1354
+ "k",
1355
+ "ä",
1356
+ "m",
1357
+ "r",
1358
+ "v",
1359
+ "j",
1360
+ "h",
1361
+ "p",
1362
+ "y",
1363
+ "d",
1364
+ "ö",
1365
+ "g",
1366
+ "c",
1367
+ "b",
1368
+ "f",
1369
+ "w",
1370
+ "z",
1371
+ ],
1372
+ "Vietnamese": [
1373
+ "n",
1374
+ "h",
1375
+ "t",
1376
+ "i",
1377
+ "c",
1378
+ "g",
1379
+ "a",
1380
+ "o",
1381
+ "u",
1382
+ "m",
1383
+ "l",
1384
+ "r",
1385
+ "à",
1386
+ "đ",
1387
+ "s",
1388
+ "e",
1389
+ "v",
1390
+ "p",
1391
+ "b",
1392
+ "y",
1393
+ "ư",
1394
+ "d",
1395
+ "á",
1396
+ "k",
1397
+ "ộ",
1398
+ "ế",
1399
+ ],
1400
+ "Czech": [
1401
+ "o",
1402
+ "e",
1403
+ "a",
1404
+ "n",
1405
+ "t",
1406
+ "s",
1407
+ "i",
1408
+ "l",
1409
+ "v",
1410
+ "r",
1411
+ "k",
1412
+ "d",
1413
+ "u",
1414
+ "m",
1415
+ "p",
1416
+ "í",
1417
+ "c",
1418
+ "h",
1419
+ "z",
1420
+ "á",
1421
+ "y",
1422
+ "j",
1423
+ "b",
1424
+ "ě",
1425
+ "é",
1426
+ "ř",
1427
+ ],
1428
+ "Hungarian": [
1429
+ "e",
1430
+ "a",
1431
+ "t",
1432
+ "l",
1433
+ "s",
1434
+ "n",
1435
+ "k",
1436
+ "r",
1437
+ "i",
1438
+ "o",
1439
+ "z",
1440
+ "á",
1441
+ "é",
1442
+ "g",
1443
+ "m",
1444
+ "b",
1445
+ "y",
1446
+ "v",
1447
+ "d",
1448
+ "h",
1449
+ "u",
1450
+ "p",
1451
+ "j",
1452
+ "ö",
1453
+ "f",
1454
+ "c",
1455
+ ],
1456
+ "Korean": [
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
+ "일",
1483
+ ],
1484
+ "Indonesian": [
1485
+ "a",
1486
+ "n",
1487
+ "e",
1488
+ "i",
1489
+ "r",
1490
+ "t",
1491
+ "u",
1492
+ "s",
1493
+ "d",
1494
+ "k",
1495
+ "m",
1496
+ "l",
1497
+ "g",
1498
+ "p",
1499
+ "b",
1500
+ "o",
1501
+ "h",
1502
+ "y",
1503
+ "j",
1504
+ "c",
1505
+ "w",
1506
+ "f",
1507
+ "v",
1508
+ "z",
1509
+ "x",
1510
+ "q",
1511
+ ],
1512
+ "Turkish": [
1513
+ "a",
1514
+ "e",
1515
+ "i",
1516
+ "n",
1517
+ "r",
1518
+ "l",
1519
+ "ı",
1520
+ "k",
1521
+ "d",
1522
+ "t",
1523
+ "s",
1524
+ "m",
1525
+ "y",
1526
+ "u",
1527
+ "o",
1528
+ "b",
1529
+ "ü",
1530
+ "ş",
1531
+ "v",
1532
+ "g",
1533
+ "z",
1534
+ "h",
1535
+ "c",
1536
+ "p",
1537
+ "ç",
1538
+ "ğ",
1539
+ ],
1540
+ "Romanian": [
1541
+ "e",
1542
+ "i",
1543
+ "a",
1544
+ "r",
1545
+ "n",
1546
+ "t",
1547
+ "u",
1548
+ "l",
1549
+ "o",
1550
+ "c",
1551
+ "s",
1552
+ "d",
1553
+ "p",
1554
+ "m",
1555
+ "ă",
1556
+ "f",
1557
+ "v",
1558
+ "î",
1559
+ "g",
1560
+ "b",
1561
+ "ș",
1562
+ "ț",
1563
+ "z",
1564
+ "h",
1565
+ "â",
1566
+ "j",
1567
+ ],
1568
+ "Farsi": [
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
+ "ص",
1595
+ ],
1596
+ "Arabic": [
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
+ "إ",
1623
+ ],
1624
+ "Danish": [
1625
+ "e",
1626
+ "r",
1627
+ "n",
1628
+ "t",
1629
+ "a",
1630
+ "i",
1631
+ "s",
1632
+ "d",
1633
+ "l",
1634
+ "o",
1635
+ "g",
1636
+ "m",
1637
+ "k",
1638
+ "f",
1639
+ "v",
1640
+ "u",
1641
+ "b",
1642
+ "h",
1643
+ "p",
1644
+ "å",
1645
+ "y",
1646
+ "ø",
1647
+ "æ",
1648
+ "c",
1649
+ "j",
1650
+ "w",
1651
+ ],
1652
+ "Serbian": [
1653
+ "а",
1654
+ "и",
1655
+ "о",
1656
+ "е",
1657
+ "н",
1658
+ "р",
1659
+ "с",
1660
+ "у",
1661
+ "т",
1662
+ "к",
1663
+ "ј",
1664
+ "в",
1665
+ "д",
1666
+ "м",
1667
+ "п",
1668
+ "л",
1669
+ "г",
1670
+ "з",
1671
+ "б",
1672
+ "a",
1673
+ "i",
1674
+ "e",
1675
+ "o",
1676
+ "n",
1677
+ "ц",
1678
+ "ш",
1679
+ ],
1680
+ "Lithuanian": [
1681
+ "i",
1682
+ "a",
1683
+ "s",
1684
+ "o",
1685
+ "r",
1686
+ "e",
1687
+ "t",
1688
+ "n",
1689
+ "u",
1690
+ "k",
1691
+ "m",
1692
+ "l",
1693
+ "p",
1694
+ "v",
1695
+ "d",
1696
+ "j",
1697
+ "g",
1698
+ "ė",
1699
+ "b",
1700
+ "y",
1701
+ "ų",
1702
+ "š",
1703
+ "ž",
1704
+ "c",
1705
+ "ą",
1706
+ "į",
1707
+ ],
1708
+ "Slovene": [
1709
+ "e",
1710
+ "a",
1711
+ "i",
1712
+ "o",
1713
+ "n",
1714
+ "r",
1715
+ "s",
1716
+ "l",
1717
+ "t",
1718
+ "j",
1719
+ "v",
1720
+ "k",
1721
+ "d",
1722
+ "p",
1723
+ "m",
1724
+ "u",
1725
+ "z",
1726
+ "b",
1727
+ "g",
1728
+ "h",
1729
+ "č",
1730
+ "c",
1731
+ "š",
1732
+ "ž",
1733
+ "f",
1734
+ "y",
1735
+ ],
1736
+ "Slovak": [
1737
+ "o",
1738
+ "a",
1739
+ "e",
1740
+ "n",
1741
+ "i",
1742
+ "r",
1743
+ "v",
1744
+ "t",
1745
+ "s",
1746
+ "l",
1747
+ "k",
1748
+ "d",
1749
+ "m",
1750
+ "p",
1751
+ "u",
1752
+ "c",
1753
+ "h",
1754
+ "j",
1755
+ "b",
1756
+ "z",
1757
+ "á",
1758
+ "y",
1759
+ "ý",
1760
+ "í",
1761
+ "č",
1762
+ "é",
1763
+ ],
1764
+ "Hebrew": [
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
+ "ך",
1790
+ ],
1791
+ "Bulgarian": [
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
+ "х",
1818
+ ],
1819
+ "Croatian": [
1820
+ "a",
1821
+ "i",
1822
+ "o",
1823
+ "e",
1824
+ "n",
1825
+ "r",
1826
+ "j",
1827
+ "s",
1828
+ "t",
1829
+ "u",
1830
+ "k",
1831
+ "l",
1832
+ "v",
1833
+ "d",
1834
+ "m",
1835
+ "p",
1836
+ "g",
1837
+ "z",
1838
+ "b",
1839
+ "c",
1840
+ "č",
1841
+ "h",
1842
+ "š",
1843
+ "ž",
1844
+ "ć",
1845
+ "f",
1846
+ ],
1847
+ "Hindi": [
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
+ "इ",
1874
+ ],
1875
+ "Estonian": [
1876
+ "a",
1877
+ "i",
1878
+ "e",
1879
+ "s",
1880
+ "t",
1881
+ "l",
1882
+ "u",
1883
+ "n",
1884
+ "o",
1885
+ "k",
1886
+ "r",
1887
+ "d",
1888
+ "m",
1889
+ "v",
1890
+ "g",
1891
+ "p",
1892
+ "j",
1893
+ "h",
1894
+ "ä",
1895
+ "b",
1896
+ "õ",
1897
+ "ü",
1898
+ "f",
1899
+ "c",
1900
+ "ö",
1901
+ "y",
1902
+ ],
1903
+ "Thai": [
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
+ "ใ",
1930
+ ],
1931
+ "Greek": [
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
+ "ύ",
1958
+ ],
1959
+ "Tamil": [
1960
+ "க",
1961
+ "த",
1962
+ "ப",
1963
+ "ட",
1964
+ "ர",
1965
+ "ம",
1966
+ "ல",
1967
+ "ன",
1968
+ "வ",
1969
+ "ற",
1970
+ "ய",
1971
+ "ள",
1972
+ "ச",
1973
+ "ந",
1974
+ "இ",
1975
+ "ண",
1976
+ "அ",
1977
+ "ஆ",
1978
+ "ழ",
1979
+ "ங",
1980
+ "எ",
1981
+ "உ",
1982
+ "ஒ",
1983
+ "ஸ",
1984
+ ],
1985
+ "Kazakh": [
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
+ }
2014
+
2015
+ LANGUAGE_SUPPORTED_COUNT: int = len(FREQUENCIES)
data/miniconda3/lib/python3.13/site-packages/charset_normalizer/legacy.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # TODO: remove this check when dropping Python 3.7 support
10
+ if TYPE_CHECKING:
11
+ from typing_extensions import TypedDict
12
+
13
+ class ResultDict(TypedDict):
14
+ encoding: str | None
15
+ language: str
16
+ confidence: float | None
17
+
18
+
19
+ def detect(
20
+ byte_str: bytes, should_rename_legacy: bool = False, **kwargs: Any
21
+ ) -> ResultDict:
22
+ """
23
+ chardet legacy method
24
+ Detect the encoding of the given byte string. It should be mostly backward-compatible.
25
+ Encoding name will match Chardet own writing whenever possible. (Not on encoding name unsupported by it)
26
+ This function is deprecated and should be used to migrate your project easily, consult the documentation for
27
+ further information. Not planned for removal.
28
+
29
+ :param byte_str: The byte sequence to examine.
30
+ :param should_rename_legacy: Should we rename legacy encodings
31
+ to their more modern equivalents?
32
+ """
33
+ if len(kwargs):
34
+ warn(
35
+ f"charset-normalizer disregard arguments '{','.join(list(kwargs.keys()))}' in legacy function detect()"
36
+ )
37
+
38
+ if not isinstance(byte_str, (bytearray, bytes)):
39
+ raise TypeError( # pragma: nocover
40
+ f"Expected object of type bytes or bytearray, got: {type(byte_str)}"
41
+ )
42
+
43
+ if isinstance(byte_str, bytearray):
44
+ byte_str = bytes(byte_str)
45
+
46
+ r = from_bytes(byte_str).best()
47
+
48
+ encoding = r.encoding if r is not None else None
49
+ language = r.language if r is not None and r.language != "Unknown" else ""
50
+ confidence = 1.0 - r.chaos if r is not None else None
51
+
52
+ # automatically lower confidence
53
+ # on small bytes samples.
54
+ # https://github.com/jawah/charset_normalizer/issues/391
55
+ if (
56
+ confidence is not None
57
+ and confidence >= 0.9
58
+ and encoding
59
+ not in {
60
+ "utf_8",
61
+ "ascii",
62
+ }
63
+ and r.bom is False # type: ignore[union-attr]
64
+ and len(byte_str) < TOO_SMALL_SEQUENCE
65
+ ):
66
+ confidence -= 0.2
67
+
68
+ # Note: CharsetNormalizer does not return 'UTF-8-SIG' as the sig get stripped in the detection/normalization process
69
+ # but chardet does return 'utf-8-sig' and it is a valid codec name.
70
+ if r is not None and encoding == "utf_8" and r.bom:
71
+ encoding += "_sig"
72
+
73
+ if should_rename_legacy is False and encoding in CHARDET_CORRESPONDENCE:
74
+ encoding = CHARDET_CORRESPONDENCE[encoding]
75
+
76
+ return {
77
+ "encoding": encoding,
78
+ "language": language,
79
+ "confidence": confidence,
80
+ }
data/miniconda3/lib/python3.13/site-packages/charset_normalizer/md.py ADDED
@@ -0,0 +1,635 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from functools import lru_cache
4
+ from logging import getLogger
5
+
6
+ from .constant import (
7
+ COMMON_SAFE_ASCII_CHARACTERS,
8
+ TRACE,
9
+ UNICODE_SECONDARY_RANGE_KEYWORD,
10
+ )
11
+ from .utils import (
12
+ is_accentuated,
13
+ is_arabic,
14
+ is_arabic_isolated_form,
15
+ is_case_variable,
16
+ is_cjk,
17
+ is_emoticon,
18
+ is_hangul,
19
+ is_hiragana,
20
+ is_katakana,
21
+ is_latin,
22
+ is_punctuation,
23
+ is_separator,
24
+ is_symbol,
25
+ is_thai,
26
+ is_unprintable,
27
+ remove_accent,
28
+ unicode_range,
29
+ is_cjk_uncommon,
30
+ )
31
+
32
+
33
+ class MessDetectorPlugin:
34
+ """
35
+ Base abstract class used for mess detection plugins.
36
+ All detectors MUST extend and implement given methods.
37
+ """
38
+
39
+ def eligible(self, character: str) -> bool:
40
+ """
41
+ Determine if given character should be fed in.
42
+ """
43
+ raise NotImplementedError # pragma: nocover
44
+
45
+ def feed(self, character: str) -> None:
46
+ """
47
+ The main routine to be executed upon character.
48
+ Insert the logic in witch the text would be considered chaotic.
49
+ """
50
+ raise NotImplementedError # pragma: nocover
51
+
52
+ def reset(self) -> None: # pragma: no cover
53
+ """
54
+ Permit to reset the plugin to the initial state.
55
+ """
56
+ raise NotImplementedError
57
+
58
+ @property
59
+ def ratio(self) -> float:
60
+ """
61
+ Compute the chaos ratio based on what your feed() has seen.
62
+ Must NOT be lower than 0.; No restriction gt 0.
63
+ """
64
+ raise NotImplementedError # pragma: nocover
65
+
66
+
67
+ class TooManySymbolOrPunctuationPlugin(MessDetectorPlugin):
68
+ def __init__(self) -> None:
69
+ self._punctuation_count: int = 0
70
+ self._symbol_count: int = 0
71
+ self._character_count: int = 0
72
+
73
+ self._last_printable_char: str | None = None
74
+ self._frenzy_symbol_in_word: bool = False
75
+
76
+ def eligible(self, character: str) -> bool:
77
+ return character.isprintable()
78
+
79
+ def feed(self, character: str) -> None:
80
+ self._character_count += 1
81
+
82
+ if (
83
+ character != self._last_printable_char
84
+ and character not in COMMON_SAFE_ASCII_CHARACTERS
85
+ ):
86
+ if is_punctuation(character):
87
+ self._punctuation_count += 1
88
+ elif (
89
+ character.isdigit() is False
90
+ and is_symbol(character)
91
+ and is_emoticon(character) is False
92
+ ):
93
+ self._symbol_count += 2
94
+
95
+ self._last_printable_char = character
96
+
97
+ def reset(self) -> None: # Abstract
98
+ self._punctuation_count = 0
99
+ self._character_count = 0
100
+ self._symbol_count = 0
101
+
102
+ @property
103
+ def ratio(self) -> float:
104
+ if self._character_count == 0:
105
+ return 0.0
106
+
107
+ ratio_of_punctuation: float = (
108
+ self._punctuation_count + self._symbol_count
109
+ ) / self._character_count
110
+
111
+ return ratio_of_punctuation if ratio_of_punctuation >= 0.3 else 0.0
112
+
113
+
114
+ class TooManyAccentuatedPlugin(MessDetectorPlugin):
115
+ def __init__(self) -> None:
116
+ self._character_count: int = 0
117
+ self._accentuated_count: int = 0
118
+
119
+ def eligible(self, character: str) -> bool:
120
+ return character.isalpha()
121
+
122
+ def feed(self, character: str) -> None:
123
+ self._character_count += 1
124
+
125
+ if is_accentuated(character):
126
+ self._accentuated_count += 1
127
+
128
+ def reset(self) -> None: # Abstract
129
+ self._character_count = 0
130
+ self._accentuated_count = 0
131
+
132
+ @property
133
+ def ratio(self) -> float:
134
+ if self._character_count < 8:
135
+ return 0.0
136
+
137
+ ratio_of_accentuation: float = self._accentuated_count / self._character_count
138
+ return ratio_of_accentuation if ratio_of_accentuation >= 0.35 else 0.0
139
+
140
+
141
+ class UnprintablePlugin(MessDetectorPlugin):
142
+ def __init__(self) -> None:
143
+ self._unprintable_count: int = 0
144
+ self._character_count: int = 0
145
+
146
+ def eligible(self, character: str) -> bool:
147
+ return True
148
+
149
+ def feed(self, character: str) -> None:
150
+ if is_unprintable(character):
151
+ self._unprintable_count += 1
152
+ self._character_count += 1
153
+
154
+ def reset(self) -> None: # Abstract
155
+ self._unprintable_count = 0
156
+
157
+ @property
158
+ def ratio(self) -> float:
159
+ if self._character_count == 0:
160
+ return 0.0
161
+
162
+ return (self._unprintable_count * 8) / self._character_count
163
+
164
+
165
+ class SuspiciousDuplicateAccentPlugin(MessDetectorPlugin):
166
+ def __init__(self) -> None:
167
+ self._successive_count: int = 0
168
+ self._character_count: int = 0
169
+
170
+ self._last_latin_character: str | None = None
171
+
172
+ def eligible(self, character: str) -> bool:
173
+ return character.isalpha() and is_latin(character)
174
+
175
+ def feed(self, character: str) -> None:
176
+ self._character_count += 1
177
+ if (
178
+ self._last_latin_character is not None
179
+ and is_accentuated(character)
180
+ and is_accentuated(self._last_latin_character)
181
+ ):
182
+ if character.isupper() and self._last_latin_character.isupper():
183
+ self._successive_count += 1
184
+ # Worse if its the same char duplicated with different accent.
185
+ if remove_accent(character) == remove_accent(self._last_latin_character):
186
+ self._successive_count += 1
187
+ self._last_latin_character = character
188
+
189
+ def reset(self) -> None: # Abstract
190
+ self._successive_count = 0
191
+ self._character_count = 0
192
+ self._last_latin_character = None
193
+
194
+ @property
195
+ def ratio(self) -> float:
196
+ if self._character_count == 0:
197
+ return 0.0
198
+
199
+ return (self._successive_count * 2) / self._character_count
200
+
201
+
202
+ class SuspiciousRange(MessDetectorPlugin):
203
+ def __init__(self) -> None:
204
+ self._suspicious_successive_range_count: int = 0
205
+ self._character_count: int = 0
206
+ self._last_printable_seen: str | None = None
207
+
208
+ def eligible(self, character: str) -> bool:
209
+ return character.isprintable()
210
+
211
+ def feed(self, character: str) -> None:
212
+ self._character_count += 1
213
+
214
+ if (
215
+ character.isspace()
216
+ or is_punctuation(character)
217
+ or character in COMMON_SAFE_ASCII_CHARACTERS
218
+ ):
219
+ self._last_printable_seen = None
220
+ return
221
+
222
+ if self._last_printable_seen is None:
223
+ self._last_printable_seen = character
224
+ return
225
+
226
+ unicode_range_a: str | None = unicode_range(self._last_printable_seen)
227
+ unicode_range_b: str | None = unicode_range(character)
228
+
229
+ if is_suspiciously_successive_range(unicode_range_a, unicode_range_b):
230
+ self._suspicious_successive_range_count += 1
231
+
232
+ self._last_printable_seen = character
233
+
234
+ def reset(self) -> None: # Abstract
235
+ self._character_count = 0
236
+ self._suspicious_successive_range_count = 0
237
+ self._last_printable_seen = None
238
+
239
+ @property
240
+ def ratio(self) -> float:
241
+ if self._character_count <= 13:
242
+ return 0.0
243
+
244
+ ratio_of_suspicious_range_usage: float = (
245
+ self._suspicious_successive_range_count * 2
246
+ ) / self._character_count
247
+
248
+ return ratio_of_suspicious_range_usage
249
+
250
+
251
+ class SuperWeirdWordPlugin(MessDetectorPlugin):
252
+ def __init__(self) -> None:
253
+ self._word_count: int = 0
254
+ self._bad_word_count: int = 0
255
+ self._foreign_long_count: int = 0
256
+
257
+ self._is_current_word_bad: bool = False
258
+ self._foreign_long_watch: bool = False
259
+
260
+ self._character_count: int = 0
261
+ self._bad_character_count: int = 0
262
+
263
+ self._buffer: str = ""
264
+ self._buffer_accent_count: int = 0
265
+ self._buffer_glyph_count: int = 0
266
+
267
+ def eligible(self, character: str) -> bool:
268
+ return True
269
+
270
+ def feed(self, character: str) -> None:
271
+ if character.isalpha():
272
+ self._buffer += character
273
+ if is_accentuated(character):
274
+ self._buffer_accent_count += 1
275
+ if (
276
+ self._foreign_long_watch is False
277
+ and (is_latin(character) is False or is_accentuated(character))
278
+ and is_cjk(character) is False
279
+ and is_hangul(character) is False
280
+ and is_katakana(character) is False
281
+ and is_hiragana(character) is False
282
+ and is_thai(character) is False
283
+ ):
284
+ self._foreign_long_watch = True
285
+ if (
286
+ is_cjk(character)
287
+ or is_hangul(character)
288
+ or is_katakana(character)
289
+ or is_hiragana(character)
290
+ or is_thai(character)
291
+ ):
292
+ self._buffer_glyph_count += 1
293
+ return
294
+ if not self._buffer:
295
+ return
296
+ if (
297
+ character.isspace() or is_punctuation(character) or is_separator(character)
298
+ ) and self._buffer:
299
+ self._word_count += 1
300
+ buffer_length: int = len(self._buffer)
301
+
302
+ self._character_count += buffer_length
303
+
304
+ if buffer_length >= 4:
305
+ if self._buffer_accent_count / buffer_length >= 0.5:
306
+ self._is_current_word_bad = True
307
+ # Word/Buffer ending with an upper case accentuated letter are so rare,
308
+ # that we will consider them all as suspicious. Same weight as foreign_long suspicious.
309
+ elif (
310
+ is_accentuated(self._buffer[-1])
311
+ and self._buffer[-1].isupper()
312
+ and all(_.isupper() for _ in self._buffer) is False
313
+ ):
314
+ self._foreign_long_count += 1
315
+ self._is_current_word_bad = True
316
+ elif self._buffer_glyph_count == 1:
317
+ self._is_current_word_bad = True
318
+ self._foreign_long_count += 1
319
+ if buffer_length >= 24 and self._foreign_long_watch:
320
+ camel_case_dst = [
321
+ i
322
+ for c, i in zip(self._buffer, range(0, buffer_length))
323
+ if c.isupper()
324
+ ]
325
+ probable_camel_cased: bool = False
326
+
327
+ if camel_case_dst and (len(camel_case_dst) / buffer_length <= 0.3):
328
+ probable_camel_cased = True
329
+
330
+ if not probable_camel_cased:
331
+ self._foreign_long_count += 1
332
+ self._is_current_word_bad = True
333
+
334
+ if self._is_current_word_bad:
335
+ self._bad_word_count += 1
336
+ self._bad_character_count += len(self._buffer)
337
+ self._is_current_word_bad = False
338
+
339
+ self._foreign_long_watch = False
340
+ self._buffer = ""
341
+ self._buffer_accent_count = 0
342
+ self._buffer_glyph_count = 0
343
+ elif (
344
+ character not in {"<", ">", "-", "=", "~", "|", "_"}
345
+ and character.isdigit() is False
346
+ and is_symbol(character)
347
+ ):
348
+ self._is_current_word_bad = True
349
+ self._buffer += character
350
+
351
+ def reset(self) -> None: # Abstract
352
+ self._buffer = ""
353
+ self._is_current_word_bad = False
354
+ self._foreign_long_watch = False
355
+ self._bad_word_count = 0
356
+ self._word_count = 0
357
+ self._character_count = 0
358
+ self._bad_character_count = 0
359
+ self._foreign_long_count = 0
360
+
361
+ @property
362
+ def ratio(self) -> float:
363
+ if self._word_count <= 10 and self._foreign_long_count == 0:
364
+ return 0.0
365
+
366
+ return self._bad_character_count / self._character_count
367
+
368
+
369
+ class CjkUncommonPlugin(MessDetectorPlugin):
370
+ """
371
+ Detect messy CJK text that probably means nothing.
372
+ """
373
+
374
+ def __init__(self) -> None:
375
+ self._character_count: int = 0
376
+ self._uncommon_count: int = 0
377
+
378
+ def eligible(self, character: str) -> bool:
379
+ return is_cjk(character)
380
+
381
+ def feed(self, character: str) -> None:
382
+ self._character_count += 1
383
+
384
+ if is_cjk_uncommon(character):
385
+ self._uncommon_count += 1
386
+ return
387
+
388
+ def reset(self) -> None: # Abstract
389
+ self._character_count = 0
390
+ self._uncommon_count = 0
391
+
392
+ @property
393
+ def ratio(self) -> float:
394
+ if self._character_count < 8:
395
+ return 0.0
396
+
397
+ uncommon_form_usage: float = self._uncommon_count / self._character_count
398
+
399
+ # we can be pretty sure it's garbage when uncommon characters are widely
400
+ # used. otherwise it could just be traditional chinese for example.
401
+ return uncommon_form_usage / 10 if uncommon_form_usage > 0.5 else 0.0
402
+
403
+
404
+ class ArchaicUpperLowerPlugin(MessDetectorPlugin):
405
+ def __init__(self) -> None:
406
+ self._buf: bool = False
407
+
408
+ self._character_count_since_last_sep: int = 0
409
+
410
+ self._successive_upper_lower_count: int = 0
411
+ self._successive_upper_lower_count_final: int = 0
412
+
413
+ self._character_count: int = 0
414
+
415
+ self._last_alpha_seen: str | None = None
416
+ self._current_ascii_only: bool = True
417
+
418
+ def eligible(self, character: str) -> bool:
419
+ return True
420
+
421
+ def feed(self, character: str) -> None:
422
+ is_concerned = character.isalpha() and is_case_variable(character)
423
+ chunk_sep = is_concerned is False
424
+
425
+ if chunk_sep and self._character_count_since_last_sep > 0:
426
+ if (
427
+ self._character_count_since_last_sep <= 64
428
+ and character.isdigit() is False
429
+ and self._current_ascii_only is False
430
+ ):
431
+ self._successive_upper_lower_count_final += (
432
+ self._successive_upper_lower_count
433
+ )
434
+
435
+ self._successive_upper_lower_count = 0
436
+ self._character_count_since_last_sep = 0
437
+ self._last_alpha_seen = None
438
+ self._buf = False
439
+ self._character_count += 1
440
+ self._current_ascii_only = True
441
+
442
+ return
443
+
444
+ if self._current_ascii_only is True and character.isascii() is False:
445
+ self._current_ascii_only = False
446
+
447
+ if self._last_alpha_seen is not None:
448
+ if (character.isupper() and self._last_alpha_seen.islower()) or (
449
+ character.islower() and self._last_alpha_seen.isupper()
450
+ ):
451
+ if self._buf is True:
452
+ self._successive_upper_lower_count += 2
453
+ self._buf = False
454
+ else:
455
+ self._buf = True
456
+ else:
457
+ self._buf = False
458
+
459
+ self._character_count += 1
460
+ self._character_count_since_last_sep += 1
461
+ self._last_alpha_seen = character
462
+
463
+ def reset(self) -> None: # Abstract
464
+ self._character_count = 0
465
+ self._character_count_since_last_sep = 0
466
+ self._successive_upper_lower_count = 0
467
+ self._successive_upper_lower_count_final = 0
468
+ self._last_alpha_seen = None
469
+ self._buf = False
470
+ self._current_ascii_only = True
471
+
472
+ @property
473
+ def ratio(self) -> float:
474
+ if self._character_count == 0:
475
+ return 0.0
476
+
477
+ return self._successive_upper_lower_count_final / self._character_count
478
+
479
+
480
+ class ArabicIsolatedFormPlugin(MessDetectorPlugin):
481
+ def __init__(self) -> None:
482
+ self._character_count: int = 0
483
+ self._isolated_form_count: int = 0
484
+
485
+ def reset(self) -> None: # Abstract
486
+ self._character_count = 0
487
+ self._isolated_form_count = 0
488
+
489
+ def eligible(self, character: str) -> bool:
490
+ return is_arabic(character)
491
+
492
+ def feed(self, character: str) -> None:
493
+ self._character_count += 1
494
+
495
+ if is_arabic_isolated_form(character):
496
+ self._isolated_form_count += 1
497
+
498
+ @property
499
+ def ratio(self) -> float:
500
+ if self._character_count < 8:
501
+ return 0.0
502
+
503
+ isolated_form_usage: float = self._isolated_form_count / self._character_count
504
+
505
+ return isolated_form_usage
506
+
507
+
508
+ @lru_cache(maxsize=1024)
509
+ def is_suspiciously_successive_range(
510
+ unicode_range_a: str | None, unicode_range_b: str | None
511
+ ) -> bool:
512
+ """
513
+ Determine if two Unicode range seen next to each other can be considered as suspicious.
514
+ """
515
+ if unicode_range_a is None or unicode_range_b is None:
516
+ return True
517
+
518
+ if unicode_range_a == unicode_range_b:
519
+ return False
520
+
521
+ if "Latin" in unicode_range_a and "Latin" in unicode_range_b:
522
+ return False
523
+
524
+ if "Emoticons" in unicode_range_a or "Emoticons" in unicode_range_b:
525
+ return False
526
+
527
+ # Latin characters can be accompanied with a combining diacritical mark
528
+ # eg. Vietnamese.
529
+ if ("Latin" in unicode_range_a or "Latin" in unicode_range_b) and (
530
+ "Combining" in unicode_range_a or "Combining" in unicode_range_b
531
+ ):
532
+ return False
533
+
534
+ keywords_range_a, keywords_range_b = (
535
+ unicode_range_a.split(" "),
536
+ unicode_range_b.split(" "),
537
+ )
538
+
539
+ for el in keywords_range_a:
540
+ if el in UNICODE_SECONDARY_RANGE_KEYWORD:
541
+ continue
542
+ if el in keywords_range_b:
543
+ return False
544
+
545
+ # Japanese Exception
546
+ range_a_jp_chars, range_b_jp_chars = (
547
+ unicode_range_a
548
+ in (
549
+ "Hiragana",
550
+ "Katakana",
551
+ ),
552
+ unicode_range_b in ("Hiragana", "Katakana"),
553
+ )
554
+ if (range_a_jp_chars or range_b_jp_chars) and (
555
+ "CJK" in unicode_range_a or "CJK" in unicode_range_b
556
+ ):
557
+ return False
558
+ if range_a_jp_chars and range_b_jp_chars:
559
+ return False
560
+
561
+ if "Hangul" in unicode_range_a or "Hangul" in unicode_range_b:
562
+ if "CJK" in unicode_range_a or "CJK" in unicode_range_b:
563
+ return False
564
+ if unicode_range_a == "Basic Latin" or unicode_range_b == "Basic Latin":
565
+ return False
566
+
567
+ # Chinese/Japanese use dedicated range for punctuation and/or separators.
568
+ if ("CJK" in unicode_range_a or "CJK" in unicode_range_b) or (
569
+ unicode_range_a in ["Katakana", "Hiragana"]
570
+ and unicode_range_b in ["Katakana", "Hiragana"]
571
+ ):
572
+ if "Punctuation" in unicode_range_a or "Punctuation" in unicode_range_b:
573
+ return False
574
+ if "Forms" in unicode_range_a or "Forms" in unicode_range_b:
575
+ return False
576
+ if unicode_range_a == "Basic Latin" or unicode_range_b == "Basic Latin":
577
+ return False
578
+
579
+ return True
580
+
581
+
582
+ @lru_cache(maxsize=2048)
583
+ def mess_ratio(
584
+ decoded_sequence: str, maximum_threshold: float = 0.2, debug: bool = False
585
+ ) -> float:
586
+ """
587
+ Compute a mess ratio given a decoded bytes sequence. The maximum threshold does stop the computation earlier.
588
+ """
589
+
590
+ detectors: list[MessDetectorPlugin] = [
591
+ md_class() for md_class in MessDetectorPlugin.__subclasses__()
592
+ ]
593
+
594
+ length: int = len(decoded_sequence) + 1
595
+
596
+ mean_mess_ratio: float = 0.0
597
+
598
+ if length < 512:
599
+ intermediary_mean_mess_ratio_calc: int = 32
600
+ elif length <= 1024:
601
+ intermediary_mean_mess_ratio_calc = 64
602
+ else:
603
+ intermediary_mean_mess_ratio_calc = 128
604
+
605
+ for character, index in zip(decoded_sequence + "\n", range(length)):
606
+ for detector in detectors:
607
+ if detector.eligible(character):
608
+ detector.feed(character)
609
+
610
+ if (
611
+ index > 0 and index % intermediary_mean_mess_ratio_calc == 0
612
+ ) or index == length - 1:
613
+ mean_mess_ratio = sum(dt.ratio for dt in detectors)
614
+
615
+ if mean_mess_ratio >= maximum_threshold:
616
+ break
617
+
618
+ if debug:
619
+ logger = getLogger("charset_normalizer")
620
+
621
+ logger.log(
622
+ TRACE,
623
+ "Mess-detector extended-analysis start. "
624
+ f"intermediary_mean_mess_ratio_calc={intermediary_mean_mess_ratio_calc} mean_mess_ratio={mean_mess_ratio} "
625
+ f"maximum_threshold={maximum_threshold}",
626
+ )
627
+
628
+ if len(decoded_sequence) > 16:
629
+ logger.log(TRACE, f"Starting with: {decoded_sequence[:16]}")
630
+ logger.log(TRACE, f"Ending with: {decoded_sequence[-16::]}")
631
+
632
+ for dt in detectors:
633
+ logger.log(TRACE, f"{dt.__class__}: {dt.ratio}")
634
+
635
+ return round(mean_mess_ratio, 3)
data/miniconda3/lib/python3.13/site-packages/charset_normalizer/models.py ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from encodings.aliases import aliases
4
+ from hashlib import sha256
5
+ from json import dumps
6
+ from re import sub
7
+ from typing import Any, Iterator, List, Tuple
8
+
9
+ from .constant import RE_POSSIBLE_ENCODING_INDICATION, TOO_BIG_SEQUENCE
10
+ from .utils import iana_name, is_multi_byte_encoding, unicode_range
11
+
12
+
13
+ class CharsetMatch:
14
+ def __init__(
15
+ self,
16
+ payload: bytes,
17
+ guessed_encoding: str,
18
+ mean_mess_ratio: float,
19
+ has_sig_or_bom: bool,
20
+ languages: CoherenceMatches,
21
+ decoded_payload: str | None = None,
22
+ preemptive_declaration: str | None = None,
23
+ ):
24
+ self._payload: bytes = payload
25
+
26
+ self._encoding: str = guessed_encoding
27
+ self._mean_mess_ratio: float = mean_mess_ratio
28
+ self._languages: CoherenceMatches = languages
29
+ self._has_sig_or_bom: bool = has_sig_or_bom
30
+ self._unicode_ranges: list[str] | None = None
31
+
32
+ self._leaves: list[CharsetMatch] = []
33
+ self._mean_coherence_ratio: float = 0.0
34
+
35
+ self._output_payload: bytes | None = None
36
+ self._output_encoding: str | None = None
37
+
38
+ self._string: str | None = decoded_payload
39
+
40
+ self._preemptive_declaration: str | None = preemptive_declaration
41
+
42
+ def __eq__(self, other: object) -> bool:
43
+ if not isinstance(other, CharsetMatch):
44
+ if isinstance(other, str):
45
+ return iana_name(other) == self.encoding
46
+ return False
47
+ return self.encoding == other.encoding and self.fingerprint == other.fingerprint
48
+
49
+ def __lt__(self, other: object) -> bool:
50
+ """
51
+ Implemented to make sorted available upon CharsetMatches items.
52
+ """
53
+ if not isinstance(other, CharsetMatch):
54
+ raise ValueError
55
+
56
+ chaos_difference: float = abs(self.chaos - other.chaos)
57
+ coherence_difference: float = abs(self.coherence - other.coherence)
58
+
59
+ # Below 1% difference --> Use Coherence
60
+ if chaos_difference < 0.01 and coherence_difference > 0.02:
61
+ return self.coherence > other.coherence
62
+ elif chaos_difference < 0.01 and coherence_difference <= 0.02:
63
+ # When having a difficult decision, use the result that decoded as many multi-byte as possible.
64
+ # preserve RAM usage!
65
+ if len(self._payload) >= TOO_BIG_SEQUENCE:
66
+ return self.chaos < other.chaos
67
+ return self.multi_byte_usage > other.multi_byte_usage
68
+
69
+ return self.chaos < other.chaos
70
+
71
+ @property
72
+ def multi_byte_usage(self) -> float:
73
+ return 1.0 - (len(str(self)) / len(self.raw))
74
+
75
+ def __str__(self) -> str:
76
+ # Lazy Str Loading
77
+ if self._string is None:
78
+ self._string = str(self._payload, self._encoding, "strict")
79
+ return self._string
80
+
81
+ def __repr__(self) -> str:
82
+ return f"<CharsetMatch '{self.encoding}' bytes({self.fingerprint})>"
83
+
84
+ def add_submatch(self, other: CharsetMatch) -> None:
85
+ if not isinstance(other, CharsetMatch) or other == self:
86
+ raise ValueError(
87
+ "Unable to add instance <{}> as a submatch of a CharsetMatch".format(
88
+ other.__class__
89
+ )
90
+ )
91
+
92
+ other._string = None # Unload RAM usage; dirty trick.
93
+ self._leaves.append(other)
94
+
95
+ @property
96
+ def encoding(self) -> str:
97
+ return self._encoding
98
+
99
+ @property
100
+ def encoding_aliases(self) -> list[str]:
101
+ """
102
+ Encoding name are known by many name, using this could help when searching for IBM855 when it's listed as CP855.
103
+ """
104
+ also_known_as: list[str] = []
105
+ for u, p in aliases.items():
106
+ if self.encoding == u:
107
+ also_known_as.append(p)
108
+ elif self.encoding == p:
109
+ also_known_as.append(u)
110
+ return also_known_as
111
+
112
+ @property
113
+ def bom(self) -> bool:
114
+ return self._has_sig_or_bom
115
+
116
+ @property
117
+ def byte_order_mark(self) -> bool:
118
+ return self._has_sig_or_bom
119
+
120
+ @property
121
+ def languages(self) -> list[str]:
122
+ """
123
+ Return the complete list of possible languages found in decoded sequence.
124
+ Usually not really useful. Returned list may be empty even if 'language' property return something != 'Unknown'.
125
+ """
126
+ return [e[0] for e in self._languages]
127
+
128
+ @property
129
+ def language(self) -> str:
130
+ """
131
+ Most probable language found in decoded sequence. If none were detected or inferred, the property will return
132
+ "Unknown".
133
+ """
134
+ if not self._languages:
135
+ # Trying to infer the language based on the given encoding
136
+ # Its either English or we should not pronounce ourselves in certain cases.
137
+ if "ascii" in self.could_be_from_charset:
138
+ return "English"
139
+
140
+ # doing it there to avoid circular import
141
+ from charset_normalizer.cd import encoding_languages, mb_encoding_languages
142
+
143
+ languages = (
144
+ mb_encoding_languages(self.encoding)
145
+ if is_multi_byte_encoding(self.encoding)
146
+ else encoding_languages(self.encoding)
147
+ )
148
+
149
+ if len(languages) == 0 or "Latin Based" in languages:
150
+ return "Unknown"
151
+
152
+ return languages[0]
153
+
154
+ return self._languages[0][0]
155
+
156
+ @property
157
+ def chaos(self) -> float:
158
+ return self._mean_mess_ratio
159
+
160
+ @property
161
+ def coherence(self) -> float:
162
+ if not self._languages:
163
+ return 0.0
164
+ return self._languages[0][1]
165
+
166
+ @property
167
+ def percent_chaos(self) -> float:
168
+ return round(self.chaos * 100, ndigits=3)
169
+
170
+ @property
171
+ def percent_coherence(self) -> float:
172
+ return round(self.coherence * 100, ndigits=3)
173
+
174
+ @property
175
+ def raw(self) -> bytes:
176
+ """
177
+ Original untouched bytes.
178
+ """
179
+ return self._payload
180
+
181
+ @property
182
+ def submatch(self) -> list[CharsetMatch]:
183
+ return self._leaves
184
+
185
+ @property
186
+ def has_submatch(self) -> bool:
187
+ return len(self._leaves) > 0
188
+
189
+ @property
190
+ def alphabets(self) -> list[str]:
191
+ if self._unicode_ranges is not None:
192
+ return self._unicode_ranges
193
+ # list detected ranges
194
+ detected_ranges: list[str | None] = [unicode_range(char) for char in str(self)]
195
+ # filter and sort
196
+ self._unicode_ranges = sorted(list({r for r in detected_ranges if r}))
197
+ return self._unicode_ranges
198
+
199
+ @property
200
+ def could_be_from_charset(self) -> list[str]:
201
+ """
202
+ The complete list of encoding that output the exact SAME str result and therefore could be the originating
203
+ encoding.
204
+ This list does include the encoding available in property 'encoding'.
205
+ """
206
+ return [self._encoding] + [m.encoding for m in self._leaves]
207
+
208
+ def output(self, encoding: str = "utf_8") -> bytes:
209
+ """
210
+ Method to get re-encoded bytes payload using given target encoding. Default to UTF-8.
211
+ Any errors will be simply ignored by the encoder NOT replaced.
212
+ """
213
+ if self._output_encoding is None or self._output_encoding != encoding:
214
+ self._output_encoding = encoding
215
+ decoded_string = str(self)
216
+ if (
217
+ self._preemptive_declaration is not None
218
+ and self._preemptive_declaration.lower()
219
+ not in ["utf-8", "utf8", "utf_8"]
220
+ ):
221
+ patched_header = sub(
222
+ RE_POSSIBLE_ENCODING_INDICATION,
223
+ lambda m: m.string[m.span()[0] : m.span()[1]].replace(
224
+ m.groups()[0],
225
+ iana_name(self._output_encoding).replace("_", "-"), # type: ignore[arg-type]
226
+ ),
227
+ decoded_string[:8192],
228
+ count=1,
229
+ )
230
+
231
+ decoded_string = patched_header + decoded_string[8192:]
232
+
233
+ self._output_payload = decoded_string.encode(encoding, "replace")
234
+
235
+ return self._output_payload # type: ignore
236
+
237
+ @property
238
+ def fingerprint(self) -> str:
239
+ """
240
+ Retrieve the unique SHA256 computed using the transformed (re-encoded) payload. Not the original one.
241
+ """
242
+ return sha256(self.output()).hexdigest()
243
+
244
+
245
+ class CharsetMatches:
246
+ """
247
+ Container with every CharsetMatch items ordered by default from most probable to the less one.
248
+ Act like a list(iterable) but does not implements all related methods.
249
+ """
250
+
251
+ def __init__(self, results: list[CharsetMatch] | None = None):
252
+ self._results: list[CharsetMatch] = sorted(results) if results else []
253
+
254
+ def __iter__(self) -> Iterator[CharsetMatch]:
255
+ yield from self._results
256
+
257
+ def __getitem__(self, item: int | str) -> CharsetMatch:
258
+ """
259
+ Retrieve a single item either by its position or encoding name (alias may be used here).
260
+ Raise KeyError upon invalid index or encoding not present in results.
261
+ """
262
+ if isinstance(item, int):
263
+ return self._results[item]
264
+ if isinstance(item, str):
265
+ item = iana_name(item, False)
266
+ for result in self._results:
267
+ if item in result.could_be_from_charset:
268
+ return result
269
+ raise KeyError
270
+
271
+ def __len__(self) -> int:
272
+ return len(self._results)
273
+
274
+ def __bool__(self) -> bool:
275
+ return len(self._results) > 0
276
+
277
+ def append(self, item: CharsetMatch) -> None:
278
+ """
279
+ Insert a single match. Will be inserted accordingly to preserve sort.
280
+ Can be inserted as a submatch.
281
+ """
282
+ if not isinstance(item, CharsetMatch):
283
+ raise ValueError(
284
+ "Cannot append instance '{}' to CharsetMatches".format(
285
+ str(item.__class__)
286
+ )
287
+ )
288
+ # We should disable the submatch factoring when the input file is too heavy (conserve RAM usage)
289
+ if len(item.raw) < TOO_BIG_SEQUENCE:
290
+ for match in self._results:
291
+ if match.fingerprint == item.fingerprint and match.chaos == item.chaos:
292
+ match.add_submatch(item)
293
+ return
294
+ self._results.append(item)
295
+ self._results = sorted(self._results)
296
+
297
+ def best(self) -> CharsetMatch | None:
298
+ """
299
+ Simply return the first match. Strict equivalent to matches[0].
300
+ """
301
+ if not self._results:
302
+ return None
303
+ return self._results[0]
304
+
305
+ def first(self) -> CharsetMatch | None:
306
+ """
307
+ Redundant method, call the method best(). Kept for BC reasons.
308
+ """
309
+ return self.best()
310
+
311
+
312
+ CoherenceMatch = Tuple[str, float]
313
+ CoherenceMatches = List[CoherenceMatch]
314
+
315
+
316
+ class CliDetectionResult:
317
+ def __init__(
318
+ self,
319
+ path: str,
320
+ encoding: str | None,
321
+ encoding_aliases: list[str],
322
+ alternative_encodings: list[str],
323
+ language: str,
324
+ alphabets: list[str],
325
+ has_sig_or_bom: bool,
326
+ chaos: float,
327
+ coherence: float,
328
+ unicode_path: str | None,
329
+ is_preferred: bool,
330
+ ):
331
+ self.path: str = path
332
+ self.unicode_path: str | None = unicode_path
333
+ self.encoding: str | None = encoding
334
+ self.encoding_aliases: list[str] = encoding_aliases
335
+ self.alternative_encodings: list[str] = alternative_encodings
336
+ self.language: str = language
337
+ self.alphabets: list[str] = alphabets
338
+ self.has_sig_or_bom: bool = has_sig_or_bom
339
+ self.chaos: float = chaos
340
+ self.coherence: float = coherence
341
+ self.is_preferred: bool = is_preferred
342
+
343
+ @property
344
+ def __dict__(self) -> dict[str, Any]: # type: ignore
345
+ return {
346
+ "path": self.path,
347
+ "encoding": self.encoding,
348
+ "encoding_aliases": self.encoding_aliases,
349
+ "alternative_encodings": self.alternative_encodings,
350
+ "language": self.language,
351
+ "alphabets": self.alphabets,
352
+ "has_sig_or_bom": self.has_sig_or_bom,
353
+ "chaos": self.chaos,
354
+ "coherence": self.coherence,
355
+ "unicode_path": self.unicode_path,
356
+ "is_preferred": self.is_preferred,
357
+ }
358
+
359
+ def to_json(self) -> str:
360
+ return dumps(self.__dict__, ensure_ascii=True, indent=4)
data/miniconda3/lib/python3.13/site-packages/charset_normalizer/py.typed ADDED
File without changes
data/miniconda3/lib/python3.13/site-packages/charset_normalizer/utils.py ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import importlib
4
+ import logging
5
+ import unicodedata
6
+ from codecs import IncrementalDecoder
7
+ from encodings.aliases import aliases
8
+ from functools import lru_cache
9
+ from re import findall
10
+ from typing import Generator
11
+
12
+ from _multibytecodec import ( # type: ignore[import-not-found,import]
13
+ MultibyteIncrementalDecoder,
14
+ )
15
+
16
+ from .constant import (
17
+ ENCODING_MARKS,
18
+ IANA_SUPPORTED_SIMILAR,
19
+ RE_POSSIBLE_ENCODING_INDICATION,
20
+ UNICODE_RANGES_COMBINED,
21
+ UNICODE_SECONDARY_RANGE_KEYWORD,
22
+ UTF8_MAXIMAL_ALLOCATION,
23
+ COMMON_CJK_CHARACTERS,
24
+ )
25
+
26
+
27
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
28
+ def is_accentuated(character: str) -> bool:
29
+ try:
30
+ description: str = unicodedata.name(character)
31
+ except ValueError: # Defensive: unicode database outdated?
32
+ return False
33
+ return (
34
+ "WITH GRAVE" in description
35
+ or "WITH ACUTE" in description
36
+ or "WITH CEDILLA" in description
37
+ or "WITH DIAERESIS" in description
38
+ or "WITH CIRCUMFLEX" in description
39
+ or "WITH TILDE" in description
40
+ or "WITH MACRON" in description
41
+ or "WITH RING ABOVE" in description
42
+ )
43
+
44
+
45
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
46
+ def remove_accent(character: str) -> str:
47
+ decomposed: str = unicodedata.decomposition(character)
48
+ if not decomposed:
49
+ return character
50
+
51
+ codes: list[str] = decomposed.split(" ")
52
+
53
+ return chr(int(codes[0], 16))
54
+
55
+
56
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
57
+ def unicode_range(character: str) -> str | None:
58
+ """
59
+ Retrieve the Unicode range official name from a single character.
60
+ """
61
+ character_ord: int = ord(character)
62
+
63
+ for range_name, ord_range in UNICODE_RANGES_COMBINED.items():
64
+ if character_ord in ord_range:
65
+ return range_name
66
+
67
+ return None
68
+
69
+
70
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
71
+ def is_latin(character: str) -> bool:
72
+ try:
73
+ description: str = unicodedata.name(character)
74
+ except ValueError: # Defensive: unicode database outdated?
75
+ return False
76
+ return "LATIN" in description
77
+
78
+
79
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
80
+ def is_punctuation(character: str) -> bool:
81
+ character_category: str = unicodedata.category(character)
82
+
83
+ if "P" in character_category:
84
+ return True
85
+
86
+ character_range: str | None = unicode_range(character)
87
+
88
+ if character_range is None:
89
+ return False
90
+
91
+ return "Punctuation" in character_range
92
+
93
+
94
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
95
+ def is_symbol(character: str) -> bool:
96
+ character_category: str = unicodedata.category(character)
97
+
98
+ if "S" in character_category or "N" in character_category:
99
+ return True
100
+
101
+ character_range: str | None = unicode_range(character)
102
+
103
+ if character_range is None:
104
+ return False
105
+
106
+ return "Forms" in character_range and character_category != "Lo"
107
+
108
+
109
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
110
+ def is_emoticon(character: str) -> bool:
111
+ character_range: str | None = unicode_range(character)
112
+
113
+ if character_range is None:
114
+ return False
115
+
116
+ return "Emoticons" in character_range or "Pictographs" in character_range
117
+
118
+
119
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
120
+ def is_separator(character: str) -> bool:
121
+ if character.isspace() or character in {"|", "+", "<", ">"}:
122
+ return True
123
+
124
+ character_category: str = unicodedata.category(character)
125
+
126
+ return "Z" in character_category or character_category in {"Po", "Pd", "Pc"}
127
+
128
+
129
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
130
+ def is_case_variable(character: str) -> bool:
131
+ return character.islower() != character.isupper()
132
+
133
+
134
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
135
+ def is_cjk(character: str) -> bool:
136
+ try:
137
+ character_name = unicodedata.name(character)
138
+ except ValueError: # Defensive: unicode database outdated?
139
+ return False
140
+
141
+ return "CJK" in character_name
142
+
143
+
144
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
145
+ def is_hiragana(character: str) -> bool:
146
+ try:
147
+ character_name = unicodedata.name(character)
148
+ except ValueError: # Defensive: unicode database outdated?
149
+ return False
150
+
151
+ return "HIRAGANA" in character_name
152
+
153
+
154
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
155
+ def is_katakana(character: str) -> bool:
156
+ try:
157
+ character_name = unicodedata.name(character)
158
+ except ValueError: # Defensive: unicode database outdated?
159
+ return False
160
+
161
+ return "KATAKANA" in character_name
162
+
163
+
164
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
165
+ def is_hangul(character: str) -> bool:
166
+ try:
167
+ character_name = unicodedata.name(character)
168
+ except ValueError: # Defensive: unicode database outdated?
169
+ return False
170
+
171
+ return "HANGUL" in character_name
172
+
173
+
174
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
175
+ def is_thai(character: str) -> bool:
176
+ try:
177
+ character_name = unicodedata.name(character)
178
+ except ValueError: # Defensive: unicode database outdated?
179
+ return False
180
+
181
+ return "THAI" in character_name
182
+
183
+
184
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
185
+ def is_arabic(character: str) -> bool:
186
+ try:
187
+ character_name = unicodedata.name(character)
188
+ except ValueError: # Defensive: unicode database outdated?
189
+ return False
190
+
191
+ return "ARABIC" in character_name
192
+
193
+
194
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
195
+ def is_arabic_isolated_form(character: str) -> bool:
196
+ try:
197
+ character_name = unicodedata.name(character)
198
+ except ValueError: # Defensive: unicode database outdated?
199
+ return False
200
+
201
+ return "ARABIC" in character_name and "ISOLATED FORM" in character_name
202
+
203
+
204
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
205
+ def is_cjk_uncommon(character: str) -> bool:
206
+ return character not in COMMON_CJK_CHARACTERS
207
+
208
+
209
+ @lru_cache(maxsize=len(UNICODE_RANGES_COMBINED))
210
+ def is_unicode_range_secondary(range_name: str) -> bool:
211
+ return any(keyword in range_name for keyword in UNICODE_SECONDARY_RANGE_KEYWORD)
212
+
213
+
214
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
215
+ def is_unprintable(character: str) -> bool:
216
+ return (
217
+ character.isspace() is False # includes \n \t \r \v
218
+ and character.isprintable() is False
219
+ and character != "\x1a" # Why? Its the ASCII substitute character.
220
+ and character != "\ufeff" # bug discovered in Python,
221
+ # Zero Width No-Break Space located in Arabic Presentation Forms-B, Unicode 1.1 not acknowledged as space.
222
+ )
223
+
224
+
225
+ def any_specified_encoding(sequence: bytes, search_zone: int = 8192) -> str | None:
226
+ """
227
+ Extract using ASCII-only decoder any specified encoding in the first n-bytes.
228
+ """
229
+ if not isinstance(sequence, bytes):
230
+ raise TypeError
231
+
232
+ seq_len: int = len(sequence)
233
+
234
+ results: list[str] = findall(
235
+ RE_POSSIBLE_ENCODING_INDICATION,
236
+ sequence[: min(seq_len, search_zone)].decode("ascii", errors="ignore"),
237
+ )
238
+
239
+ if len(results) == 0:
240
+ return None
241
+
242
+ for specified_encoding in results:
243
+ specified_encoding = specified_encoding.lower().replace("-", "_")
244
+
245
+ encoding_alias: str
246
+ encoding_iana: str
247
+
248
+ for encoding_alias, encoding_iana in aliases.items():
249
+ if encoding_alias == specified_encoding:
250
+ return encoding_iana
251
+ if encoding_iana == specified_encoding:
252
+ return encoding_iana
253
+
254
+ return None
255
+
256
+
257
+ @lru_cache(maxsize=128)
258
+ def is_multi_byte_encoding(name: str) -> bool:
259
+ """
260
+ Verify is a specific encoding is a multi byte one based on it IANA name
261
+ """
262
+ return name in {
263
+ "utf_8",
264
+ "utf_8_sig",
265
+ "utf_16",
266
+ "utf_16_be",
267
+ "utf_16_le",
268
+ "utf_32",
269
+ "utf_32_le",
270
+ "utf_32_be",
271
+ "utf_7",
272
+ } or issubclass(
273
+ importlib.import_module(f"encodings.{name}").IncrementalDecoder,
274
+ MultibyteIncrementalDecoder,
275
+ )
276
+
277
+
278
+ def identify_sig_or_bom(sequence: bytes) -> tuple[str | None, bytes]:
279
+ """
280
+ Identify and extract SIG/BOM in given sequence.
281
+ """
282
+
283
+ for iana_encoding in ENCODING_MARKS:
284
+ marks: bytes | list[bytes] = ENCODING_MARKS[iana_encoding]
285
+
286
+ if isinstance(marks, bytes):
287
+ marks = [marks]
288
+
289
+ for mark in marks:
290
+ if sequence.startswith(mark):
291
+ return iana_encoding, mark
292
+
293
+ return None, b""
294
+
295
+
296
+ def should_strip_sig_or_bom(iana_encoding: str) -> bool:
297
+ return iana_encoding not in {"utf_16", "utf_32"}
298
+
299
+
300
+ def iana_name(cp_name: str, strict: bool = True) -> str:
301
+ """Returns the Python normalized encoding name (Not the IANA official name)."""
302
+ cp_name = cp_name.lower().replace("-", "_")
303
+
304
+ encoding_alias: str
305
+ encoding_iana: str
306
+
307
+ for encoding_alias, encoding_iana in aliases.items():
308
+ if cp_name in [encoding_alias, encoding_iana]:
309
+ return encoding_iana
310
+
311
+ if strict:
312
+ raise ValueError(f"Unable to retrieve IANA for '{cp_name}'")
313
+
314
+ return cp_name
315
+
316
+
317
+ def cp_similarity(iana_name_a: str, iana_name_b: str) -> float:
318
+ if is_multi_byte_encoding(iana_name_a) or is_multi_byte_encoding(iana_name_b):
319
+ return 0.0
320
+
321
+ decoder_a = importlib.import_module(f"encodings.{iana_name_a}").IncrementalDecoder
322
+ decoder_b = importlib.import_module(f"encodings.{iana_name_b}").IncrementalDecoder
323
+
324
+ id_a: IncrementalDecoder = decoder_a(errors="ignore")
325
+ id_b: IncrementalDecoder = decoder_b(errors="ignore")
326
+
327
+ character_match_count: int = 0
328
+
329
+ for i in range(255):
330
+ to_be_decoded: bytes = bytes([i])
331
+ if id_a.decode(to_be_decoded) == id_b.decode(to_be_decoded):
332
+ character_match_count += 1
333
+
334
+ return character_match_count / 254
335
+
336
+
337
+ def is_cp_similar(iana_name_a: str, iana_name_b: str) -> bool:
338
+ """
339
+ Determine if two code page are at least 80% similar. IANA_SUPPORTED_SIMILAR dict was generated using
340
+ the function cp_similarity.
341
+ """
342
+ return (
343
+ iana_name_a in IANA_SUPPORTED_SIMILAR
344
+ and iana_name_b in IANA_SUPPORTED_SIMILAR[iana_name_a]
345
+ )
346
+
347
+
348
+ def set_logging_handler(
349
+ name: str = "charset_normalizer",
350
+ level: int = logging.INFO,
351
+ format_string: str = "%(asctime)s | %(levelname)s | %(message)s",
352
+ ) -> None:
353
+ logger = logging.getLogger(name)
354
+ logger.setLevel(level)
355
+
356
+ handler = logging.StreamHandler()
357
+ handler.setFormatter(logging.Formatter(format_string))
358
+ logger.addHandler(handler)
359
+
360
+
361
+ def cut_sequence_chunks(
362
+ sequences: bytes,
363
+ encoding_iana: str,
364
+ offsets: range,
365
+ chunk_size: int,
366
+ bom_or_sig_available: bool,
367
+ strip_sig_or_bom: bool,
368
+ sig_payload: bytes,
369
+ is_multi_byte_decoder: bool,
370
+ decoded_payload: str | None = None,
371
+ ) -> Generator[str, None, None]:
372
+ if decoded_payload and is_multi_byte_decoder is False:
373
+ for i in offsets:
374
+ chunk = decoded_payload[i : i + chunk_size]
375
+ if not chunk:
376
+ break
377
+ yield chunk
378
+ else:
379
+ for i in offsets:
380
+ chunk_end = i + chunk_size
381
+ if chunk_end > len(sequences) + 8:
382
+ continue
383
+
384
+ cut_sequence = sequences[i : i + chunk_size]
385
+
386
+ if bom_or_sig_available and strip_sig_or_bom is False:
387
+ cut_sequence = sig_payload + cut_sequence
388
+
389
+ chunk = cut_sequence.decode(
390
+ encoding_iana,
391
+ errors="ignore" if is_multi_byte_decoder else "strict",
392
+ )
393
+
394
+ # multi-byte bad cutting detector and adjustment
395
+ # not the cleanest way to perform that fix but clever enough for now.
396
+ if is_multi_byte_decoder and i > 0:
397
+ chunk_partial_size_chk: int = min(chunk_size, 16)
398
+
399
+ if (
400
+ decoded_payload
401
+ and chunk[:chunk_partial_size_chk] not in decoded_payload
402
+ ):
403
+ for j in range(i, i - 4, -1):
404
+ cut_sequence = sequences[j:chunk_end]
405
+
406
+ if bom_or_sig_available and strip_sig_or_bom is False:
407
+ cut_sequence = sig_payload + cut_sequence
408
+
409
+ chunk = cut_sequence.decode(encoding_iana, errors="ignore")
410
+
411
+ if chunk[:chunk_partial_size_chk] in decoded_payload:
412
+ break
413
+
414
+ yield chunk
data/miniconda3/lib/python3.13/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.4"
8
+ VERSION = __version__.split(".")
data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ conda
data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/METADATA ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: conda-libmamba-solver
3
+ Version: 25.11.0
4
+ Summary: The fast mamba solver, now in conda
5
+ Project-URL: homepage, https://github.com/conda/conda-libmamba-solver
6
+ Author-email: "Anaconda, Inc." <conda@continuum.io>
7
+ License: BSD 3-Clause License
8
+
9
+ Copyright (c) 2022, Anaconda, Inc.
10
+ Copyright (c) 2023, conda
11
+ All rights reserved.
12
+
13
+ Redistribution and use in source and binary forms, with or without
14
+ modification, are permitted provided that the following conditions are met:
15
+
16
+ * Redistributions of source code must retain the above copyright
17
+ notice, this list of conditions and the following disclaimer.
18
+ * Redistributions in binary form must reproduce the above copyright
19
+ notice, this list of conditions and the following disclaimer in the
20
+ documentation and/or other materials provided with the distribution.
21
+ * Neither the name of the copyright holder nor the names of its
22
+ contributors may be used to endorse or promote products
23
+ derived from this software without specific prior written permission.
24
+
25
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
26
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
27
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
28
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
29
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
30
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
32
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
34
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
+
36
+ ---
37
+
38
+ This work also includes code borrowed from mamba.utils v0.19, licensed as BSD 3-Clause
39
+ License-File: AUTHORS.md
40
+ License-File: LICENSE
41
+ Classifier: License :: OSI Approved :: BSD License
42
+ Classifier: Programming Language :: Python :: 3
43
+ Classifier: Programming Language :: Python :: 3 :: Only
44
+ Classifier: Programming Language :: Python :: 3.10
45
+ Classifier: Programming Language :: Python :: 3.11
46
+ Classifier: Programming Language :: Python :: 3.12
47
+ Classifier: Programming Language :: Python :: 3.13
48
+ Classifier: Programming Language :: Python :: Implementation :: CPython
49
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
50
+ Requires-Python: >=3.10
51
+ Requires-Dist: boltons>=23.0.0
52
+ Requires-Dist: conda>=25.9
53
+ Requires-Dist: msgpack>=1.1.1
54
+ Requires-Dist: requests<3,>=2.28.0
55
+ Requires-Dist: zstandard>=0.15
56
+ Description-Content-Type: text/markdown
57
+
58
+ # conda-libmamba-solver
59
+
60
+ The fast mamba solver, now in conda!
61
+
62
+ ## What is this exactly?
63
+
64
+ conda-libmamba-solver is a new solver for the
65
+ [conda package manager](https://docs.conda.io/) which uses the solver from the
66
+ [mamba project](https://mamba.readthedocs.io/) behind the scenes, while
67
+ carefully implementing conda's functionality and expected behaviors on top.
68
+ The library used by mamba to do the heavy-lifting is called [libsolv](https://github.com/openSUSE/libsolv).
69
+
70
+ Additional information about the project can be found in the blog post on Anaconda's weblog:
71
+ [A Faster Solver for Conda: Libmamba](https://www.anaconda.com/blog/a-faster-conda-for-a-growing-community).
72
+
73
+ ## Documentation
74
+
75
+ Check the [documentation](https://conda.github.io/conda-libmamba-solver/) for
76
+ instructions on how to install, use and make the most out the new conda solver!
77
+
78
+
79
+ ## Build status
80
+
81
+ | [![Build status](https://github.com/conda/conda-libmamba-solver/actions/workflows/tests.yml/badge.svg)](https://github.com/conda/conda-libmamba-solver/actions/workflows/tests.yml?query=branch%3Amain) [![Docs status](https://github.com/conda/conda-libmamba-solver/actions/workflows/docs.yml/badge.svg)](https://github.com/conda/conda-libmamba-solver/actions/workflows/docs.yml?query=branch%3Amain) [![codecov](https://codecov.io/gh/conda/conda-libmamba-solver/branch/main/graph/badge.svg)](https://codecov.io/gh/conda/conda-libmamba-solver) [![pre-commit.ci status](https://results.pre-commit.ci/badge/github/conda/conda-libmamba-solver/main.svg)](https://results.pre-commit.ci/latest/github/conda/conda-libmamba-solver/main) [![CalVer version used YY.MM.MICRO](https://img.shields.io/badge/calver-YY.MM.MICRO-22bfda.svg?style=flat-square)](https://calver.org) | [![Anaconda-Server Badge](https://anaconda.org/conda-canary/conda-libmamba-solver/badges/latest_release_date.svg)](https://anaconda.org/conda-canary/conda-libmamba-solver) |
82
+ | --- | :-: |
83
+ | [`conda install defaults::conda-libmamba-solver`](https://anaconda.org/anaconda/conda-libmamba-solver) | [![Anaconda-Server Badge](https://anaconda.org/anaconda/conda-libmamba-solver/badges/version.svg)](https://anaconda.org/anaconda/conda-libmamba-solver) |
84
+ | [`conda install conda-forge::conda-libmamba-solver`](https://anaconda.org/conda-forge/conda-libmamba-solver) | [![Anaconda-Server Badge](https://anaconda.org/conda-forge/conda-libmamba-solver/badges/version.svg)](https://anaconda.org/conda-forge/conda-libmamba-solver) |
85
+ | [`conda install conda-canary/label/dev::conda-libmamba-solver`](https://anaconda.org/conda-canary/conda-libmamba-solver) | [![Anaconda-Server Badge](https://anaconda.org/conda-canary/conda-libmamba-solver/badges/version.svg)](https://anaconda.org/conda-canary/conda-libmamba-solver) |
data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/RECORD ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ conda_libmamba_solver-25.11.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ conda_libmamba_solver-25.11.0.dist-info/METADATA,sha256=o_oBj8RWJpOCXYes0y_xHvd0ah1I0_yWpKtS5297cQw,5662
3
+ conda_libmamba_solver-25.11.0.dist-info/RECORD,,
4
+ conda_libmamba_solver-25.11.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ conda_libmamba_solver-25.11.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
6
+ conda_libmamba_solver-25.11.0.dist-info/direct_url.json,sha256=rNWoGbk7ksTJ2DfIZjsYd-dXx8QUlaoMivpQcp2YVPU,103
7
+ conda_libmamba_solver-25.11.0.dist-info/entry_points.txt,sha256=JHAxZa0f1SAUCgVquOdUUOGqSRcMyz3rkpiXL1Ploc8,61
8
+ conda_libmamba_solver-25.11.0.dist-info/licenses/AUTHORS.md,sha256=_NosLCcbDN9KQZSQXyQmP-0kWKdoxEHt3K3OdocuyuE,460
9
+ conda_libmamba_solver-25.11.0.dist-info/licenses/LICENSE,sha256=s5c3lMy_FgHDSK7ltL_gNFw7zSHcDcgKOEQbmUBf67A,1663
10
+ conda_libmamba_solver/__init__.py,sha256=Er13Z9pJpQJ1pZna7WBWjS2q-ZWP6MbTRvNbtuE8GVs,564
11
+ conda_libmamba_solver/__pycache__/__init__.cpython-314.pyc,,
12
+ conda_libmamba_solver/__pycache__/conda_build_exceptions.cpython-314.pyc,,
13
+ conda_libmamba_solver/__pycache__/exceptions.cpython-314.pyc,,
14
+ conda_libmamba_solver/__pycache__/index.cpython-314.pyc,,
15
+ conda_libmamba_solver/__pycache__/mamba_utils.cpython-314.pyc,,
16
+ conda_libmamba_solver/__pycache__/plugin.cpython-314.pyc,,
17
+ conda_libmamba_solver/__pycache__/repoquery.cpython-314.pyc,,
18
+ conda_libmamba_solver/__pycache__/shards.cpython-314.pyc,,
19
+ conda_libmamba_solver/__pycache__/shards_cache.cpython-314.pyc,,
20
+ conda_libmamba_solver/__pycache__/shards_subset.cpython-314.pyc,,
21
+ conda_libmamba_solver/__pycache__/shards_typing.cpython-314.pyc,,
22
+ conda_libmamba_solver/__pycache__/solver.cpython-314.pyc,,
23
+ conda_libmamba_solver/__pycache__/state.cpython-314.pyc,,
24
+ conda_libmamba_solver/__pycache__/utils.cpython-314.pyc,,
25
+ conda_libmamba_solver/conda_build_exceptions.py,sha256=uPc7PKn9IN-V44wEpKeZHZpojiH2hwuQKdBzCfZHEK0,1396
26
+ conda_libmamba_solver/exceptions.py,sha256=AqESkZmhveRKxUfRTo-QSPEWFb1DIeX6W8-wYZ9qhvM,485
27
+ conda_libmamba_solver/index.py,sha256=xTcHO8lr29eRrz_e3qsWlB4lZOLuoDf8LHmaRTRWXLQ,31625
28
+ conda_libmamba_solver/mamba_utils.py,sha256=aWL-IXqPx9akbkk7jgOeJgjhdzYOBZqluEyrR9LJxCE,6879
29
+ conda_libmamba_solver/plugin.py,sha256=_P6NUwil6vTEt5Pp1jm9qkKUmq4qou5vePBdfG_I2AU,1149
30
+ conda_libmamba_solver/repoquery.py,sha256=2IrzDBcfeM6Gq7vN0fkmJN5TKWMM8TvvpdH1dIbhOf8,7610
31
+ conda_libmamba_solver/shards.py,sha256=RK3Caz2e42FHsi-Go8b6eUU1pJMlPE9HwdQ2fVA5xb4,24542
32
+ conda_libmamba_solver/shards_cache.py,sha256=-KR98kr8at8-lAt_w1coRmMfRxCGLo-9BEz-QwJjGTY,5005
33
+ conda_libmamba_solver/shards_subset.py,sha256=EorIgQAD-f9rmnElwY1-D9vDrX8fzIgkeCPvp-DqOok,21890
34
+ conda_libmamba_solver/shards_typing.py,sha256=xxeOQzb9nqk0gN8bJyr0bhM7I30mk3RVpy81fBgSADU,1574
35
+ conda_libmamba_solver/solver.py,sha256=KSk3mNq-PbytZaCSwvrjOz1ezjedAm-LG0NxZH_8mAA,48671
36
+ conda_libmamba_solver/state.py,sha256=BPWt8O706ArlKBtumRuGJNkO3ZNFIzA3j-TcX2PzlRU,33572
37
+ conda_libmamba_solver/utils.py,sha256=QoorafpuqtBbn4YPhmjprAelIsp-2SInA84z0QhztW0,3833
data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/REQUESTED ADDED
File without changes
data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/direct_url.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"dir_info": {}, "url": "file:///C:/miniconda3/conda-bld/conda-libmamba-solver_1764245615235/work/src"}
data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/entry_points.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [conda]
2
+ conda-libmamba-solver = conda_libmamba_solver.plugin
data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __version__ = "0.12.0"
data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/create.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tools for creating ``.conda``-format archives.
3
+
4
+ Uses ``tempfile.SpooledTemporaryFile`` to buffer ``pkg-*.tar`` and
5
+ ``info-*.tar``, then compress directly into an open `ZipFile` at the end.
6
+ `SpooledTemporaryFile` buffers the first 10MB of the package and its metadata in
7
+ memory, but writes out to disk for larger packages.
8
+
9
+ Uses more disk space than ``conda-package-handling`` (temporary uncompressed
10
+ tarballs of the package contents) but accepts streams instead of just
11
+ files-on-the-filesystem.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import shutil
18
+ import tarfile
19
+ import tempfile
20
+ import zipfile
21
+ from collections.abc import Iterator
22
+ from contextlib import contextmanager
23
+ from pathlib import Path
24
+ from typing import Callable
25
+
26
+ import zstandard
27
+
28
+ # increase to reduce speed and increase compression (levels above 19 use much
29
+ # more memory)
30
+ ZSTD_COMPRESS_LEVEL = 19
31
+ # increase to reduce compression and increase speed
32
+ ZSTD_COMPRESS_THREADS = 1
33
+
34
+ CONDA_PACKAGE_FORMAT_VERSION = 2
35
+
36
+ # Account for growth from "2 GB of /dev/urandom" to not exceed ZIP64_LIMIT after
37
+ # compression
38
+ CONDA_ZIP64_LIMIT = zipfile.ZIP64_LIMIT - (1 << 18) - 1
39
+
40
+
41
+ def anonymize(tarinfo: tarfile.TarInfo):
42
+ """
43
+ Pass to ``tarfile.add(..., filter=anonymize)`` to anonymize uid/gid.
44
+
45
+ Does not anonymize mtime or any other field.
46
+ """
47
+ tarinfo.uid = tarinfo.gid = 0
48
+ tarinfo.uname = tarinfo.gname = ""
49
+ return tarinfo
50
+
51
+
52
+ class CondaTarFile(tarfile.TarFile):
53
+ """
54
+ Subclass of :external+python:py:class:`tarfile.TarFile` that adds members to
55
+ a second ``info`` tar if they match ``is_info(name)``.
56
+
57
+ Create this with ``conda_builder(...)`` which sets up the component
58
+ archives, then wraps them into a ``.conda`` on exit.
59
+
60
+ Only useful for creating, not extracting ``.conda``.
61
+ """
62
+
63
+ info_tar: tarfile.TarFile
64
+ is_info: Callable
65
+
66
+ def __init__(
67
+ self,
68
+ *args,
69
+ info_tar: tarfile.TarFile,
70
+ is_info=lambda name: name.startswith("info/"),
71
+ **kwargs,
72
+ ):
73
+ super().__init__(*args, **kwargs)
74
+ self.info_tar = info_tar
75
+ self.is_info = is_info
76
+
77
+ def addfile(self, tarinfo, fileobj=None):
78
+ """
79
+ Add the TarInfo object ``tarinfo`` to the archive. If ``fileobj`` is
80
+ given, it should be a binary file, and tarinfo.size bytes are read from
81
+ it and added to the archive. You can create TarInfo objects directly, or
82
+ by using ``gettarinfo()``.
83
+
84
+ If ``self.is_info(tarinfo.name)`` returns ``True``, add ``tarinfo`` to
85
+ ``self.info_tar`` instead.
86
+ """
87
+ if self.is_info(tarinfo.name):
88
+ return self.info_tar.addfile(tarinfo, fileobj=fileobj)
89
+ else:
90
+ return super().addfile(tarinfo, fileobj)
91
+
92
+
93
+ @contextmanager
94
+ def conda_builder(
95
+ stem,
96
+ path,
97
+ *,
98
+ compressor: Callable[
99
+ [], zstandard.ZstdCompressor
100
+ ] = lambda: zstandard.ZstdCompressor(
101
+ level=ZSTD_COMPRESS_LEVEL, threads=ZSTD_COMPRESS_THREADS
102
+ ),
103
+ is_info: Callable[[str], bool] = lambda filename: filename.startswith("info/"),
104
+ encoding="utf-8",
105
+ ) -> Iterator[CondaTarFile]:
106
+ """
107
+ Produce a ``TarFile`` subclass used to build a ``.conda`` package. The
108
+ subclass delegates ``addfile()`` to the ``info-`` component when ``is_info``
109
+ returns True.
110
+
111
+ When the context manager exits, ``{path}/{stem}.conda`` is written with
112
+ the component tar archives.
113
+
114
+ Args:
115
+ stem: output filename without extension
116
+
117
+ path: destination path for transmuted .conda package compressor: A
118
+ function that creates instances of ``zstandard.ZstdCompressor()``.
119
+
120
+ encoding: passed to TarFile constructor. Keep default "utf-8" for valid
121
+ .conda.
122
+
123
+ Yields:
124
+ ``CondaTarFile``
125
+ """
126
+ output_path = Path(path, f"{stem}.conda")
127
+ with (
128
+ tempfile.SpooledTemporaryFile() as info_file,
129
+ tempfile.SpooledTemporaryFile() as pkg_file,
130
+ ):
131
+ with (
132
+ tarfile.TarFile(fileobj=info_file, mode="w", encoding=encoding) as info_tar,
133
+ CondaTarFile(
134
+ fileobj=pkg_file,
135
+ mode="w",
136
+ info_tar=info_tar,
137
+ is_info=is_info,
138
+ encoding=encoding,
139
+ ) as pkg_tar,
140
+ ):
141
+ # If we wanted to compress these at a low setting to save temporary
142
+ # space, we could insert a file object that counts bytes written in
143
+ # front of a zstd (level between 1..3) compressor.
144
+ yield pkg_tar
145
+
146
+ info_tar.close()
147
+ pkg_tar.close()
148
+
149
+ info_size = info_file.tell()
150
+ pkg_size = pkg_file.tell()
151
+
152
+ info_file.seek(0)
153
+ pkg_file.seek(0)
154
+
155
+ with zipfile.ZipFile(
156
+ output_path,
157
+ "x", # x to not append to existing
158
+ compresslevel=zipfile.ZIP_STORED,
159
+ ) as conda_file:
160
+ # Use a maximum of one Zstd compressor, stream_writer at a time to save
161
+ # # memory.
162
+ data_compress = compressor()
163
+
164
+ pkg_metadata = {"conda_pkg_format_version": CONDA_PACKAGE_FORMAT_VERSION}
165
+ conda_file.writestr("metadata.json", json.dumps(pkg_metadata))
166
+
167
+ with (
168
+ conda_file.open(
169
+ f"pkg-{stem}.tar.zst",
170
+ "w",
171
+ force_zip64=(pkg_size > CONDA_ZIP64_LIMIT),
172
+ ) as pkg_file_zip,
173
+ data_compress.stream_writer(
174
+ pkg_file_zip, size=pkg_size, closefd=False
175
+ ) as pkg_stream,
176
+ ):
177
+ shutil.copyfileobj(pkg_file._file, pkg_stream)
178
+
179
+ with (
180
+ conda_file.open(
181
+ f"info-{stem}.tar.zst",
182
+ "w",
183
+ force_zip64=(info_size > CONDA_ZIP64_LIMIT),
184
+ ) as info_file_zip,
185
+ data_compress.stream_writer(
186
+ info_file_zip,
187
+ size=info_size,
188
+ closefd=False,
189
+ ) as info_stream,
190
+ ):
191
+ shutil.copyfileobj(info_file._file, info_stream)
data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/exceptions.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tarfile
2
+
3
+
4
+ class SafetyError(tarfile.TarError):
5
+ def __init__(self, msg, *args, **kw):
6
+ msg = f"Error with archive. {msg}"
7
+ super().__init__(msg)
8
+
9
+
10
+ class CaseInsensitiveFileSystemError(OSError):
11
+ def __init__(self):
12
+ message = """\
13
+ Cannot extract package to a case-insensitive file system. Your install
14
+ destination does not differentiate between upper and lowercase characters, and
15
+ this breaks things. Try installing to a location that is case-sensitive. Windows
16
+ drives are usually the culprit here - can you install to a native Unix drive, or
17
+ turn on case sensitivity for this (Windows) location?
18
+ """
19
+ super().__init__(message)
data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/extract.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Extract package to directory, with checks against tar members extracting outside
3
+ the target directory.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import tarfile
10
+ from collections.abc import Generator
11
+ from errno import ELOOP
12
+ from pathlib import Path
13
+
14
+ from . import exceptions, package_streaming
15
+
16
+ __all__ = ["extract_stream", "extract"]
17
+ HAS_TAR_FILTER = hasattr(tarfile, "tar_filter")
18
+
19
+
20
+ def extract_stream(
21
+ stream: Generator[tuple[tarfile.TarFile, tarfile.TarInfo]],
22
+ dest_dir: Path | str,
23
+ tar_filter: str | None = None,
24
+ ):
25
+ """
26
+ Pipe ``stream_conda_component`` output here to extract every member into
27
+ dest_dir.
28
+
29
+ For ``.conda`` will need to be called twice (for info and pkg components);
30
+ for ``.tar.bz2`` every member is extracted.
31
+ """
32
+ dest_dir = os.path.realpath(dest_dir)
33
+
34
+ def is_within_dest_dir(name):
35
+ abs_target = os.path.realpath(os.path.join(dest_dir, name))
36
+ prefix = os.path.commonpath((dest_dir, abs_target))
37
+ return prefix == dest_dir
38
+
39
+ for tar_file, _ in stream:
40
+ # careful not to seek backwards
41
+ def checked_members():
42
+ # from conda_package_handling
43
+ for member in tar_file:
44
+ if not is_within_dest_dir(member.name):
45
+ raise exceptions.SafetyError(f"contains unsafe path: {member.name}")
46
+ yield member
47
+
48
+ try:
49
+ # Drop checked_members() when HAS_TAR_FILTER once we are 100%
50
+ # certain the stdlib filter maintains same permissions as
51
+ # checked_members().
52
+ tar_args = {"path": dest_dir, "members": checked_members()}
53
+ if HAS_TAR_FILTER:
54
+ tar_args["filter"] = tar_filter or "fully_trusted"
55
+ tar_file.extractall(**tar_args)
56
+ except OSError as e:
57
+ if e.errno == ELOOP:
58
+ raise exceptions.CaseInsensitiveFileSystemError() from e
59
+ raise
60
+
61
+ # next iteraton of for loop raises GeneratorExit in stream
62
+ stream.close()
63
+
64
+
65
+ def extract(filename, dest_dir=None, fileobj=None):
66
+ """
67
+ Extract all components of conda package to dest_dir.
68
+
69
+ fileobj: must be seekable if provided, if a ``.conda`` package.
70
+ """
71
+ assert dest_dir, "dest_dir is required"
72
+ if str(filename).endswith(".conda"):
73
+ components = [
74
+ package_streaming.CondaComponent.pkg,
75
+ package_streaming.CondaComponent.info,
76
+ ]
77
+ else: # .tar.bz2 doesn't filter by component
78
+ components = [package_streaming.CondaComponent.pkg]
79
+
80
+ closefd = False
81
+ if not fileobj:
82
+ fileobj = open(filename, "rb")
83
+ closefd = True
84
+
85
+ try:
86
+ for component in components:
87
+ stream = package_streaming.stream_conda_component(
88
+ filename, fileobj, component=component
89
+ )
90
+ extract_stream(stream, dest_dir)
91
+ finally:
92
+ if closefd:
93
+ fileobj.close()
data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/lazy_wheel.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Lazy ZIP over HTTP"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import zipfile
7
+ from bisect import bisect_left, bisect_right
8
+ from collections.abc import Iterator
9
+ from contextlib import contextmanager
10
+ from tempfile import NamedTemporaryFile
11
+ from typing import Any
12
+ from zipfile import BadZipfile, ZipFile
13
+
14
+ from requests import HTTPError, Session
15
+ from requests.models import CONTENT_CHUNK_SIZE, Response
16
+
17
+ # from pip 22.0.3 with fixes & remove imports from pip
18
+
19
+
20
+ log = logging.getLogger(__name__)
21
+
22
+ # If-Match (etag) to detect file changed during fetch would also be nice
23
+ HEADERS = {"Accept-Encoding": "identity"}
24
+
25
+
26
+ class HTTPRangeRequestUnsupported(Exception):
27
+ pass
28
+
29
+
30
+ class LazyZipOverHTTP:
31
+ """File-like object mapped to a ZIP file over HTTP.
32
+
33
+ This uses HTTP range requests to lazily fetch the file's content,
34
+ which is supposed to be fed to ZipFile. If such requests are not
35
+ supported by the server, raise HTTPRangeRequestUnsupported
36
+ during initialization.
37
+ """
38
+
39
+ def __init__(
40
+ self,
41
+ url: str,
42
+ session: Session,
43
+ chunk_size: int = CONTENT_CHUNK_SIZE,
44
+ fall_back_to_full_download: bool = False,
45
+ ) -> None:
46
+ """
47
+ Initialize a LazyZipOverHTTP object.
48
+
49
+ :param session: The session to use for web requests.
50
+ :param chunk_size: The chunk size to use for downloading.
51
+ :param fall_back_to_full_download: If true, we fall back to downloading
52
+ the whole file if the server incorrectly responds with 416
53
+ (Range Not Satisfiable) to an HTTP range request.
54
+ """
55
+ # if CONTENT_CHUNK_SIZE is bigger than the file:
56
+ # In [8]: response.headers["Content-Range"]
57
+ # Out[8]: 'bytes 0-3133374/3133375'
58
+
59
+ self._request_count = 0
60
+
61
+ self._session, self._url, self._chunk_size = session, url, chunk_size
62
+
63
+ self._fall_back_to_full_download: bool = fall_back_to_full_download
64
+ self._has_streaming_support: bool = True
65
+
66
+ # If the server returns 416 (Range Not Satisfiable) and the fallback is
67
+ # enabled, we request the whole file and set this to False. Some package
68
+ # servers incorrectly respond with 416 (Range Not Satisfiable) if the
69
+ # file is smaller than the range requested.
70
+
71
+ # initial range request for the end of the file
72
+ # if the server does not support range requests, this sets
73
+ # _has_streaming_support to False
74
+ tail = self._stream_response(start="", end=CONTENT_CHUNK_SIZE)
75
+ # e.g. {'accept-ranges': 'bytes', 'content-length': '10240',
76
+ # 'content-range': 'bytes 12824-23063/23064', 'last-modified': 'Sat, 16
77
+ # Apr 2022 13:03:02 GMT', 'date': 'Thu, 21 Apr 2022 11:34:04 GMT'}
78
+
79
+ if self._has_streaming_support and tail.status_code != 206:
80
+ raise HTTPRangeRequestUnsupported("range request is not supported")
81
+
82
+ if self._has_streaming_support:
83
+ # lowercase content-range to support s3
84
+ self._length = int(tail.headers["content-range"].partition("/")[-1])
85
+ else:
86
+ # the file is already downloaded
87
+ self._length = len(tail.content)
88
+
89
+ self._file = NamedTemporaryFile()
90
+ self.truncate(self._length)
91
+
92
+ # length is also in Content-Length and Content-Range header
93
+ with self._stay():
94
+ if self._has_streaming_support:
95
+ content_length = int(tail.headers["content-length"])
96
+ if hasattr(tail, "content"):
97
+ assert content_length == len(tail.content)
98
+ else:
99
+ content_length = len(tail.content)
100
+ self.seek(self._length - content_length)
101
+ for chunk in tail.iter_content(self._chunk_size):
102
+ self._file.write(chunk)
103
+ self._left: list[int] = [self._length - content_length]
104
+ self._right: list[int] = [self._length - 1]
105
+
106
+ @property
107
+ def mode(self) -> str:
108
+ """Opening mode, which is always rb."""
109
+ return "rb"
110
+
111
+ @property
112
+ def name(self) -> str:
113
+ """Path to the underlying file."""
114
+ return self._file.name
115
+
116
+ def seekable(self) -> bool:
117
+ """Return whether random access is supported, which is True."""
118
+ return True
119
+
120
+ def close(self) -> None:
121
+ """Close the file."""
122
+ self._file.close()
123
+
124
+ @property
125
+ def closed(self) -> bool:
126
+ """Whether the file is closed."""
127
+ return self._file.closed
128
+
129
+ def read(self, size: int = -1) -> bytes:
130
+ """Read up to size bytes from the object and return them.
131
+
132
+ As a convenience, if size is unspecified or -1,
133
+ all bytes until EOF are returned. Fewer than
134
+ size bytes may be returned if EOF is reached.
135
+ """
136
+ # BUG does not download correctly if size is unspecified
137
+ download_size = size
138
+ start, length = self.tell(), self._length
139
+ stop = length if size < 0 else min(start + download_size, length)
140
+ start = max(0, stop - download_size)
141
+ self._download(start, stop - 1)
142
+ return self._file.read(size)
143
+
144
+ def readable(self) -> bool:
145
+ """Return whether the file is readable, which is True."""
146
+ return True
147
+
148
+ def seek(self, offset: int, whence: int = 0) -> int:
149
+ """Change stream position and return the new absolute position.
150
+
151
+ Seek to offset relative position indicated by whence:
152
+ * 0: Start of stream (the default). pos should be >= 0;
153
+ * 1: Current position - pos may be negative;
154
+ * 2: End of stream - pos usually negative.
155
+ """
156
+ return self._file.seek(offset, whence)
157
+
158
+ def tell(self) -> int:
159
+ """Return the current position."""
160
+ return self._file.tell()
161
+
162
+ def truncate(self, size: int | None = None) -> int:
163
+ """Resize the stream to the given size in bytes.
164
+
165
+ If size is unspecified resize to the current position.
166
+ The current stream position isn't changed.
167
+
168
+ Return the new file size.
169
+ """
170
+ return self._file.truncate(size)
171
+
172
+ def writable(self) -> bool:
173
+ """Return False."""
174
+ return False
175
+
176
+ def __enter__(self) -> LazyZipOverHTTP:
177
+ self._file.__enter__()
178
+ return self
179
+
180
+ def __exit__(self, *exc: Any) -> bool | None:
181
+ return self._file.__exit__(*exc)
182
+
183
+ @contextmanager
184
+ def _stay(self) -> Iterator[None]:
185
+ """Return a context manager keeping the position.
186
+
187
+ At the end of the block, seek back to original position.
188
+ """
189
+ pos = self.tell()
190
+ try:
191
+ yield
192
+ finally:
193
+ self.seek(pos)
194
+
195
+ def _check_zip(self) -> None:
196
+ """Check and download until the file is a valid ZIP."""
197
+ end = self._length - 1
198
+ for start in reversed(range(0, end, self._chunk_size)):
199
+ self._download(start, end)
200
+ with self._stay():
201
+ try:
202
+ # For read-only ZIP files, ZipFile only needs
203
+ # methods read, seek, seekable and tell.
204
+ ZipFile(self) # type: ignore
205
+ except BadZipfile:
206
+ pass
207
+ else:
208
+ break
209
+
210
+ def _stream_response(
211
+ self, start: int | str, end: int, base_headers: dict[str, str] = HEADERS
212
+ ) -> Response:
213
+ """
214
+ Return HTTP response to a range request from start to end.
215
+ If the does not support range requests, the whole file is requested.
216
+
217
+ :param start: if "", request `end` bytes from end of file.
218
+ """
219
+ headers = base_headers.copy()
220
+ headers["Range"] = f"bytes={start}-{end}"
221
+ log.debug("%s", headers["Range"])
222
+ # TODO: Get range requests to be correctly cached
223
+ headers["Cache-Control"] = "no-cache"
224
+ self._request_count += 1
225
+
226
+ if self._has_streaming_support:
227
+ response = self._session.get(self._url, headers=headers, stream=True)
228
+
229
+ if response.status_code == 416 and self._fall_back_to_full_download:
230
+ # Range Not Satisfiable -> enable fallback
231
+ self._has_streaming_support = False
232
+ elif response.status_code == 416:
233
+ # fallback disabled, print helpful error message
234
+ raise HTTPError(
235
+ "The server returned 416 (Range Not Satisfiable). "
236
+ "This can occur on a buggy server if the file is smaller "
237
+ "than the range requested. Set the fall_back_to_full_download flag "
238
+ "to work around this issue.",
239
+ response=response,
240
+ )
241
+ else:
242
+ response.raise_for_status()
243
+ return response
244
+
245
+ # no streaming support, try to get the whole file
246
+ del headers["Range"]
247
+ response = self._session.get(self._url, headers=headers, stream=True)
248
+
249
+ response.raise_for_status()
250
+ return response
251
+
252
+ def _merge(
253
+ self, start: int, end: int, left: int, right: int
254
+ ) -> Iterator[tuple[int, int]]:
255
+ """Return an iterator of intervals to be fetched.
256
+
257
+ Args:
258
+ start (int): Start of needed interval
259
+ end (int): End of needed interval
260
+ left (int): Index of first overlapping downloaded data
261
+ right (int): Index after last overlapping downloaded data
262
+ """
263
+ lslice, rslice = self._left[left:right], self._right[left:right]
264
+ i = start = min([start] + lslice[:1])
265
+ end = max([end] + rslice[-1:])
266
+ for j, k in zip(lslice, rslice):
267
+ if j > i:
268
+ yield i, j - 1
269
+ i = k + 1
270
+ if i <= end:
271
+ yield i, end
272
+ self._left[left:right], self._right[left:right] = [start], [end]
273
+
274
+ def _download(self, start: int, end: int) -> None:
275
+ """
276
+ Download bytes from start to end inclusively. If the server does not support
277
+ streaming for this file, this does nothing as the entire file is already
278
+ downloaded.
279
+ """
280
+ # these assertions should hold, but read() violates them
281
+ # assert 0 <= start <= end
282
+ # assert end < self._length
283
+
284
+ with self._stay():
285
+ left = bisect_left(self._right, start)
286
+ right = bisect_right(self._left, end)
287
+ for start, end in self._merge(start, end, left, right):
288
+ response = self._stream_response(start, end)
289
+ self.seek(start)
290
+ for chunk in response.iter_content(self._chunk_size):
291
+ self._file.write(chunk)
292
+
293
+
294
+ class LazyConda(LazyZipOverHTTP):
295
+ def prefetch(self, conda_file_id):
296
+ """
297
+ Conda fork specific. Prefetch the `.info` range from the remote archive.
298
+ Reduces number of Range requests to 2 or 3 (1 or 2 for the directory, 1
299
+ for the file).
300
+
301
+ conda_file_id: name of .conda without path or `.conda` extension
302
+ """
303
+ target_file = f"info-{conda_file_id}.tar.zst"
304
+ with self._stay(): # not strictly necessary
305
+ # try to read entire conda info in one request
306
+ zf = zipfile.ZipFile(self)
307
+ infolist = zf.infolist()
308
+ for i, info in enumerate(infolist):
309
+ if info.filename == target_file:
310
+ # could be incorrect if zipfile was concatenated to another
311
+ # file (not likely for .conda)
312
+ start = info.header_offset
313
+ try:
314
+ end = infolist[i + 1].header_offset
315
+ # or info.header_offset
316
+ # + len(info.filename)
317
+ # + len(info.extra)
318
+ # + info.compress_size
319
+ # (unless Zip64)
320
+ except IndexError:
321
+ end = zf.start_dir
322
+ self.seek(start)
323
+ self.read(end - start)
324
+ log.debug(
325
+ "prefetch %s-%s",
326
+ info.header_offset,
327
+ end,
328
+ )
329
+ break
330
+ else:
331
+ log.debug("no zip prefetch")
data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/package_streaming.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Unpack conda packages without using a temporary file.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import bz2
8
+ import os
9
+ import os.path
10
+ import tarfile
11
+ import zipfile
12
+ from collections.abc import Generator
13
+ from enum import Enum
14
+
15
+ # acquire umask taking advantage of import system lock, instead of possibly in
16
+ # multiple threads at once.
17
+ UMASK = os.umask(0)
18
+ os.umask(UMASK)
19
+
20
+ try:
21
+ import zstandard
22
+ except ImportError:
23
+ import warnings
24
+
25
+ warnings.warn("zstandard could not be imported. Running without .conda support.")
26
+
27
+ zstandard = None
28
+
29
+
30
+ class CondaComponent(Enum):
31
+ pkg = "pkg"
32
+ info = "info"
33
+
34
+ def __str__(self):
35
+ return self.value
36
+
37
+
38
+ class TarfileNoSameOwner(tarfile.TarFile):
39
+ def __init__(self, *args, umask: int | None = None, **kwargs):
40
+ """Open an (uncompressed) tar archive `name'. `mode' is either 'r' to
41
+ read from an existing archive, 'a' to append data to an existing
42
+ file or 'w' to create a new file overwriting an existing one. `mode'
43
+ defaults to 'r'.
44
+ If `fileobj' is given, it is used for reading or writing data. If it
45
+ can be determined, `mode' is overridden by `fileobj's mode.
46
+ `fileobj' is not closed, when TarFile is closed.
47
+ """
48
+ super().__init__(*args, **kwargs)
49
+ self.umask = umask if umask is not None else UMASK
50
+
51
+ def chown(self, tarinfo, targetpath, numeric_owner):
52
+ """
53
+ Override chown to be a no-op, since we don't want to preserve ownership
54
+ here. (tarfile.TarFile only lets us toggle all of (chown, chmod, mtime))
55
+ """
56
+ return
57
+
58
+ def chmod(self, tarinfo, targetpath):
59
+ """
60
+ Set file permissions of targetpath according to tarinfo, respecting
61
+ umask.
62
+ """
63
+ if tarinfo.mode is None:
64
+ return
65
+
66
+ try:
67
+ os.chmod(targetpath, tarinfo.mode & (-1 & (~self.umask)))
68
+ except OSError as e:
69
+ raise tarfile.ExtractError("could not change mode") from e
70
+
71
+
72
+ def tar_generator(
73
+ fileobj, tarfile_open=TarfileNoSameOwner.open, closefd=False, *, encoding="utf-8"
74
+ ) -> Generator[tuple[tarfile.TarFile, tarfile.TarInfo]]:
75
+ """
76
+ Yield (tar, member) from fileobj.
77
+
78
+ Args:
79
+ fileobj: file-like object
80
+
81
+ encoding: "utf-8" passed to TarFile.open(); can be changed for testing.
82
+ """
83
+ # tarfile will not close fileobj because _extfileobj is True
84
+ # caller should take care to close files all the way back to the http request...
85
+ try:
86
+ with tarfile_open(fileobj=fileobj, mode="r|", encoding=encoding) as tar:
87
+ for member in tar:
88
+ yield tar, member
89
+ finally:
90
+ if closefd:
91
+ fileobj.close()
92
+
93
+
94
+ def stream_conda_info(
95
+ filename, fileobj=None
96
+ ) -> Generator[tuple[tarfile.TarFile, tarfile.TarInfo]]:
97
+ """
98
+ Yield members from conda's embedded info/ tarball.
99
+
100
+ For .tar.bz2 packages, yield all members.
101
+
102
+ Yields (tar, member) tuples. You must only use the current member to
103
+ prevent tar seeks and scans.
104
+
105
+ To extract to disk, it's possible to call ``tar.extractall(path)`` on the
106
+ first result and then ignore the rest of this generator. ``extractall`` takes
107
+ care of some directory permissions/mtime issues, compared to ``extract`` or
108
+ writing out the file objects yourself.
109
+ """
110
+ component = "info"
111
+ return stream_conda_component(filename, fileobj, component)
112
+
113
+
114
+ def stream_conda_component(
115
+ filename,
116
+ fileobj=None,
117
+ component: CondaComponent | str = CondaComponent.pkg,
118
+ *,
119
+ encoding="utf-8",
120
+ ) -> Generator[tuple[tarfile.TarFile, tarfile.TarInfo]]:
121
+ """
122
+ Yield members from .conda's embedded {component}- tarball. "info" or "pkg".
123
+
124
+ For .tar.bz2 packages, yield all members.
125
+
126
+ Yields (tar, member) tuples. You must only use the current member to
127
+ prevent tar seeks and scans.
128
+
129
+ To extract to disk, it's possible to call ``tar.extractall(path)`` on the
130
+ first result and then ignore the rest of this generator. ``extractall`` takes
131
+ care of some directory permissions/mtime issues, compared to ``extract`` or
132
+ writing out the file objects yourself.
133
+ """
134
+ if str(filename).endswith(".conda"):
135
+ if zstandard is None:
136
+ raise RuntimeError("Cannot unpack `.conda` without zstandard")
137
+
138
+ zf = zipfile.ZipFile(fileobj or filename)
139
+ stem, _, _ = os.path.basename(filename).rpartition(".")
140
+ component_name = f"{component}-{stem}"
141
+ component_filename = [
142
+ info for info in zf.infolist() if info.filename.startswith(component_name)
143
+ ]
144
+ if not component_filename:
145
+ raise LookupError(f"didn't find {component_name} component in {filename}")
146
+ assert len(component_filename) == 1
147
+ reader = zstandard.ZstdDecompressor().stream_reader(
148
+ zf.open(component_filename[0])
149
+ )
150
+ elif str(filename).endswith(".tar.bz2"):
151
+ reader = bz2.open(fileobj or filename, mode="rb")
152
+ else:
153
+ raise ValueError("unsupported file extension")
154
+ return tar_generator(reader, closefd=fileobj is None, encoding=encoding)
data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/s3.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Adapt s3 to package_streaming
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import typing
8
+ from contextlib import closing
9
+ from typing import Any
10
+
11
+ from . import package_streaming
12
+
13
+ if typing.TYPE_CHECKING: # pragma: no cover
14
+ from mypy_boto3_s3 import Client
15
+ from mypy_boto3_s3.type_defs import GetObjectOutputTypeDef
16
+ else:
17
+ Client = GetObjectOutputTypeDef = None
18
+
19
+ from .url import conda_reader_for_url
20
+
21
+ __all__ = ["stream_conda_info", "conda_reader_for_s3"]
22
+
23
+
24
+ class ResponseFacade:
25
+ def __init__(self, response: GetObjectOutputTypeDef):
26
+ self.response = response
27
+ self.raw: Any = response["Body"]
28
+
29
+ def raise_for_status(self):
30
+ # s3 get_object raises automatically?
31
+ pass
32
+
33
+ @property
34
+ def status_code(self):
35
+ return self.response["ResponseMetadata"]["HTTPStatusCode"]
36
+
37
+ @property
38
+ def headers(self):
39
+ # a case-sensitive dict; keys may be lowercased always?
40
+ return self.response["ResponseMetadata"]["HTTPHeaders"]
41
+
42
+ def iter_content(self, n: int):
43
+ return iter(lambda: self.raw.read(n), b"")
44
+
45
+
46
+ class SessionFacade:
47
+ """
48
+ Make s3 client look just enough like a requests.session for LazyZipOverHTTP
49
+ """
50
+
51
+ def __init__(self, client: Client, bucket: str, key: str):
52
+ self.client = client
53
+ self.bucket = bucket
54
+ self.key = key
55
+
56
+ def get(self, url, *, headers: dict | None = None, stream=True):
57
+ if headers and "Range" in headers:
58
+ response = self.client.get_object(
59
+ Bucket=self.bucket, Key=self.key, Range=headers["Range"]
60
+ )
61
+ else:
62
+ response = self.client.get_object(Bucket=self.bucket, Key=self.key)
63
+ return ResponseFacade(response)
64
+
65
+
66
+ def stream_conda_info(client, bucket, key):
67
+ """
68
+ Yield (tar, member) for conda package.
69
+
70
+ Just "info/" for .conda, all members for tar.
71
+ """
72
+ filename, conda = conda_reader_for_s3(client, bucket, key)
73
+
74
+ with closing(conda):
75
+ yield from package_streaming.stream_conda_info(filename, conda)
76
+
77
+
78
+ def conda_reader_for_s3(client: Client, bucket: str, key: str):
79
+ """
80
+ Return (name, file_like) suitable for package_streaming APIs
81
+ """
82
+ session: Any = SessionFacade(client, bucket, key)
83
+ return conda_reader_for_url(key, session)