Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +2 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/models/siglip/__pycache__/processing_siglip.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/models/siglip/__pycache__/tokenization_siglip.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/models/siglip/configuration_siglip.py +302 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/models/siglip/image_processing_siglip.py +225 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/__init__.py +25 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/_compat.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/applications.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/background.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/concurrency.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/datastructures.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/exceptions.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/logger.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/params.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/responses.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/staticfiles.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/templating.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/types.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/utils.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/websockets.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/applications.py +945 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/concurrency.py +40 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/datastructures.py +83 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/dependencies/__pycache__/utils.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/dependencies/models.py +58 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/exceptions.py +55 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/logger.py +3 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/__init__.py +1 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/__pycache__/asyncexitstack.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/__pycache__/cors.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/__pycache__/gzip.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/__pycache__/httpsredirect.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/__pycache__/trustedhost.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/__pycache__/wsgi.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/asyncexitstack.py +25 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/cors.py +1 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/gzip.py +1 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/httpsredirect.py +3 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/trustedhost.py +3 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/wsgi.py +1 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/py.typed +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/requests.py +2 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/security/__pycache__/base.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/security/__pycache__/http.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/security/api_key.py +98 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/security/base.py +6 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/security/http.py +165 -0
- evalkit_tf437/lib/python3.10/site-packages/fastapi/security/open_id_connect_url.py +34 -0
.gitattributes
CHANGED
|
@@ -1594,3 +1594,5 @@ evalkit_cambrian/lib/libstdc++.so.6.0.29 filter=lfs diff=lfs merge=lfs -text
|
|
| 1594 |
evalkit_internvl/lib/python3.10/site-packages/transformers/models/oneformer/__pycache__/modeling_oneformer.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1595 |
evalkit_internvl/lib/python3.10/site-packages/transformers/models/seamless_m4t/__pycache__/modeling_seamless_m4t.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1596 |
evalkit_tf449/lib/python3.10/site-packages/torch/lib/libtorch_python.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 1594 |
evalkit_internvl/lib/python3.10/site-packages/transformers/models/oneformer/__pycache__/modeling_oneformer.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1595 |
evalkit_internvl/lib/python3.10/site-packages/transformers/models/seamless_m4t/__pycache__/modeling_seamless_m4t.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1596 |
evalkit_tf449/lib/python3.10/site-packages/torch/lib/libtorch_python.so filter=lfs diff=lfs merge=lfs -text
|
| 1597 |
+
evalkit_tf437/lib/python3.10/site-packages/pip/_vendor/idna/__pycache__/idnadata.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1598 |
+
evalkit_tf437/lib/python3.10/site-packages/pip/_vendor/idna/__pycache__/uts46data.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
evalkit_internvl/lib/python3.10/site-packages/transformers/models/siglip/__pycache__/processing_siglip.cpython-310.pyc
ADDED
|
Binary file (6.85 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/transformers/models/siglip/__pycache__/tokenization_siglip.cpython-310.pyc
ADDED
|
Binary file (13.6 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/transformers/models/siglip/configuration_siglip.py
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Siglip model configuration"""
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
from typing import Union
|
| 19 |
+
|
| 20 |
+
from ...configuration_utils import PretrainedConfig
|
| 21 |
+
from ...utils import logging
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
logger = logging.get_logger(__name__)
|
| 25 |
+
|
| 26 |
+
SIGLIP_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
| 27 |
+
"google/siglip-base-patch16-224": "https://huggingface.co/google/siglip-base-patch16-224/resolve/main/config.json",
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class SiglipTextConfig(PretrainedConfig):
|
| 32 |
+
r"""
|
| 33 |
+
This is the configuration class to store the configuration of a [`SiglipTextModel`]. It is used to instantiate a
|
| 34 |
+
Siglip text encoder according to the specified arguments, defining the model architecture. Instantiating a
|
| 35 |
+
configuration with the defaults will yield a similar configuration to that of the text encoder of the Siglip
|
| 36 |
+
[google/siglip-base-patch16-224](https://huggingface.co/google/siglip-base-patch16-224) architecture.
|
| 37 |
+
|
| 38 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 39 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
vocab_size (`int`, *optional*, defaults to 32000):
|
| 43 |
+
Vocabulary size of the Siglip text model. Defines the number of different tokens that can be represented by
|
| 44 |
+
the `inputs_ids` passed when calling [`SiglipModel`].
|
| 45 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 46 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 47 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 48 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 49 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 50 |
+
Number of hidden layers in the Transformer encoder.
|
| 51 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 52 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 53 |
+
max_position_embeddings (`int`, *optional*, defaults to 64):
|
| 54 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 55 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 56 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
|
| 57 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 58 |
+
`"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
|
| 59 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 60 |
+
The epsilon used by the layer normalization layers.
|
| 61 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 62 |
+
The dropout ratio for the attention probabilities.
|
| 63 |
+
pad_token_id (`int`, *optional*, defaults to 1):
|
| 64 |
+
The id of the padding token in the vocabulary.
|
| 65 |
+
bos_token_id (`int`, *optional*, defaults to 49406):
|
| 66 |
+
The id of the beginning-of-sequence token in the vocabulary.
|
| 67 |
+
eos_token_id (`int`, *optional*, defaults to 49407):
|
| 68 |
+
The id of the end-of-sequence token in the vocabulary.
|
| 69 |
+
|
| 70 |
+
Example:
|
| 71 |
+
|
| 72 |
+
```python
|
| 73 |
+
>>> from transformers import SiglipTextConfig, SiglipTextModel
|
| 74 |
+
|
| 75 |
+
>>> # Initializing a SiglipTextConfig with google/siglip-base-patch16-224 style configuration
|
| 76 |
+
>>> configuration = SiglipTextConfig()
|
| 77 |
+
|
| 78 |
+
>>> # Initializing a SiglipTextModel (with random weights) from the google/siglip-base-patch16-224 style configuration
|
| 79 |
+
>>> model = SiglipTextModel(configuration)
|
| 80 |
+
|
| 81 |
+
>>> # Accessing the model configuration
|
| 82 |
+
>>> configuration = model.config
|
| 83 |
+
```"""
|
| 84 |
+
|
| 85 |
+
model_type = "siglip_text_model"
|
| 86 |
+
|
| 87 |
+
def __init__(
|
| 88 |
+
self,
|
| 89 |
+
vocab_size=32000,
|
| 90 |
+
hidden_size=768,
|
| 91 |
+
intermediate_size=3072,
|
| 92 |
+
num_hidden_layers=12,
|
| 93 |
+
num_attention_heads=12,
|
| 94 |
+
max_position_embeddings=64,
|
| 95 |
+
hidden_act="gelu_pytorch_tanh",
|
| 96 |
+
layer_norm_eps=1e-6,
|
| 97 |
+
attention_dropout=0.0,
|
| 98 |
+
# This differs from `CLIPTokenizer`'s default and from openai/siglip
|
| 99 |
+
# See https://github.com/huggingface/transformers/pull/24773#issuecomment-1632287538
|
| 100 |
+
pad_token_id=1,
|
| 101 |
+
bos_token_id=49406,
|
| 102 |
+
eos_token_id=49407,
|
| 103 |
+
**kwargs,
|
| 104 |
+
):
|
| 105 |
+
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
| 106 |
+
|
| 107 |
+
self.vocab_size = vocab_size
|
| 108 |
+
self.hidden_size = hidden_size
|
| 109 |
+
self.intermediate_size = intermediate_size
|
| 110 |
+
self.num_hidden_layers = num_hidden_layers
|
| 111 |
+
self.num_attention_heads = num_attention_heads
|
| 112 |
+
self.max_position_embeddings = max_position_embeddings
|
| 113 |
+
self.layer_norm_eps = layer_norm_eps
|
| 114 |
+
self.hidden_act = hidden_act
|
| 115 |
+
self.attention_dropout = attention_dropout
|
| 116 |
+
|
| 117 |
+
@classmethod
|
| 118 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
|
| 119 |
+
cls._set_token_in_kwargs(kwargs)
|
| 120 |
+
|
| 121 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 122 |
+
|
| 123 |
+
# get the text config dict if we are loading from SiglipConfig
|
| 124 |
+
if config_dict.get("model_type") == "siglip":
|
| 125 |
+
config_dict = config_dict["text_config"]
|
| 126 |
+
|
| 127 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
| 128 |
+
logger.warning(
|
| 129 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
| 130 |
+
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
return cls.from_dict(config_dict, **kwargs)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class SiglipVisionConfig(PretrainedConfig):
|
| 137 |
+
r"""
|
| 138 |
+
This is the configuration class to store the configuration of a [`SiglipVisionModel`]. It is used to instantiate a
|
| 139 |
+
Siglip vision encoder according to the specified arguments, defining the model architecture. Instantiating a
|
| 140 |
+
configuration with the defaults will yield a similar configuration to that of the vision encoder of the Siglip
|
| 141 |
+
[google/siglip-base-patch16-224](https://huggingface.co/google/siglip-base-patch16-224) architecture.
|
| 142 |
+
|
| 143 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 144 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 145 |
+
|
| 146 |
+
Args:
|
| 147 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 148 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 149 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 150 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 151 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 152 |
+
Number of hidden layers in the Transformer encoder.
|
| 153 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 154 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 155 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 156 |
+
Number of channels in the input images.
|
| 157 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 158 |
+
The size (resolution) of each image.
|
| 159 |
+
patch_size (`int`, *optional*, defaults to 16):
|
| 160 |
+
The size (resolution) of each patch.
|
| 161 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
|
| 162 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 163 |
+
`"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported.
|
| 164 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 165 |
+
The epsilon used by the layer normalization layers.
|
| 166 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 167 |
+
The dropout ratio for the attention probabilities.
|
| 168 |
+
|
| 169 |
+
Example:
|
| 170 |
+
|
| 171 |
+
```python
|
| 172 |
+
>>> from transformers import SiglipVisionConfig, SiglipVisionModel
|
| 173 |
+
|
| 174 |
+
>>> # Initializing a SiglipVisionConfig with google/siglip-base-patch16-224 style configuration
|
| 175 |
+
>>> configuration = SiglipVisionConfig()
|
| 176 |
+
|
| 177 |
+
>>> # Initializing a SiglipVisionModel (with random weights) from the google/siglip-base-patch16-224 style configuration
|
| 178 |
+
>>> model = SiglipVisionModel(configuration)
|
| 179 |
+
|
| 180 |
+
>>> # Accessing the model configuration
|
| 181 |
+
>>> configuration = model.config
|
| 182 |
+
```"""
|
| 183 |
+
|
| 184 |
+
model_type = "siglip_vision_model"
|
| 185 |
+
|
| 186 |
+
def __init__(
|
| 187 |
+
self,
|
| 188 |
+
hidden_size=768,
|
| 189 |
+
intermediate_size=3072,
|
| 190 |
+
num_hidden_layers=12,
|
| 191 |
+
num_attention_heads=12,
|
| 192 |
+
num_channels=3,
|
| 193 |
+
image_size=224,
|
| 194 |
+
patch_size=16,
|
| 195 |
+
hidden_act="gelu_pytorch_tanh",
|
| 196 |
+
layer_norm_eps=1e-6,
|
| 197 |
+
attention_dropout=0.0,
|
| 198 |
+
**kwargs,
|
| 199 |
+
):
|
| 200 |
+
super().__init__(**kwargs)
|
| 201 |
+
|
| 202 |
+
self.hidden_size = hidden_size
|
| 203 |
+
self.intermediate_size = intermediate_size
|
| 204 |
+
self.num_hidden_layers = num_hidden_layers
|
| 205 |
+
self.num_attention_heads = num_attention_heads
|
| 206 |
+
self.num_channels = num_channels
|
| 207 |
+
self.patch_size = patch_size
|
| 208 |
+
self.image_size = image_size
|
| 209 |
+
self.attention_dropout = attention_dropout
|
| 210 |
+
self.layer_norm_eps = layer_norm_eps
|
| 211 |
+
self.hidden_act = hidden_act
|
| 212 |
+
|
| 213 |
+
@classmethod
|
| 214 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
|
| 215 |
+
cls._set_token_in_kwargs(kwargs)
|
| 216 |
+
|
| 217 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 218 |
+
|
| 219 |
+
# get the vision config dict if we are loading from SiglipConfig
|
| 220 |
+
if config_dict.get("model_type") == "siglip":
|
| 221 |
+
config_dict = config_dict["vision_config"]
|
| 222 |
+
|
| 223 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
| 224 |
+
logger.warning(
|
| 225 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
| 226 |
+
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
return cls.from_dict(config_dict, **kwargs)
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
class SiglipConfig(PretrainedConfig):
|
| 233 |
+
r"""
|
| 234 |
+
[`SiglipConfig`] is the configuration class to store the configuration of a [`SiglipModel`]. It is used to
|
| 235 |
+
instantiate a Siglip model according to the specified arguments, defining the text model and vision model configs.
|
| 236 |
+
Instantiating a configuration with the defaults will yield a similar configuration to that of the Siglip
|
| 237 |
+
[google/siglip-base-patch16-224](https://huggingface.co/google/siglip-base-patch16-224) architecture.
|
| 238 |
+
|
| 239 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 240 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 241 |
+
|
| 242 |
+
Args:
|
| 243 |
+
text_config (`dict`, *optional*):
|
| 244 |
+
Dictionary of configuration options used to initialize [`SiglipTextConfig`].
|
| 245 |
+
vision_config (`dict`, *optional*):
|
| 246 |
+
Dictionary of configuration options used to initialize [`SiglipVisionConfig`].
|
| 247 |
+
kwargs (*optional*):
|
| 248 |
+
Dictionary of keyword arguments.
|
| 249 |
+
|
| 250 |
+
Example:
|
| 251 |
+
|
| 252 |
+
```python
|
| 253 |
+
>>> from transformers import SiglipConfig, SiglipModel
|
| 254 |
+
|
| 255 |
+
>>> # Initializing a SiglipConfig with google/siglip-base-patch16-224 style configuration
|
| 256 |
+
>>> configuration = SiglipConfig()
|
| 257 |
+
|
| 258 |
+
>>> # Initializing a SiglipModel (with random weights) from the google/siglip-base-patch16-224 style configuration
|
| 259 |
+
>>> model = SiglipModel(configuration)
|
| 260 |
+
|
| 261 |
+
>>> # Accessing the model configuration
|
| 262 |
+
>>> configuration = model.config
|
| 263 |
+
|
| 264 |
+
>>> # We can also initialize a SiglipConfig from a SiglipTextConfig and a SiglipVisionConfig
|
| 265 |
+
>>> from transformers import SiglipTextConfig, SiglipVisionConfig
|
| 266 |
+
|
| 267 |
+
>>> # Initializing a SiglipText and SiglipVision configuration
|
| 268 |
+
>>> config_text = SiglipTextConfig()
|
| 269 |
+
>>> config_vision = SiglipVisionConfig()
|
| 270 |
+
|
| 271 |
+
>>> config = SiglipConfig.from_text_vision_configs(config_text, config_vision)
|
| 272 |
+
```"""
|
| 273 |
+
|
| 274 |
+
model_type = "siglip"
|
| 275 |
+
|
| 276 |
+
def __init__(self, text_config=None, vision_config=None, **kwargs):
|
| 277 |
+
super().__init__(**kwargs)
|
| 278 |
+
|
| 279 |
+
if text_config is None:
|
| 280 |
+
text_config = {}
|
| 281 |
+
logger.info("`text_config` is `None`. Initializing the `SiglipTextConfig` with default values.")
|
| 282 |
+
|
| 283 |
+
if vision_config is None:
|
| 284 |
+
vision_config = {}
|
| 285 |
+
logger.info("`vision_config` is `None`. initializing the `SiglipVisionConfig` with default values.")
|
| 286 |
+
|
| 287 |
+
self.text_config = SiglipTextConfig(**text_config)
|
| 288 |
+
self.vision_config = SiglipVisionConfig(**vision_config)
|
| 289 |
+
|
| 290 |
+
self.initializer_factor = 1.0
|
| 291 |
+
|
| 292 |
+
@classmethod
|
| 293 |
+
def from_text_vision_configs(cls, text_config: SiglipTextConfig, vision_config: SiglipVisionConfig, **kwargs):
|
| 294 |
+
r"""
|
| 295 |
+
Instantiate a [`SiglipConfig`] (or a derived class) from siglip text model configuration and siglip vision
|
| 296 |
+
model configuration.
|
| 297 |
+
|
| 298 |
+
Returns:
|
| 299 |
+
[`SiglipConfig`]: An instance of a configuration object
|
| 300 |
+
"""
|
| 301 |
+
|
| 302 |
+
return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)
|
evalkit_internvl/lib/python3.10/site-packages/transformers/models/siglip/image_processing_siglip.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Image processor class for SigLIP."""
|
| 16 |
+
|
| 17 |
+
from typing import Dict, List, Optional, Union
|
| 18 |
+
|
| 19 |
+
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
|
| 20 |
+
from ...image_transforms import (
|
| 21 |
+
resize,
|
| 22 |
+
to_channel_dimension_format,
|
| 23 |
+
)
|
| 24 |
+
from ...image_utils import (
|
| 25 |
+
IMAGENET_STANDARD_MEAN,
|
| 26 |
+
IMAGENET_STANDARD_STD,
|
| 27 |
+
ChannelDimension,
|
| 28 |
+
ImageInput,
|
| 29 |
+
PILImageResampling,
|
| 30 |
+
infer_channel_dimension_format,
|
| 31 |
+
is_scaled_image,
|
| 32 |
+
make_list_of_images,
|
| 33 |
+
to_numpy_array,
|
| 34 |
+
valid_images,
|
| 35 |
+
)
|
| 36 |
+
from ...utils import TensorType, is_vision_available, logging
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
logger = logging.get_logger(__name__)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
if is_vision_available():
|
| 43 |
+
import PIL
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class SiglipImageProcessor(BaseImageProcessor):
|
| 47 |
+
r"""
|
| 48 |
+
Constructs a SigLIP image processor.
|
| 49 |
+
|
| 50 |
+
Args:
|
| 51 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 52 |
+
Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by
|
| 53 |
+
`do_resize` in the `preprocess` method.
|
| 54 |
+
size (`Dict[str, int]` *optional*, defaults to `{"height": 224, "width": 224}`):
|
| 55 |
+
Size of the image after resizing. Can be overridden by `size` in the `preprocess` method.
|
| 56 |
+
resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
|
| 57 |
+
Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method.
|
| 58 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
| 59 |
+
Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
|
| 60 |
+
the `preprocess` method.
|
| 61 |
+
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
|
| 62 |
+
Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess`
|
| 63 |
+
method.
|
| 64 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
| 65 |
+
Whether to normalize the image by the specified mean and standard deviation. Can be overridden by
|
| 66 |
+
`do_normalize` in the `preprocess` method.
|
| 67 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `[0.5, 0.5, 0.5]`):
|
| 68 |
+
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
|
| 69 |
+
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
|
| 70 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `[0.5, 0.5, 0.5]`):
|
| 71 |
+
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
|
| 72 |
+
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 73 |
+
Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
model_input_names = ["pixel_values"]
|
| 77 |
+
|
| 78 |
+
def __init__(
|
| 79 |
+
self,
|
| 80 |
+
do_resize: bool = True,
|
| 81 |
+
size: Dict[str, int] = None,
|
| 82 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
| 83 |
+
do_rescale: bool = True,
|
| 84 |
+
rescale_factor: Union[int, float] = 1 / 255,
|
| 85 |
+
do_normalize: bool = True,
|
| 86 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 87 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 88 |
+
**kwargs,
|
| 89 |
+
) -> None:
|
| 90 |
+
super().__init__(**kwargs)
|
| 91 |
+
size = size if size is not None else {"height": 224, "width": 224}
|
| 92 |
+
image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
|
| 93 |
+
image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
|
| 94 |
+
|
| 95 |
+
self.do_resize = do_resize
|
| 96 |
+
self.size = size
|
| 97 |
+
self.resample = resample
|
| 98 |
+
self.do_rescale = do_rescale
|
| 99 |
+
self.rescale_factor = rescale_factor
|
| 100 |
+
self.do_normalize = do_normalize
|
| 101 |
+
self.image_mean = image_mean
|
| 102 |
+
self.image_std = image_std
|
| 103 |
+
|
| 104 |
+
def preprocess(
|
| 105 |
+
self,
|
| 106 |
+
images: ImageInput,
|
| 107 |
+
do_resize: bool = None,
|
| 108 |
+
size: Dict[str, int] = None,
|
| 109 |
+
resample: PILImageResampling = None,
|
| 110 |
+
do_rescale: bool = None,
|
| 111 |
+
rescale_factor: float = None,
|
| 112 |
+
do_normalize: bool = None,
|
| 113 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 114 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 115 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 116 |
+
data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
|
| 117 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 118 |
+
**kwargs,
|
| 119 |
+
) -> PIL.Image.Image:
|
| 120 |
+
"""
|
| 121 |
+
Preprocess an image or batch of images.
|
| 122 |
+
|
| 123 |
+
Args:
|
| 124 |
+
images (`ImageInput`):
|
| 125 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
| 126 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
| 127 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
| 128 |
+
Whether to resize the image.
|
| 129 |
+
size (`Dict[str, int]`, *optional*, defaults to `self.size`):
|
| 130 |
+
Size of the image after resizing.
|
| 131 |
+
resample (`int`, *optional*, defaults to `self.resample`):
|
| 132 |
+
Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
|
| 133 |
+
has an effect if `do_resize` is set to `True`.
|
| 134 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
| 135 |
+
Whether to rescale the image.
|
| 136 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
| 137 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
| 138 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
| 139 |
+
Whether to normalize the image.
|
| 140 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
|
| 141 |
+
Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
|
| 142 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
|
| 143 |
+
Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
|
| 144 |
+
`True`.
|
| 145 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
| 146 |
+
The type of tensors to return. Can be one of:
|
| 147 |
+
- Unset: Return a list of `np.ndarray`.
|
| 148 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
| 149 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
| 150 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
| 151 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
| 152 |
+
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
|
| 153 |
+
The channel dimension format for the output image. Can be one of:
|
| 154 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 155 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 156 |
+
- Unset: Use the channel dimension format of the input image.
|
| 157 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 158 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 159 |
+
from the input image. Can be one of:
|
| 160 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 161 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 162 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 163 |
+
"""
|
| 164 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
| 165 |
+
size = size if size is not None else self.size
|
| 166 |
+
size = get_size_dict(size, param_name="size", default_to_square=False)
|
| 167 |
+
resample = resample if resample is not None else self.resample
|
| 168 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
| 169 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
| 170 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 171 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
| 172 |
+
image_std = image_std if image_std is not None else self.image_std
|
| 173 |
+
|
| 174 |
+
images = make_list_of_images(images)
|
| 175 |
+
|
| 176 |
+
if not valid_images(images):
|
| 177 |
+
raise ValueError(
|
| 178 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
| 179 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
if do_resize and size is None:
|
| 183 |
+
raise ValueError("Size must be specified if do_resize is True.")
|
| 184 |
+
|
| 185 |
+
if do_rescale and rescale_factor is None:
|
| 186 |
+
raise ValueError("Rescale factor must be specified if do_rescale is True.")
|
| 187 |
+
|
| 188 |
+
# All transformations expect numpy arrays.
|
| 189 |
+
images = [to_numpy_array(image) for image in images]
|
| 190 |
+
|
| 191 |
+
if is_scaled_image(images[0]) and do_rescale:
|
| 192 |
+
logger.warning_once(
|
| 193 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
| 194 |
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
if input_data_format is None:
|
| 198 |
+
# We assume that all images have the same channel dimension format.
|
| 199 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
| 200 |
+
|
| 201 |
+
if do_resize:
|
| 202 |
+
height, width = size["height"], size["width"]
|
| 203 |
+
images = [
|
| 204 |
+
resize(image=image, size=(height, width), resample=resample, input_data_format=input_data_format)
|
| 205 |
+
for image in images
|
| 206 |
+
]
|
| 207 |
+
|
| 208 |
+
if do_rescale:
|
| 209 |
+
images = [
|
| 210 |
+
self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
|
| 211 |
+
for image in images
|
| 212 |
+
]
|
| 213 |
+
|
| 214 |
+
if do_normalize:
|
| 215 |
+
images = [
|
| 216 |
+
self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
|
| 217 |
+
for image in images
|
| 218 |
+
]
|
| 219 |
+
|
| 220 |
+
images = [
|
| 221 |
+
to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
|
| 222 |
+
]
|
| 223 |
+
|
| 224 |
+
data = {"pixel_values": images}
|
| 225 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FastAPI framework, high performance, easy to learn, fast to code, ready for production"""
|
| 2 |
+
|
| 3 |
+
__version__ = "0.103.2"
|
| 4 |
+
|
| 5 |
+
from starlette import status as status
|
| 6 |
+
|
| 7 |
+
from .applications import FastAPI as FastAPI
|
| 8 |
+
from .background import BackgroundTasks as BackgroundTasks
|
| 9 |
+
from .datastructures import UploadFile as UploadFile
|
| 10 |
+
from .exceptions import HTTPException as HTTPException
|
| 11 |
+
from .exceptions import WebSocketException as WebSocketException
|
| 12 |
+
from .param_functions import Body as Body
|
| 13 |
+
from .param_functions import Cookie as Cookie
|
| 14 |
+
from .param_functions import Depends as Depends
|
| 15 |
+
from .param_functions import File as File
|
| 16 |
+
from .param_functions import Form as Form
|
| 17 |
+
from .param_functions import Header as Header
|
| 18 |
+
from .param_functions import Path as Path
|
| 19 |
+
from .param_functions import Query as Query
|
| 20 |
+
from .param_functions import Security as Security
|
| 21 |
+
from .requests import Request as Request
|
| 22 |
+
from .responses import Response as Response
|
| 23 |
+
from .routing import APIRouter as APIRouter
|
| 24 |
+
from .websockets import WebSocket as WebSocket
|
| 25 |
+
from .websockets import WebSocketDisconnect as WebSocketDisconnect
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.06 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/_compat.cpython-310.pyc
ADDED
|
Binary file (17.5 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/applications.cpython-310.pyc
ADDED
|
Binary file (18.9 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/background.cpython-310.pyc
ADDED
|
Binary file (228 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/concurrency.cpython-310.pyc
ADDED
|
Binary file (1.05 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/datastructures.cpython-310.pyc
ADDED
|
Binary file (3.54 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/exceptions.cpython-310.pyc
ADDED
|
Binary file (2.9 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/logger.cpython-310.pyc
ADDED
|
Binary file (223 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/params.cpython-310.pyc
ADDED
|
Binary file (15.6 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/responses.cpython-310.pyc
ADDED
|
Binary file (1.42 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/staticfiles.cpython-310.pyc
ADDED
|
Binary file (226 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/templating.cpython-310.pyc
ADDED
|
Binary file (228 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/types.cpython-310.pyc
ADDED
|
Binary file (608 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (5.86 kB). View file
|
|
|
evalkit_tf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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from enum import Enum
|
| 2 |
+
from typing import (
|
| 3 |
+
Any,
|
| 4 |
+
Awaitable,
|
| 5 |
+
Callable,
|
| 6 |
+
Coroutine,
|
| 7 |
+
Dict,
|
| 8 |
+
List,
|
| 9 |
+
Optional,
|
| 10 |
+
Sequence,
|
| 11 |
+
Type,
|
| 12 |
+
TypeVar,
|
| 13 |
+
Union,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
from fastapi import routing
|
| 17 |
+
from fastapi.datastructures import Default, DefaultPlaceholder
|
| 18 |
+
from fastapi.exception_handlers import (
|
| 19 |
+
http_exception_handler,
|
| 20 |
+
request_validation_exception_handler,
|
| 21 |
+
websocket_request_validation_exception_handler,
|
| 22 |
+
)
|
| 23 |
+
from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError
|
| 24 |
+
from fastapi.logger import logger
|
| 25 |
+
from fastapi.middleware.asyncexitstack import AsyncExitStackMiddleware
|
| 26 |
+
from fastapi.openapi.docs import (
|
| 27 |
+
get_redoc_html,
|
| 28 |
+
get_swagger_ui_html,
|
| 29 |
+
get_swagger_ui_oauth2_redirect_html,
|
| 30 |
+
)
|
| 31 |
+
from fastapi.openapi.utils import get_openapi
|
| 32 |
+
from fastapi.params import Depends
|
| 33 |
+
from fastapi.types import DecoratedCallable, IncEx
|
| 34 |
+
from fastapi.utils import generate_unique_id
|
| 35 |
+
from starlette.applications import Starlette
|
| 36 |
+
from starlette.datastructures import State
|
| 37 |
+
from starlette.exceptions import HTTPException
|
| 38 |
+
from starlette.middleware import Middleware
|
| 39 |
+
from starlette.middleware.base import BaseHTTPMiddleware
|
| 40 |
+
from starlette.middleware.errors import ServerErrorMiddleware
|
| 41 |
+
from starlette.middleware.exceptions import ExceptionMiddleware
|
| 42 |
+
from starlette.requests import Request
|
| 43 |
+
from starlette.responses import HTMLResponse, JSONResponse, Response
|
| 44 |
+
from starlette.routing import BaseRoute
|
| 45 |
+
from starlette.types import ASGIApp, Lifespan, Receive, Scope, Send
|
| 46 |
+
|
| 47 |
+
AppType = TypeVar("AppType", bound="FastAPI")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class FastAPI(Starlette):
|
| 51 |
+
def __init__(
|
| 52 |
+
self: AppType,
|
| 53 |
+
*,
|
| 54 |
+
debug: bool = False,
|
| 55 |
+
routes: Optional[List[BaseRoute]] = None,
|
| 56 |
+
title: str = "FastAPI",
|
| 57 |
+
summary: Optional[str] = None,
|
| 58 |
+
description: str = "",
|
| 59 |
+
version: str = "0.1.0",
|
| 60 |
+
openapi_url: Optional[str] = "/openapi.json",
|
| 61 |
+
openapi_tags: Optional[List[Dict[str, Any]]] = None,
|
| 62 |
+
servers: Optional[List[Dict[str, Union[str, Any]]]] = None,
|
| 63 |
+
dependencies: Optional[Sequence[Depends]] = None,
|
| 64 |
+
default_response_class: Type[Response] = Default(JSONResponse),
|
| 65 |
+
redirect_slashes: bool = True,
|
| 66 |
+
docs_url: Optional[str] = "/docs",
|
| 67 |
+
redoc_url: Optional[str] = "/redoc",
|
| 68 |
+
swagger_ui_oauth2_redirect_url: Optional[str] = "/docs/oauth2-redirect",
|
| 69 |
+
swagger_ui_init_oauth: Optional[Dict[str, Any]] = None,
|
| 70 |
+
middleware: Optional[Sequence[Middleware]] = None,
|
| 71 |
+
exception_handlers: Optional[
|
| 72 |
+
Dict[
|
| 73 |
+
Union[int, Type[Exception]],
|
| 74 |
+
Callable[[Request, Any], Coroutine[Any, Any, Response]],
|
| 75 |
+
]
|
| 76 |
+
] = None,
|
| 77 |
+
on_startup: Optional[Sequence[Callable[[], Any]]] = None,
|
| 78 |
+
on_shutdown: Optional[Sequence[Callable[[], Any]]] = None,
|
| 79 |
+
lifespan: Optional[Lifespan[AppType]] = None,
|
| 80 |
+
terms_of_service: Optional[str] = None,
|
| 81 |
+
contact: Optional[Dict[str, Union[str, Any]]] = None,
|
| 82 |
+
license_info: Optional[Dict[str, Union[str, Any]]] = None,
|
| 83 |
+
openapi_prefix: str = "",
|
| 84 |
+
root_path: str = "",
|
| 85 |
+
root_path_in_servers: bool = True,
|
| 86 |
+
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
| 87 |
+
callbacks: Optional[List[BaseRoute]] = None,
|
| 88 |
+
webhooks: Optional[routing.APIRouter] = None,
|
| 89 |
+
deprecated: Optional[bool] = None,
|
| 90 |
+
include_in_schema: bool = True,
|
| 91 |
+
swagger_ui_parameters: Optional[Dict[str, Any]] = None,
|
| 92 |
+
generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(
|
| 93 |
+
generate_unique_id
|
| 94 |
+
),
|
| 95 |
+
separate_input_output_schemas: bool = True,
|
| 96 |
+
**extra: Any,
|
| 97 |
+
) -> None:
|
| 98 |
+
self.debug = debug
|
| 99 |
+
self.title = title
|
| 100 |
+
self.summary = summary
|
| 101 |
+
self.description = description
|
| 102 |
+
self.version = version
|
| 103 |
+
self.terms_of_service = terms_of_service
|
| 104 |
+
self.contact = contact
|
| 105 |
+
self.license_info = license_info
|
| 106 |
+
self.openapi_url = openapi_url
|
| 107 |
+
self.openapi_tags = openapi_tags
|
| 108 |
+
self.root_path_in_servers = root_path_in_servers
|
| 109 |
+
self.docs_url = docs_url
|
| 110 |
+
self.redoc_url = redoc_url
|
| 111 |
+
self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url
|
| 112 |
+
self.swagger_ui_init_oauth = swagger_ui_init_oauth
|
| 113 |
+
self.swagger_ui_parameters = swagger_ui_parameters
|
| 114 |
+
self.servers = servers or []
|
| 115 |
+
self.separate_input_output_schemas = separate_input_output_schemas
|
| 116 |
+
self.extra = extra
|
| 117 |
+
self.openapi_version = "3.1.0"
|
| 118 |
+
self.openapi_schema: Optional[Dict[str, Any]] = None
|
| 119 |
+
if self.openapi_url:
|
| 120 |
+
assert self.title, "A title must be provided for OpenAPI, e.g.: 'My API'"
|
| 121 |
+
assert self.version, "A version must be provided for OpenAPI, e.g.: '2.1.0'"
|
| 122 |
+
# TODO: remove when discarding the openapi_prefix parameter
|
| 123 |
+
if openapi_prefix:
|
| 124 |
+
logger.warning(
|
| 125 |
+
'"openapi_prefix" has been deprecated in favor of "root_path", which '
|
| 126 |
+
"follows more closely the ASGI standard, is simpler, and more "
|
| 127 |
+
"automatic. Check the docs at "
|
| 128 |
+
"https://fastapi.tiangolo.com/advanced/sub-applications/"
|
| 129 |
+
)
|
| 130 |
+
self.webhooks = webhooks or routing.APIRouter()
|
| 131 |
+
self.root_path = root_path or openapi_prefix
|
| 132 |
+
self.state: State = State()
|
| 133 |
+
self.dependency_overrides: Dict[Callable[..., Any], Callable[..., Any]] = {}
|
| 134 |
+
self.router: routing.APIRouter = routing.APIRouter(
|
| 135 |
+
routes=routes,
|
| 136 |
+
redirect_slashes=redirect_slashes,
|
| 137 |
+
dependency_overrides_provider=self,
|
| 138 |
+
on_startup=on_startup,
|
| 139 |
+
on_shutdown=on_shutdown,
|
| 140 |
+
lifespan=lifespan,
|
| 141 |
+
default_response_class=default_response_class,
|
| 142 |
+
dependencies=dependencies,
|
| 143 |
+
callbacks=callbacks,
|
| 144 |
+
deprecated=deprecated,
|
| 145 |
+
include_in_schema=include_in_schema,
|
| 146 |
+
responses=responses,
|
| 147 |
+
generate_unique_id_function=generate_unique_id_function,
|
| 148 |
+
)
|
| 149 |
+
self.exception_handlers: Dict[
|
| 150 |
+
Any, Callable[[Request, Any], Union[Response, Awaitable[Response]]]
|
| 151 |
+
] = ({} if exception_handlers is None else dict(exception_handlers))
|
| 152 |
+
self.exception_handlers.setdefault(HTTPException, http_exception_handler)
|
| 153 |
+
self.exception_handlers.setdefault(
|
| 154 |
+
RequestValidationError, request_validation_exception_handler
|
| 155 |
+
)
|
| 156 |
+
self.exception_handlers.setdefault(
|
| 157 |
+
WebSocketRequestValidationError,
|
| 158 |
+
# Starlette still has incorrect type specification for the handlers
|
| 159 |
+
websocket_request_validation_exception_handler, # type: ignore
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
self.user_middleware: List[Middleware] = (
|
| 163 |
+
[] if middleware is None else list(middleware)
|
| 164 |
+
)
|
| 165 |
+
self.middleware_stack: Union[ASGIApp, None] = None
|
| 166 |
+
self.setup()
|
| 167 |
+
|
| 168 |
+
def build_middleware_stack(self) -> ASGIApp:
|
| 169 |
+
# Duplicate/override from Starlette to add AsyncExitStackMiddleware
|
| 170 |
+
# inside of ExceptionMiddleware, inside of custom user middlewares
|
| 171 |
+
debug = self.debug
|
| 172 |
+
error_handler = None
|
| 173 |
+
exception_handlers = {}
|
| 174 |
+
|
| 175 |
+
for key, value in self.exception_handlers.items():
|
| 176 |
+
if key in (500, Exception):
|
| 177 |
+
error_handler = value
|
| 178 |
+
else:
|
| 179 |
+
exception_handlers[key] = value
|
| 180 |
+
|
| 181 |
+
middleware = (
|
| 182 |
+
[Middleware(ServerErrorMiddleware, handler=error_handler, debug=debug)]
|
| 183 |
+
+ self.user_middleware
|
| 184 |
+
+ [
|
| 185 |
+
Middleware(
|
| 186 |
+
ExceptionMiddleware, handlers=exception_handlers, debug=debug
|
| 187 |
+
),
|
| 188 |
+
# Add FastAPI-specific AsyncExitStackMiddleware for dependencies with
|
| 189 |
+
# contextvars.
|
| 190 |
+
# This needs to happen after user middlewares because those create a
|
| 191 |
+
# new contextvars context copy by using a new AnyIO task group.
|
| 192 |
+
# The initial part of dependencies with 'yield' is executed in the
|
| 193 |
+
# FastAPI code, inside all the middlewares. However, the teardown part
|
| 194 |
+
# (after 'yield') is executed in the AsyncExitStack in this middleware.
|
| 195 |
+
# If the AsyncExitStack lived outside of the custom middlewares and
|
| 196 |
+
# contextvars were set in a dependency with 'yield' in that internal
|
| 197 |
+
# contextvars context, the values would not be available in the
|
| 198 |
+
# outer context of the AsyncExitStack.
|
| 199 |
+
# By placing the middleware and the AsyncExitStack here, inside all
|
| 200 |
+
# user middlewares, the code before and after 'yield' in dependencies
|
| 201 |
+
# with 'yield' is executed in the same contextvars context. Thus, all values
|
| 202 |
+
# set in contextvars before 'yield' are still available after 'yield,' as
|
| 203 |
+
# expected.
|
| 204 |
+
# Additionally, by having this AsyncExitStack here, after the
|
| 205 |
+
# ExceptionMiddleware, dependencies can now catch handled exceptions,
|
| 206 |
+
# e.g. HTTPException, to customize the teardown code (e.g. DB session
|
| 207 |
+
# rollback).
|
| 208 |
+
Middleware(AsyncExitStackMiddleware),
|
| 209 |
+
]
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
app = self.router
|
| 213 |
+
for cls, options in reversed(middleware):
|
| 214 |
+
app = cls(app=app, **options)
|
| 215 |
+
return app
|
| 216 |
+
|
| 217 |
+
def openapi(self) -> Dict[str, Any]:
|
| 218 |
+
if not self.openapi_schema:
|
| 219 |
+
self.openapi_schema = get_openapi(
|
| 220 |
+
title=self.title,
|
| 221 |
+
version=self.version,
|
| 222 |
+
openapi_version=self.openapi_version,
|
| 223 |
+
summary=self.summary,
|
| 224 |
+
description=self.description,
|
| 225 |
+
terms_of_service=self.terms_of_service,
|
| 226 |
+
contact=self.contact,
|
| 227 |
+
license_info=self.license_info,
|
| 228 |
+
routes=self.routes,
|
| 229 |
+
webhooks=self.webhooks.routes,
|
| 230 |
+
tags=self.openapi_tags,
|
| 231 |
+
servers=self.servers,
|
| 232 |
+
separate_input_output_schemas=self.separate_input_output_schemas,
|
| 233 |
+
)
|
| 234 |
+
return self.openapi_schema
|
| 235 |
+
|
| 236 |
+
def setup(self) -> None:
|
| 237 |
+
if self.openapi_url:
|
| 238 |
+
urls = (server_data.get("url") for server_data in self.servers)
|
| 239 |
+
server_urls = {url for url in urls if url}
|
| 240 |
+
|
| 241 |
+
async def openapi(req: Request) -> JSONResponse:
|
| 242 |
+
root_path = req.scope.get("root_path", "").rstrip("/")
|
| 243 |
+
if root_path not in server_urls:
|
| 244 |
+
if root_path and self.root_path_in_servers:
|
| 245 |
+
self.servers.insert(0, {"url": root_path})
|
| 246 |
+
server_urls.add(root_path)
|
| 247 |
+
return JSONResponse(self.openapi())
|
| 248 |
+
|
| 249 |
+
self.add_route(self.openapi_url, openapi, include_in_schema=False)
|
| 250 |
+
if self.openapi_url and self.docs_url:
|
| 251 |
+
|
| 252 |
+
async def swagger_ui_html(req: Request) -> HTMLResponse:
|
| 253 |
+
root_path = req.scope.get("root_path", "").rstrip("/")
|
| 254 |
+
openapi_url = root_path + self.openapi_url
|
| 255 |
+
oauth2_redirect_url = self.swagger_ui_oauth2_redirect_url
|
| 256 |
+
if oauth2_redirect_url:
|
| 257 |
+
oauth2_redirect_url = root_path + oauth2_redirect_url
|
| 258 |
+
return get_swagger_ui_html(
|
| 259 |
+
openapi_url=openapi_url,
|
| 260 |
+
title=self.title + " - Swagger UI",
|
| 261 |
+
oauth2_redirect_url=oauth2_redirect_url,
|
| 262 |
+
init_oauth=self.swagger_ui_init_oauth,
|
| 263 |
+
swagger_ui_parameters=self.swagger_ui_parameters,
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
self.add_route(self.docs_url, swagger_ui_html, include_in_schema=False)
|
| 267 |
+
|
| 268 |
+
if self.swagger_ui_oauth2_redirect_url:
|
| 269 |
+
|
| 270 |
+
async def swagger_ui_redirect(req: Request) -> HTMLResponse:
|
| 271 |
+
return get_swagger_ui_oauth2_redirect_html()
|
| 272 |
+
|
| 273 |
+
self.add_route(
|
| 274 |
+
self.swagger_ui_oauth2_redirect_url,
|
| 275 |
+
swagger_ui_redirect,
|
| 276 |
+
include_in_schema=False,
|
| 277 |
+
)
|
| 278 |
+
if self.openapi_url and self.redoc_url:
|
| 279 |
+
|
| 280 |
+
async def redoc_html(req: Request) -> HTMLResponse:
|
| 281 |
+
root_path = req.scope.get("root_path", "").rstrip("/")
|
| 282 |
+
openapi_url = root_path + self.openapi_url
|
| 283 |
+
return get_redoc_html(
|
| 284 |
+
openapi_url=openapi_url, title=self.title + " - ReDoc"
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
self.add_route(self.redoc_url, redoc_html, include_in_schema=False)
|
| 288 |
+
|
| 289 |
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
| 290 |
+
if self.root_path:
|
| 291 |
+
scope["root_path"] = self.root_path
|
| 292 |
+
await super().__call__(scope, receive, send)
|
| 293 |
+
|
| 294 |
+
def add_api_route(
|
| 295 |
+
self,
|
| 296 |
+
path: str,
|
| 297 |
+
endpoint: Callable[..., Coroutine[Any, Any, Response]],
|
| 298 |
+
*,
|
| 299 |
+
response_model: Any = Default(None),
|
| 300 |
+
status_code: Optional[int] = None,
|
| 301 |
+
tags: Optional[List[Union[str, Enum]]] = None,
|
| 302 |
+
dependencies: Optional[Sequence[Depends]] = None,
|
| 303 |
+
summary: Optional[str] = None,
|
| 304 |
+
description: Optional[str] = None,
|
| 305 |
+
response_description: str = "Successful Response",
|
| 306 |
+
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
| 307 |
+
deprecated: Optional[bool] = None,
|
| 308 |
+
methods: Optional[List[str]] = None,
|
| 309 |
+
operation_id: Optional[str] = None,
|
| 310 |
+
response_model_include: Optional[IncEx] = None,
|
| 311 |
+
response_model_exclude: Optional[IncEx] = None,
|
| 312 |
+
response_model_by_alias: bool = True,
|
| 313 |
+
response_model_exclude_unset: bool = False,
|
| 314 |
+
response_model_exclude_defaults: bool = False,
|
| 315 |
+
response_model_exclude_none: bool = False,
|
| 316 |
+
include_in_schema: bool = True,
|
| 317 |
+
response_class: Union[Type[Response], DefaultPlaceholder] = Default(
|
| 318 |
+
JSONResponse
|
| 319 |
+
),
|
| 320 |
+
name: Optional[str] = None,
|
| 321 |
+
openapi_extra: Optional[Dict[str, Any]] = None,
|
| 322 |
+
generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(
|
| 323 |
+
generate_unique_id
|
| 324 |
+
),
|
| 325 |
+
) -> None:
|
| 326 |
+
self.router.add_api_route(
|
| 327 |
+
path,
|
| 328 |
+
endpoint=endpoint,
|
| 329 |
+
response_model=response_model,
|
| 330 |
+
status_code=status_code,
|
| 331 |
+
tags=tags,
|
| 332 |
+
dependencies=dependencies,
|
| 333 |
+
summary=summary,
|
| 334 |
+
description=description,
|
| 335 |
+
response_description=response_description,
|
| 336 |
+
responses=responses,
|
| 337 |
+
deprecated=deprecated,
|
| 338 |
+
methods=methods,
|
| 339 |
+
operation_id=operation_id,
|
| 340 |
+
response_model_include=response_model_include,
|
| 341 |
+
response_model_exclude=response_model_exclude,
|
| 342 |
+
response_model_by_alias=response_model_by_alias,
|
| 343 |
+
response_model_exclude_unset=response_model_exclude_unset,
|
| 344 |
+
response_model_exclude_defaults=response_model_exclude_defaults,
|
| 345 |
+
response_model_exclude_none=response_model_exclude_none,
|
| 346 |
+
include_in_schema=include_in_schema,
|
| 347 |
+
response_class=response_class,
|
| 348 |
+
name=name,
|
| 349 |
+
openapi_extra=openapi_extra,
|
| 350 |
+
generate_unique_id_function=generate_unique_id_function,
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
def api_route(
|
| 354 |
+
self,
|
| 355 |
+
path: str,
|
| 356 |
+
*,
|
| 357 |
+
response_model: Any = Default(None),
|
| 358 |
+
status_code: Optional[int] = None,
|
| 359 |
+
tags: Optional[List[Union[str, Enum]]] = None,
|
| 360 |
+
dependencies: Optional[Sequence[Depends]] = None,
|
| 361 |
+
summary: Optional[str] = None,
|
| 362 |
+
description: Optional[str] = None,
|
| 363 |
+
response_description: str = "Successful Response",
|
| 364 |
+
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
| 365 |
+
deprecated: Optional[bool] = None,
|
| 366 |
+
methods: Optional[List[str]] = None,
|
| 367 |
+
operation_id: Optional[str] = None,
|
| 368 |
+
response_model_include: Optional[IncEx] = None,
|
| 369 |
+
response_model_exclude: Optional[IncEx] = None,
|
| 370 |
+
response_model_by_alias: bool = True,
|
| 371 |
+
response_model_exclude_unset: bool = False,
|
| 372 |
+
response_model_exclude_defaults: bool = False,
|
| 373 |
+
response_model_exclude_none: bool = False,
|
| 374 |
+
include_in_schema: bool = True,
|
| 375 |
+
response_class: Type[Response] = Default(JSONResponse),
|
| 376 |
+
name: Optional[str] = None,
|
| 377 |
+
openapi_extra: Optional[Dict[str, Any]] = None,
|
| 378 |
+
generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(
|
| 379 |
+
generate_unique_id
|
| 380 |
+
),
|
| 381 |
+
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
| 382 |
+
def decorator(func: DecoratedCallable) -> DecoratedCallable:
|
| 383 |
+
self.router.add_api_route(
|
| 384 |
+
path,
|
| 385 |
+
func,
|
| 386 |
+
response_model=response_model,
|
| 387 |
+
status_code=status_code,
|
| 388 |
+
tags=tags,
|
| 389 |
+
dependencies=dependencies,
|
| 390 |
+
summary=summary,
|
| 391 |
+
description=description,
|
| 392 |
+
response_description=response_description,
|
| 393 |
+
responses=responses,
|
| 394 |
+
deprecated=deprecated,
|
| 395 |
+
methods=methods,
|
| 396 |
+
operation_id=operation_id,
|
| 397 |
+
response_model_include=response_model_include,
|
| 398 |
+
response_model_exclude=response_model_exclude,
|
| 399 |
+
response_model_by_alias=response_model_by_alias,
|
| 400 |
+
response_model_exclude_unset=response_model_exclude_unset,
|
| 401 |
+
response_model_exclude_defaults=response_model_exclude_defaults,
|
| 402 |
+
response_model_exclude_none=response_model_exclude_none,
|
| 403 |
+
include_in_schema=include_in_schema,
|
| 404 |
+
response_class=response_class,
|
| 405 |
+
name=name,
|
| 406 |
+
openapi_extra=openapi_extra,
|
| 407 |
+
generate_unique_id_function=generate_unique_id_function,
|
| 408 |
+
)
|
| 409 |
+
return func
|
| 410 |
+
|
| 411 |
+
return decorator
|
| 412 |
+
|
| 413 |
+
def add_api_websocket_route(
|
| 414 |
+
self,
|
| 415 |
+
path: str,
|
| 416 |
+
endpoint: Callable[..., Any],
|
| 417 |
+
name: Optional[str] = None,
|
| 418 |
+
*,
|
| 419 |
+
dependencies: Optional[Sequence[Depends]] = None,
|
| 420 |
+
) -> None:
|
| 421 |
+
self.router.add_api_websocket_route(
|
| 422 |
+
path,
|
| 423 |
+
endpoint,
|
| 424 |
+
name=name,
|
| 425 |
+
dependencies=dependencies,
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
def websocket(
|
| 429 |
+
self,
|
| 430 |
+
path: str,
|
| 431 |
+
name: Optional[str] = None,
|
| 432 |
+
*,
|
| 433 |
+
dependencies: Optional[Sequence[Depends]] = None,
|
| 434 |
+
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
| 435 |
+
def decorator(func: DecoratedCallable) -> DecoratedCallable:
|
| 436 |
+
self.add_api_websocket_route(
|
| 437 |
+
path,
|
| 438 |
+
func,
|
| 439 |
+
name=name,
|
| 440 |
+
dependencies=dependencies,
|
| 441 |
+
)
|
| 442 |
+
return func
|
| 443 |
+
|
| 444 |
+
return decorator
|
| 445 |
+
|
| 446 |
+
def include_router(
|
| 447 |
+
self,
|
| 448 |
+
router: routing.APIRouter,
|
| 449 |
+
*,
|
| 450 |
+
prefix: str = "",
|
| 451 |
+
tags: Optional[List[Union[str, Enum]]] = None,
|
| 452 |
+
dependencies: Optional[Sequence[Depends]] = None,
|
| 453 |
+
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
| 454 |
+
deprecated: Optional[bool] = None,
|
| 455 |
+
include_in_schema: bool = True,
|
| 456 |
+
default_response_class: Type[Response] = Default(JSONResponse),
|
| 457 |
+
callbacks: Optional[List[BaseRoute]] = None,
|
| 458 |
+
generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(
|
| 459 |
+
generate_unique_id
|
| 460 |
+
),
|
| 461 |
+
) -> None:
|
| 462 |
+
self.router.include_router(
|
| 463 |
+
router,
|
| 464 |
+
prefix=prefix,
|
| 465 |
+
tags=tags,
|
| 466 |
+
dependencies=dependencies,
|
| 467 |
+
responses=responses,
|
| 468 |
+
deprecated=deprecated,
|
| 469 |
+
include_in_schema=include_in_schema,
|
| 470 |
+
default_response_class=default_response_class,
|
| 471 |
+
callbacks=callbacks,
|
| 472 |
+
generate_unique_id_function=generate_unique_id_function,
|
| 473 |
+
)
|
| 474 |
+
|
| 475 |
+
def get(
|
| 476 |
+
self,
|
| 477 |
+
path: str,
|
| 478 |
+
*,
|
| 479 |
+
response_model: Any = Default(None),
|
| 480 |
+
status_code: Optional[int] = None,
|
| 481 |
+
tags: Optional[List[Union[str, Enum]]] = None,
|
| 482 |
+
dependencies: Optional[Sequence[Depends]] = None,
|
| 483 |
+
summary: Optional[str] = None,
|
| 484 |
+
description: Optional[str] = None,
|
| 485 |
+
response_description: str = "Successful Response",
|
| 486 |
+
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
| 487 |
+
deprecated: Optional[bool] = None,
|
| 488 |
+
operation_id: Optional[str] = None,
|
| 489 |
+
response_model_include: Optional[IncEx] = None,
|
| 490 |
+
response_model_exclude: Optional[IncEx] = None,
|
| 491 |
+
response_model_by_alias: bool = True,
|
| 492 |
+
response_model_exclude_unset: bool = False,
|
| 493 |
+
response_model_exclude_defaults: bool = False,
|
| 494 |
+
response_model_exclude_none: bool = False,
|
| 495 |
+
include_in_schema: bool = True,
|
| 496 |
+
response_class: Type[Response] = Default(JSONResponse),
|
| 497 |
+
name: Optional[str] = None,
|
| 498 |
+
callbacks: Optional[List[BaseRoute]] = None,
|
| 499 |
+
openapi_extra: Optional[Dict[str, Any]] = None,
|
| 500 |
+
generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(
|
| 501 |
+
generate_unique_id
|
| 502 |
+
),
|
| 503 |
+
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
| 504 |
+
return self.router.get(
|
| 505 |
+
path,
|
| 506 |
+
response_model=response_model,
|
| 507 |
+
status_code=status_code,
|
| 508 |
+
tags=tags,
|
| 509 |
+
dependencies=dependencies,
|
| 510 |
+
summary=summary,
|
| 511 |
+
description=description,
|
| 512 |
+
response_description=response_description,
|
| 513 |
+
responses=responses,
|
| 514 |
+
deprecated=deprecated,
|
| 515 |
+
operation_id=operation_id,
|
| 516 |
+
response_model_include=response_model_include,
|
| 517 |
+
response_model_exclude=response_model_exclude,
|
| 518 |
+
response_model_by_alias=response_model_by_alias,
|
| 519 |
+
response_model_exclude_unset=response_model_exclude_unset,
|
| 520 |
+
response_model_exclude_defaults=response_model_exclude_defaults,
|
| 521 |
+
response_model_exclude_none=response_model_exclude_none,
|
| 522 |
+
include_in_schema=include_in_schema,
|
| 523 |
+
response_class=response_class,
|
| 524 |
+
name=name,
|
| 525 |
+
callbacks=callbacks,
|
| 526 |
+
openapi_extra=openapi_extra,
|
| 527 |
+
generate_unique_id_function=generate_unique_id_function,
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
def put(
|
| 531 |
+
self,
|
| 532 |
+
path: str,
|
| 533 |
+
*,
|
| 534 |
+
response_model: Any = Default(None),
|
| 535 |
+
status_code: Optional[int] = None,
|
| 536 |
+
tags: Optional[List[Union[str, Enum]]] = None,
|
| 537 |
+
dependencies: Optional[Sequence[Depends]] = None,
|
| 538 |
+
summary: Optional[str] = None,
|
| 539 |
+
description: Optional[str] = None,
|
| 540 |
+
response_description: str = "Successful Response",
|
| 541 |
+
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
| 542 |
+
deprecated: Optional[bool] = None,
|
| 543 |
+
operation_id: Optional[str] = None,
|
| 544 |
+
response_model_include: Optional[IncEx] = None,
|
| 545 |
+
response_model_exclude: Optional[IncEx] = None,
|
| 546 |
+
response_model_by_alias: bool = True,
|
| 547 |
+
response_model_exclude_unset: bool = False,
|
| 548 |
+
response_model_exclude_defaults: bool = False,
|
| 549 |
+
response_model_exclude_none: bool = False,
|
| 550 |
+
include_in_schema: bool = True,
|
| 551 |
+
response_class: Type[Response] = Default(JSONResponse),
|
| 552 |
+
name: Optional[str] = None,
|
| 553 |
+
callbacks: Optional[List[BaseRoute]] = None,
|
| 554 |
+
openapi_extra: Optional[Dict[str, Any]] = None,
|
| 555 |
+
generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(
|
| 556 |
+
generate_unique_id
|
| 557 |
+
),
|
| 558 |
+
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
| 559 |
+
return self.router.put(
|
| 560 |
+
path,
|
| 561 |
+
response_model=response_model,
|
| 562 |
+
status_code=status_code,
|
| 563 |
+
tags=tags,
|
| 564 |
+
dependencies=dependencies,
|
| 565 |
+
summary=summary,
|
| 566 |
+
description=description,
|
| 567 |
+
response_description=response_description,
|
| 568 |
+
responses=responses,
|
| 569 |
+
deprecated=deprecated,
|
| 570 |
+
operation_id=operation_id,
|
| 571 |
+
response_model_include=response_model_include,
|
| 572 |
+
response_model_exclude=response_model_exclude,
|
| 573 |
+
response_model_by_alias=response_model_by_alias,
|
| 574 |
+
response_model_exclude_unset=response_model_exclude_unset,
|
| 575 |
+
response_model_exclude_defaults=response_model_exclude_defaults,
|
| 576 |
+
response_model_exclude_none=response_model_exclude_none,
|
| 577 |
+
include_in_schema=include_in_schema,
|
| 578 |
+
response_class=response_class,
|
| 579 |
+
name=name,
|
| 580 |
+
callbacks=callbacks,
|
| 581 |
+
openapi_extra=openapi_extra,
|
| 582 |
+
generate_unique_id_function=generate_unique_id_function,
|
| 583 |
+
)
|
| 584 |
+
|
| 585 |
+
def post(
|
| 586 |
+
self,
|
| 587 |
+
path: str,
|
| 588 |
+
*,
|
| 589 |
+
response_model: Any = Default(None),
|
| 590 |
+
status_code: Optional[int] = None,
|
| 591 |
+
tags: Optional[List[Union[str, Enum]]] = None,
|
| 592 |
+
dependencies: Optional[Sequence[Depends]] = None,
|
| 593 |
+
summary: Optional[str] = None,
|
| 594 |
+
description: Optional[str] = None,
|
| 595 |
+
response_description: str = "Successful Response",
|
| 596 |
+
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
| 597 |
+
deprecated: Optional[bool] = None,
|
| 598 |
+
operation_id: Optional[str] = None,
|
| 599 |
+
response_model_include: Optional[IncEx] = None,
|
| 600 |
+
response_model_exclude: Optional[IncEx] = None,
|
| 601 |
+
response_model_by_alias: bool = True,
|
| 602 |
+
response_model_exclude_unset: bool = False,
|
| 603 |
+
response_model_exclude_defaults: bool = False,
|
| 604 |
+
response_model_exclude_none: bool = False,
|
| 605 |
+
include_in_schema: bool = True,
|
| 606 |
+
response_class: Type[Response] = Default(JSONResponse),
|
| 607 |
+
name: Optional[str] = None,
|
| 608 |
+
callbacks: Optional[List[BaseRoute]] = None,
|
| 609 |
+
openapi_extra: Optional[Dict[str, Any]] = None,
|
| 610 |
+
generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(
|
| 611 |
+
generate_unique_id
|
| 612 |
+
),
|
| 613 |
+
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
| 614 |
+
return self.router.post(
|
| 615 |
+
path,
|
| 616 |
+
response_model=response_model,
|
| 617 |
+
status_code=status_code,
|
| 618 |
+
tags=tags,
|
| 619 |
+
dependencies=dependencies,
|
| 620 |
+
summary=summary,
|
| 621 |
+
description=description,
|
| 622 |
+
response_description=response_description,
|
| 623 |
+
responses=responses,
|
| 624 |
+
deprecated=deprecated,
|
| 625 |
+
operation_id=operation_id,
|
| 626 |
+
response_model_include=response_model_include,
|
| 627 |
+
response_model_exclude=response_model_exclude,
|
| 628 |
+
response_model_by_alias=response_model_by_alias,
|
| 629 |
+
response_model_exclude_unset=response_model_exclude_unset,
|
| 630 |
+
response_model_exclude_defaults=response_model_exclude_defaults,
|
| 631 |
+
response_model_exclude_none=response_model_exclude_none,
|
| 632 |
+
include_in_schema=include_in_schema,
|
| 633 |
+
response_class=response_class,
|
| 634 |
+
name=name,
|
| 635 |
+
callbacks=callbacks,
|
| 636 |
+
openapi_extra=openapi_extra,
|
| 637 |
+
generate_unique_id_function=generate_unique_id_function,
|
| 638 |
+
)
|
| 639 |
+
|
| 640 |
+
def delete(
|
| 641 |
+
self,
|
| 642 |
+
path: str,
|
| 643 |
+
*,
|
| 644 |
+
response_model: Any = Default(None),
|
| 645 |
+
status_code: Optional[int] = None,
|
| 646 |
+
tags: Optional[List[Union[str, Enum]]] = None,
|
| 647 |
+
dependencies: Optional[Sequence[Depends]] = None,
|
| 648 |
+
summary: Optional[str] = None,
|
| 649 |
+
description: Optional[str] = None,
|
| 650 |
+
response_description: str = "Successful Response",
|
| 651 |
+
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
| 652 |
+
deprecated: Optional[bool] = None,
|
| 653 |
+
operation_id: Optional[str] = None,
|
| 654 |
+
response_model_include: Optional[IncEx] = None,
|
| 655 |
+
response_model_exclude: Optional[IncEx] = None,
|
| 656 |
+
response_model_by_alias: bool = True,
|
| 657 |
+
response_model_exclude_unset: bool = False,
|
| 658 |
+
response_model_exclude_defaults: bool = False,
|
| 659 |
+
response_model_exclude_none: bool = False,
|
| 660 |
+
include_in_schema: bool = True,
|
| 661 |
+
response_class: Type[Response] = Default(JSONResponse),
|
| 662 |
+
name: Optional[str] = None,
|
| 663 |
+
callbacks: Optional[List[BaseRoute]] = None,
|
| 664 |
+
openapi_extra: Optional[Dict[str, Any]] = None,
|
| 665 |
+
generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(
|
| 666 |
+
generate_unique_id
|
| 667 |
+
),
|
| 668 |
+
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
| 669 |
+
return self.router.delete(
|
| 670 |
+
path,
|
| 671 |
+
response_model=response_model,
|
| 672 |
+
status_code=status_code,
|
| 673 |
+
tags=tags,
|
| 674 |
+
dependencies=dependencies,
|
| 675 |
+
summary=summary,
|
| 676 |
+
description=description,
|
| 677 |
+
response_description=response_description,
|
| 678 |
+
responses=responses,
|
| 679 |
+
deprecated=deprecated,
|
| 680 |
+
operation_id=operation_id,
|
| 681 |
+
response_model_include=response_model_include,
|
| 682 |
+
response_model_exclude=response_model_exclude,
|
| 683 |
+
response_model_by_alias=response_model_by_alias,
|
| 684 |
+
response_model_exclude_unset=response_model_exclude_unset,
|
| 685 |
+
response_model_exclude_defaults=response_model_exclude_defaults,
|
| 686 |
+
response_model_exclude_none=response_model_exclude_none,
|
| 687 |
+
include_in_schema=include_in_schema,
|
| 688 |
+
response_class=response_class,
|
| 689 |
+
name=name,
|
| 690 |
+
callbacks=callbacks,
|
| 691 |
+
openapi_extra=openapi_extra,
|
| 692 |
+
generate_unique_id_function=generate_unique_id_function,
|
| 693 |
+
)
|
| 694 |
+
|
| 695 |
+
def options(
|
| 696 |
+
self,
|
| 697 |
+
path: str,
|
| 698 |
+
*,
|
| 699 |
+
response_model: Any = Default(None),
|
| 700 |
+
status_code: Optional[int] = None,
|
| 701 |
+
tags: Optional[List[Union[str, Enum]]] = None,
|
| 702 |
+
dependencies: Optional[Sequence[Depends]] = None,
|
| 703 |
+
summary: Optional[str] = None,
|
| 704 |
+
description: Optional[str] = None,
|
| 705 |
+
response_description: str = "Successful Response",
|
| 706 |
+
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
| 707 |
+
deprecated: Optional[bool] = None,
|
| 708 |
+
operation_id: Optional[str] = None,
|
| 709 |
+
response_model_include: Optional[IncEx] = None,
|
| 710 |
+
response_model_exclude: Optional[IncEx] = None,
|
| 711 |
+
response_model_by_alias: bool = True,
|
| 712 |
+
response_model_exclude_unset: bool = False,
|
| 713 |
+
response_model_exclude_defaults: bool = False,
|
| 714 |
+
response_model_exclude_none: bool = False,
|
| 715 |
+
include_in_schema: bool = True,
|
| 716 |
+
response_class: Type[Response] = Default(JSONResponse),
|
| 717 |
+
name: Optional[str] = None,
|
| 718 |
+
callbacks: Optional[List[BaseRoute]] = None,
|
| 719 |
+
openapi_extra: Optional[Dict[str, Any]] = None,
|
| 720 |
+
generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(
|
| 721 |
+
generate_unique_id
|
| 722 |
+
),
|
| 723 |
+
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
| 724 |
+
return self.router.options(
|
| 725 |
+
path,
|
| 726 |
+
response_model=response_model,
|
| 727 |
+
status_code=status_code,
|
| 728 |
+
tags=tags,
|
| 729 |
+
dependencies=dependencies,
|
| 730 |
+
summary=summary,
|
| 731 |
+
description=description,
|
| 732 |
+
response_description=response_description,
|
| 733 |
+
responses=responses,
|
| 734 |
+
deprecated=deprecated,
|
| 735 |
+
operation_id=operation_id,
|
| 736 |
+
response_model_include=response_model_include,
|
| 737 |
+
response_model_exclude=response_model_exclude,
|
| 738 |
+
response_model_by_alias=response_model_by_alias,
|
| 739 |
+
response_model_exclude_unset=response_model_exclude_unset,
|
| 740 |
+
response_model_exclude_defaults=response_model_exclude_defaults,
|
| 741 |
+
response_model_exclude_none=response_model_exclude_none,
|
| 742 |
+
include_in_schema=include_in_schema,
|
| 743 |
+
response_class=response_class,
|
| 744 |
+
name=name,
|
| 745 |
+
callbacks=callbacks,
|
| 746 |
+
openapi_extra=openapi_extra,
|
| 747 |
+
generate_unique_id_function=generate_unique_id_function,
|
| 748 |
+
)
|
| 749 |
+
|
| 750 |
+
def head(
|
| 751 |
+
self,
|
| 752 |
+
path: str,
|
| 753 |
+
*,
|
| 754 |
+
response_model: Any = Default(None),
|
| 755 |
+
status_code: Optional[int] = None,
|
| 756 |
+
tags: Optional[List[Union[str, Enum]]] = None,
|
| 757 |
+
dependencies: Optional[Sequence[Depends]] = None,
|
| 758 |
+
summary: Optional[str] = None,
|
| 759 |
+
description: Optional[str] = None,
|
| 760 |
+
response_description: str = "Successful Response",
|
| 761 |
+
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
| 762 |
+
deprecated: Optional[bool] = None,
|
| 763 |
+
operation_id: Optional[str] = None,
|
| 764 |
+
response_model_include: Optional[IncEx] = None,
|
| 765 |
+
response_model_exclude: Optional[IncEx] = None,
|
| 766 |
+
response_model_by_alias: bool = True,
|
| 767 |
+
response_model_exclude_unset: bool = False,
|
| 768 |
+
response_model_exclude_defaults: bool = False,
|
| 769 |
+
response_model_exclude_none: bool = False,
|
| 770 |
+
include_in_schema: bool = True,
|
| 771 |
+
response_class: Type[Response] = Default(JSONResponse),
|
| 772 |
+
name: Optional[str] = None,
|
| 773 |
+
callbacks: Optional[List[BaseRoute]] = None,
|
| 774 |
+
openapi_extra: Optional[Dict[str, Any]] = None,
|
| 775 |
+
generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(
|
| 776 |
+
generate_unique_id
|
| 777 |
+
),
|
| 778 |
+
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
| 779 |
+
return self.router.head(
|
| 780 |
+
path,
|
| 781 |
+
response_model=response_model,
|
| 782 |
+
status_code=status_code,
|
| 783 |
+
tags=tags,
|
| 784 |
+
dependencies=dependencies,
|
| 785 |
+
summary=summary,
|
| 786 |
+
description=description,
|
| 787 |
+
response_description=response_description,
|
| 788 |
+
responses=responses,
|
| 789 |
+
deprecated=deprecated,
|
| 790 |
+
operation_id=operation_id,
|
| 791 |
+
response_model_include=response_model_include,
|
| 792 |
+
response_model_exclude=response_model_exclude,
|
| 793 |
+
response_model_by_alias=response_model_by_alias,
|
| 794 |
+
response_model_exclude_unset=response_model_exclude_unset,
|
| 795 |
+
response_model_exclude_defaults=response_model_exclude_defaults,
|
| 796 |
+
response_model_exclude_none=response_model_exclude_none,
|
| 797 |
+
include_in_schema=include_in_schema,
|
| 798 |
+
response_class=response_class,
|
| 799 |
+
name=name,
|
| 800 |
+
callbacks=callbacks,
|
| 801 |
+
openapi_extra=openapi_extra,
|
| 802 |
+
generate_unique_id_function=generate_unique_id_function,
|
| 803 |
+
)
|
| 804 |
+
|
| 805 |
+
def patch(
|
| 806 |
+
self,
|
| 807 |
+
path: str,
|
| 808 |
+
*,
|
| 809 |
+
response_model: Any = Default(None),
|
| 810 |
+
status_code: Optional[int] = None,
|
| 811 |
+
tags: Optional[List[Union[str, Enum]]] = None,
|
| 812 |
+
dependencies: Optional[Sequence[Depends]] = None,
|
| 813 |
+
summary: Optional[str] = None,
|
| 814 |
+
description: Optional[str] = None,
|
| 815 |
+
response_description: str = "Successful Response",
|
| 816 |
+
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
| 817 |
+
deprecated: Optional[bool] = None,
|
| 818 |
+
operation_id: Optional[str] = None,
|
| 819 |
+
response_model_include: Optional[IncEx] = None,
|
| 820 |
+
response_model_exclude: Optional[IncEx] = None,
|
| 821 |
+
response_model_by_alias: bool = True,
|
| 822 |
+
response_model_exclude_unset: bool = False,
|
| 823 |
+
response_model_exclude_defaults: bool = False,
|
| 824 |
+
response_model_exclude_none: bool = False,
|
| 825 |
+
include_in_schema: bool = True,
|
| 826 |
+
response_class: Type[Response] = Default(JSONResponse),
|
| 827 |
+
name: Optional[str] = None,
|
| 828 |
+
callbacks: Optional[List[BaseRoute]] = None,
|
| 829 |
+
openapi_extra: Optional[Dict[str, Any]] = None,
|
| 830 |
+
generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(
|
| 831 |
+
generate_unique_id
|
| 832 |
+
),
|
| 833 |
+
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
| 834 |
+
return self.router.patch(
|
| 835 |
+
path,
|
| 836 |
+
response_model=response_model,
|
| 837 |
+
status_code=status_code,
|
| 838 |
+
tags=tags,
|
| 839 |
+
dependencies=dependencies,
|
| 840 |
+
summary=summary,
|
| 841 |
+
description=description,
|
| 842 |
+
response_description=response_description,
|
| 843 |
+
responses=responses,
|
| 844 |
+
deprecated=deprecated,
|
| 845 |
+
operation_id=operation_id,
|
| 846 |
+
response_model_include=response_model_include,
|
| 847 |
+
response_model_exclude=response_model_exclude,
|
| 848 |
+
response_model_by_alias=response_model_by_alias,
|
| 849 |
+
response_model_exclude_unset=response_model_exclude_unset,
|
| 850 |
+
response_model_exclude_defaults=response_model_exclude_defaults,
|
| 851 |
+
response_model_exclude_none=response_model_exclude_none,
|
| 852 |
+
include_in_schema=include_in_schema,
|
| 853 |
+
response_class=response_class,
|
| 854 |
+
name=name,
|
| 855 |
+
callbacks=callbacks,
|
| 856 |
+
openapi_extra=openapi_extra,
|
| 857 |
+
generate_unique_id_function=generate_unique_id_function,
|
| 858 |
+
)
|
| 859 |
+
|
| 860 |
+
def trace(
|
| 861 |
+
self,
|
| 862 |
+
path: str,
|
| 863 |
+
*,
|
| 864 |
+
response_model: Any = Default(None),
|
| 865 |
+
status_code: Optional[int] = None,
|
| 866 |
+
tags: Optional[List[Union[str, Enum]]] = None,
|
| 867 |
+
dependencies: Optional[Sequence[Depends]] = None,
|
| 868 |
+
summary: Optional[str] = None,
|
| 869 |
+
description: Optional[str] = None,
|
| 870 |
+
response_description: str = "Successful Response",
|
| 871 |
+
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
| 872 |
+
deprecated: Optional[bool] = None,
|
| 873 |
+
operation_id: Optional[str] = None,
|
| 874 |
+
response_model_include: Optional[IncEx] = None,
|
| 875 |
+
response_model_exclude: Optional[IncEx] = None,
|
| 876 |
+
response_model_by_alias: bool = True,
|
| 877 |
+
response_model_exclude_unset: bool = False,
|
| 878 |
+
response_model_exclude_defaults: bool = False,
|
| 879 |
+
response_model_exclude_none: bool = False,
|
| 880 |
+
include_in_schema: bool = True,
|
| 881 |
+
response_class: Type[Response] = Default(JSONResponse),
|
| 882 |
+
name: Optional[str] = None,
|
| 883 |
+
callbacks: Optional[List[BaseRoute]] = None,
|
| 884 |
+
openapi_extra: Optional[Dict[str, Any]] = None,
|
| 885 |
+
generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(
|
| 886 |
+
generate_unique_id
|
| 887 |
+
),
|
| 888 |
+
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
| 889 |
+
return self.router.trace(
|
| 890 |
+
path,
|
| 891 |
+
response_model=response_model,
|
| 892 |
+
status_code=status_code,
|
| 893 |
+
tags=tags,
|
| 894 |
+
dependencies=dependencies,
|
| 895 |
+
summary=summary,
|
| 896 |
+
description=description,
|
| 897 |
+
response_description=response_description,
|
| 898 |
+
responses=responses,
|
| 899 |
+
deprecated=deprecated,
|
| 900 |
+
operation_id=operation_id,
|
| 901 |
+
response_model_include=response_model_include,
|
| 902 |
+
response_model_exclude=response_model_exclude,
|
| 903 |
+
response_model_by_alias=response_model_by_alias,
|
| 904 |
+
response_model_exclude_unset=response_model_exclude_unset,
|
| 905 |
+
response_model_exclude_defaults=response_model_exclude_defaults,
|
| 906 |
+
response_model_exclude_none=response_model_exclude_none,
|
| 907 |
+
include_in_schema=include_in_schema,
|
| 908 |
+
response_class=response_class,
|
| 909 |
+
name=name,
|
| 910 |
+
callbacks=callbacks,
|
| 911 |
+
openapi_extra=openapi_extra,
|
| 912 |
+
generate_unique_id_function=generate_unique_id_function,
|
| 913 |
+
)
|
| 914 |
+
|
| 915 |
+
def websocket_route(
|
| 916 |
+
self, path: str, name: Union[str, None] = None
|
| 917 |
+
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
| 918 |
+
def decorator(func: DecoratedCallable) -> DecoratedCallable:
|
| 919 |
+
self.router.add_websocket_route(path, func, name=name)
|
| 920 |
+
return func
|
| 921 |
+
|
| 922 |
+
return decorator
|
| 923 |
+
|
| 924 |
+
def on_event(
|
| 925 |
+
self, event_type: str
|
| 926 |
+
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
| 927 |
+
return self.router.on_event(event_type)
|
| 928 |
+
|
| 929 |
+
def middleware(
|
| 930 |
+
self, middleware_type: str
|
| 931 |
+
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
| 932 |
+
def decorator(func: DecoratedCallable) -> DecoratedCallable:
|
| 933 |
+
self.add_middleware(BaseHTTPMiddleware, dispatch=func)
|
| 934 |
+
return func
|
| 935 |
+
|
| 936 |
+
return decorator
|
| 937 |
+
|
| 938 |
+
def exception_handler(
|
| 939 |
+
self, exc_class_or_status_code: Union[int, Type[Exception]]
|
| 940 |
+
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
| 941 |
+
def decorator(func: DecoratedCallable) -> DecoratedCallable:
|
| 942 |
+
self.add_exception_handler(exc_class_or_status_code, func)
|
| 943 |
+
return func
|
| 944 |
+
|
| 945 |
+
return decorator
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/concurrency.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from contextlib import AsyncExitStack as AsyncExitStack # noqa
|
| 2 |
+
from contextlib import asynccontextmanager as asynccontextmanager
|
| 3 |
+
from typing import AsyncGenerator, ContextManager, TypeVar
|
| 4 |
+
|
| 5 |
+
import anyio
|
| 6 |
+
from anyio import CapacityLimiter
|
| 7 |
+
from starlette.concurrency import iterate_in_threadpool as iterate_in_threadpool # noqa
|
| 8 |
+
from starlette.concurrency import run_in_threadpool as run_in_threadpool # noqa
|
| 9 |
+
from starlette.concurrency import ( # noqa
|
| 10 |
+
run_until_first_complete as run_until_first_complete,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
_T = TypeVar("_T")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@asynccontextmanager
|
| 17 |
+
async def contextmanager_in_threadpool(
|
| 18 |
+
cm: ContextManager[_T],
|
| 19 |
+
) -> AsyncGenerator[_T, None]:
|
| 20 |
+
# blocking __exit__ from running waiting on a free thread
|
| 21 |
+
# can create race conditions/deadlocks if the context manager itself
|
| 22 |
+
# has its own internal pool (e.g. a database connection pool)
|
| 23 |
+
# to avoid this we let __exit__ run without a capacity limit
|
| 24 |
+
# since we're creating a new limiter for each call, any non-zero limit
|
| 25 |
+
# works (1 is arbitrary)
|
| 26 |
+
exit_limiter = CapacityLimiter(1)
|
| 27 |
+
try:
|
| 28 |
+
yield await run_in_threadpool(cm.__enter__)
|
| 29 |
+
except Exception as e:
|
| 30 |
+
ok = bool(
|
| 31 |
+
await anyio.to_thread.run_sync(
|
| 32 |
+
cm.__exit__, type(e), e, None, limiter=exit_limiter
|
| 33 |
+
)
|
| 34 |
+
)
|
| 35 |
+
if not ok:
|
| 36 |
+
raise e
|
| 37 |
+
else:
|
| 38 |
+
await anyio.to_thread.run_sync(
|
| 39 |
+
cm.__exit__, None, None, None, limiter=exit_limiter
|
| 40 |
+
)
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/datastructures.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Callable, Dict, Iterable, Type, TypeVar, cast
|
| 2 |
+
|
| 3 |
+
from fastapi._compat import (
|
| 4 |
+
PYDANTIC_V2,
|
| 5 |
+
CoreSchema,
|
| 6 |
+
GetJsonSchemaHandler,
|
| 7 |
+
JsonSchemaValue,
|
| 8 |
+
with_info_plain_validator_function,
|
| 9 |
+
)
|
| 10 |
+
from starlette.datastructures import URL as URL # noqa: F401
|
| 11 |
+
from starlette.datastructures import Address as Address # noqa: F401
|
| 12 |
+
from starlette.datastructures import FormData as FormData # noqa: F401
|
| 13 |
+
from starlette.datastructures import Headers as Headers # noqa: F401
|
| 14 |
+
from starlette.datastructures import QueryParams as QueryParams # noqa: F401
|
| 15 |
+
from starlette.datastructures import State as State # noqa: F401
|
| 16 |
+
from starlette.datastructures import UploadFile as StarletteUploadFile
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class UploadFile(StarletteUploadFile):
|
| 20 |
+
@classmethod
|
| 21 |
+
def __get_validators__(cls: Type["UploadFile"]) -> Iterable[Callable[..., Any]]:
|
| 22 |
+
yield cls.validate
|
| 23 |
+
|
| 24 |
+
@classmethod
|
| 25 |
+
def validate(cls: Type["UploadFile"], v: Any) -> Any:
|
| 26 |
+
if not isinstance(v, StarletteUploadFile):
|
| 27 |
+
raise ValueError(f"Expected UploadFile, received: {type(v)}")
|
| 28 |
+
return v
|
| 29 |
+
|
| 30 |
+
@classmethod
|
| 31 |
+
def _validate(cls, __input_value: Any, _: Any) -> "UploadFile":
|
| 32 |
+
if not isinstance(__input_value, StarletteUploadFile):
|
| 33 |
+
raise ValueError(f"Expected UploadFile, received: {type(__input_value)}")
|
| 34 |
+
return cast(UploadFile, __input_value)
|
| 35 |
+
|
| 36 |
+
if not PYDANTIC_V2:
|
| 37 |
+
|
| 38 |
+
@classmethod
|
| 39 |
+
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
|
| 40 |
+
field_schema.update({"type": "string", "format": "binary"})
|
| 41 |
+
|
| 42 |
+
@classmethod
|
| 43 |
+
def __get_pydantic_json_schema__(
|
| 44 |
+
cls, core_schema: CoreSchema, handler: GetJsonSchemaHandler
|
| 45 |
+
) -> JsonSchemaValue:
|
| 46 |
+
return {"type": "string", "format": "binary"}
|
| 47 |
+
|
| 48 |
+
@classmethod
|
| 49 |
+
def __get_pydantic_core_schema__(
|
| 50 |
+
cls, source: Type[Any], handler: Callable[[Any], CoreSchema]
|
| 51 |
+
) -> CoreSchema:
|
| 52 |
+
return with_info_plain_validator_function(cls._validate)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class DefaultPlaceholder:
|
| 56 |
+
"""
|
| 57 |
+
You shouldn't use this class directly.
|
| 58 |
+
|
| 59 |
+
It's used internally to recognize when a default value has been overwritten, even
|
| 60 |
+
if the overridden default value was truthy.
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
def __init__(self, value: Any):
|
| 64 |
+
self.value = value
|
| 65 |
+
|
| 66 |
+
def __bool__(self) -> bool:
|
| 67 |
+
return bool(self.value)
|
| 68 |
+
|
| 69 |
+
def __eq__(self, o: object) -> bool:
|
| 70 |
+
return isinstance(o, DefaultPlaceholder) and o.value == self.value
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
DefaultType = TypeVar("DefaultType")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def Default(value: DefaultType) -> DefaultType:
|
| 77 |
+
"""
|
| 78 |
+
You shouldn't use this function directly.
|
| 79 |
+
|
| 80 |
+
It's used internally to recognize when a default value has been overwritten, even
|
| 81 |
+
if the overridden default value was truthy.
|
| 82 |
+
"""
|
| 83 |
+
return DefaultPlaceholder(value) # type: ignore
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/dependencies/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (18.3 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/dependencies/models.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Callable, List, Optional, Sequence
|
| 2 |
+
|
| 3 |
+
from fastapi._compat import ModelField
|
| 4 |
+
from fastapi.security.base import SecurityBase
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class SecurityRequirement:
|
| 8 |
+
def __init__(
|
| 9 |
+
self, security_scheme: SecurityBase, scopes: Optional[Sequence[str]] = None
|
| 10 |
+
):
|
| 11 |
+
self.security_scheme = security_scheme
|
| 12 |
+
self.scopes = scopes
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class Dependant:
|
| 16 |
+
def __init__(
|
| 17 |
+
self,
|
| 18 |
+
*,
|
| 19 |
+
path_params: Optional[List[ModelField]] = None,
|
| 20 |
+
query_params: Optional[List[ModelField]] = None,
|
| 21 |
+
header_params: Optional[List[ModelField]] = None,
|
| 22 |
+
cookie_params: Optional[List[ModelField]] = None,
|
| 23 |
+
body_params: Optional[List[ModelField]] = None,
|
| 24 |
+
dependencies: Optional[List["Dependant"]] = None,
|
| 25 |
+
security_schemes: Optional[List[SecurityRequirement]] = None,
|
| 26 |
+
name: Optional[str] = None,
|
| 27 |
+
call: Optional[Callable[..., Any]] = None,
|
| 28 |
+
request_param_name: Optional[str] = None,
|
| 29 |
+
websocket_param_name: Optional[str] = None,
|
| 30 |
+
http_connection_param_name: Optional[str] = None,
|
| 31 |
+
response_param_name: Optional[str] = None,
|
| 32 |
+
background_tasks_param_name: Optional[str] = None,
|
| 33 |
+
security_scopes_param_name: Optional[str] = None,
|
| 34 |
+
security_scopes: Optional[List[str]] = None,
|
| 35 |
+
use_cache: bool = True,
|
| 36 |
+
path: Optional[str] = None,
|
| 37 |
+
) -> None:
|
| 38 |
+
self.path_params = path_params or []
|
| 39 |
+
self.query_params = query_params or []
|
| 40 |
+
self.header_params = header_params or []
|
| 41 |
+
self.cookie_params = cookie_params or []
|
| 42 |
+
self.body_params = body_params or []
|
| 43 |
+
self.dependencies = dependencies or []
|
| 44 |
+
self.security_requirements = security_schemes or []
|
| 45 |
+
self.request_param_name = request_param_name
|
| 46 |
+
self.websocket_param_name = websocket_param_name
|
| 47 |
+
self.http_connection_param_name = http_connection_param_name
|
| 48 |
+
self.response_param_name = response_param_name
|
| 49 |
+
self.background_tasks_param_name = background_tasks_param_name
|
| 50 |
+
self.security_scopes = security_scopes
|
| 51 |
+
self.security_scopes_param_name = security_scopes_param_name
|
| 52 |
+
self.name = name
|
| 53 |
+
self.call = call
|
| 54 |
+
self.use_cache = use_cache
|
| 55 |
+
# Store the path to be able to re-generate a dependable from it in overrides
|
| 56 |
+
self.path = path
|
| 57 |
+
# Save the cache key at creation to optimize performance
|
| 58 |
+
self.cache_key = (self.call, tuple(sorted(set(self.security_scopes or []))))
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/exceptions.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict, Optional, Sequence, Type
|
| 2 |
+
|
| 3 |
+
from pydantic import BaseModel, create_model
|
| 4 |
+
from starlette.exceptions import HTTPException as StarletteHTTPException
|
| 5 |
+
from starlette.exceptions import WebSocketException as WebSocketException # noqa: F401
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class HTTPException(StarletteHTTPException):
|
| 9 |
+
def __init__(
|
| 10 |
+
self,
|
| 11 |
+
status_code: int,
|
| 12 |
+
detail: Any = None,
|
| 13 |
+
headers: Optional[Dict[str, str]] = None,
|
| 14 |
+
) -> None:
|
| 15 |
+
super().__init__(status_code=status_code, detail=detail, headers=headers)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
RequestErrorModel: Type[BaseModel] = create_model("Request")
|
| 19 |
+
WebSocketErrorModel: Type[BaseModel] = create_model("WebSocket")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class FastAPIError(RuntimeError):
|
| 23 |
+
"""
|
| 24 |
+
A generic, FastAPI-specific error.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class ValidationException(Exception):
|
| 29 |
+
def __init__(self, errors: Sequence[Any]) -> None:
|
| 30 |
+
self._errors = errors
|
| 31 |
+
|
| 32 |
+
def errors(self) -> Sequence[Any]:
|
| 33 |
+
return self._errors
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class RequestValidationError(ValidationException):
|
| 37 |
+
def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None:
|
| 38 |
+
super().__init__(errors)
|
| 39 |
+
self.body = body
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class WebSocketRequestValidationError(ValidationException):
|
| 43 |
+
pass
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class ResponseValidationError(ValidationException):
|
| 47 |
+
def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None:
|
| 48 |
+
super().__init__(errors)
|
| 49 |
+
self.body = body
|
| 50 |
+
|
| 51 |
+
def __str__(self) -> str:
|
| 52 |
+
message = f"{len(self._errors)} validation errors:\n"
|
| 53 |
+
for err in self._errors:
|
| 54 |
+
message += f" {err}\n"
|
| 55 |
+
return message
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/logger.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
|
| 3 |
+
logger = logging.getLogger("fastapi")
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from starlette.middleware import Middleware as Middleware
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (232 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/__pycache__/asyncexitstack.cpython-310.pyc
ADDED
|
Binary file (1.22 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/__pycache__/cors.cpython-310.pyc
ADDED
|
Binary file (237 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/__pycache__/gzip.cpython-310.pyc
ADDED
|
Binary file (237 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/__pycache__/httpsredirect.cpython-310.pyc
ADDED
|
Binary file (264 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/__pycache__/trustedhost.cpython-310.pyc
ADDED
|
Binary file (258 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/__pycache__/wsgi.cpython-310.pyc
ADDED
|
Binary file (237 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/asyncexitstack.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
|
| 3 |
+
from fastapi.concurrency import AsyncExitStack
|
| 4 |
+
from starlette.types import ASGIApp, Receive, Scope, Send
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class AsyncExitStackMiddleware:
|
| 8 |
+
def __init__(self, app: ASGIApp, context_name: str = "fastapi_astack") -> None:
|
| 9 |
+
self.app = app
|
| 10 |
+
self.context_name = context_name
|
| 11 |
+
|
| 12 |
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
| 13 |
+
dependency_exception: Optional[Exception] = None
|
| 14 |
+
async with AsyncExitStack() as stack:
|
| 15 |
+
scope[self.context_name] = stack
|
| 16 |
+
try:
|
| 17 |
+
await self.app(scope, receive, send)
|
| 18 |
+
except Exception as e:
|
| 19 |
+
dependency_exception = e
|
| 20 |
+
raise e
|
| 21 |
+
if dependency_exception:
|
| 22 |
+
# This exception was possibly handled by the dependency but it should
|
| 23 |
+
# still bubble up so that the ServerErrorMiddleware can return a 500
|
| 24 |
+
# or the ExceptionMiddleware can catch and handle any other exceptions
|
| 25 |
+
raise dependency_exception
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/cors.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from starlette.middleware.cors import CORSMiddleware as CORSMiddleware # noqa
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/gzip.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from starlette.middleware.gzip import GZipMiddleware as GZipMiddleware # noqa
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/httpsredirect.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from starlette.middleware.httpsredirect import ( # noqa
|
| 2 |
+
HTTPSRedirectMiddleware as HTTPSRedirectMiddleware,
|
| 3 |
+
)
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/trustedhost.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from starlette.middleware.trustedhost import ( # noqa
|
| 2 |
+
TrustedHostMiddleware as TrustedHostMiddleware,
|
| 3 |
+
)
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/middleware/wsgi.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from starlette.middleware.wsgi import WSGIMiddleware as WSGIMiddleware # noqa
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/py.typed
ADDED
|
File without changes
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/requests.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from starlette.requests import HTTPConnection as HTTPConnection # noqa: F401
|
| 2 |
+
from starlette.requests import Request as Request # noqa: F401
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/security/__pycache__/base.cpython-310.pyc
ADDED
|
Binary file (463 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/security/__pycache__/http.cpython-310.pyc
ADDED
|
Binary file (4.63 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/security/api_key.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
|
| 3 |
+
from fastapi.openapi.models import APIKey, APIKeyIn
|
| 4 |
+
from fastapi.security.base import SecurityBase
|
| 5 |
+
from starlette.exceptions import HTTPException
|
| 6 |
+
from starlette.requests import Request
|
| 7 |
+
from starlette.status import HTTP_403_FORBIDDEN
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class APIKeyBase(SecurityBase):
|
| 11 |
+
pass
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class APIKeyQuery(APIKeyBase):
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
*,
|
| 18 |
+
name: str,
|
| 19 |
+
scheme_name: Optional[str] = None,
|
| 20 |
+
description: Optional[str] = None,
|
| 21 |
+
auto_error: bool = True,
|
| 22 |
+
):
|
| 23 |
+
self.model: APIKey = APIKey(
|
| 24 |
+
**{"in": APIKeyIn.query}, # type: ignore[arg-type]
|
| 25 |
+
name=name,
|
| 26 |
+
description=description,
|
| 27 |
+
)
|
| 28 |
+
self.scheme_name = scheme_name or self.__class__.__name__
|
| 29 |
+
self.auto_error = auto_error
|
| 30 |
+
|
| 31 |
+
async def __call__(self, request: Request) -> Optional[str]:
|
| 32 |
+
api_key = request.query_params.get(self.model.name)
|
| 33 |
+
if not api_key:
|
| 34 |
+
if self.auto_error:
|
| 35 |
+
raise HTTPException(
|
| 36 |
+
status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
|
| 37 |
+
)
|
| 38 |
+
else:
|
| 39 |
+
return None
|
| 40 |
+
return api_key
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class APIKeyHeader(APIKeyBase):
|
| 44 |
+
def __init__(
|
| 45 |
+
self,
|
| 46 |
+
*,
|
| 47 |
+
name: str,
|
| 48 |
+
scheme_name: Optional[str] = None,
|
| 49 |
+
description: Optional[str] = None,
|
| 50 |
+
auto_error: bool = True,
|
| 51 |
+
):
|
| 52 |
+
self.model: APIKey = APIKey(
|
| 53 |
+
**{"in": APIKeyIn.header}, # type: ignore[arg-type]
|
| 54 |
+
name=name,
|
| 55 |
+
description=description,
|
| 56 |
+
)
|
| 57 |
+
self.scheme_name = scheme_name or self.__class__.__name__
|
| 58 |
+
self.auto_error = auto_error
|
| 59 |
+
|
| 60 |
+
async def __call__(self, request: Request) -> Optional[str]:
|
| 61 |
+
api_key = request.headers.get(self.model.name)
|
| 62 |
+
if not api_key:
|
| 63 |
+
if self.auto_error:
|
| 64 |
+
raise HTTPException(
|
| 65 |
+
status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
|
| 66 |
+
)
|
| 67 |
+
else:
|
| 68 |
+
return None
|
| 69 |
+
return api_key
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class APIKeyCookie(APIKeyBase):
|
| 73 |
+
def __init__(
|
| 74 |
+
self,
|
| 75 |
+
*,
|
| 76 |
+
name: str,
|
| 77 |
+
scheme_name: Optional[str] = None,
|
| 78 |
+
description: Optional[str] = None,
|
| 79 |
+
auto_error: bool = True,
|
| 80 |
+
):
|
| 81 |
+
self.model: APIKey = APIKey(
|
| 82 |
+
**{"in": APIKeyIn.cookie}, # type: ignore[arg-type]
|
| 83 |
+
name=name,
|
| 84 |
+
description=description,
|
| 85 |
+
)
|
| 86 |
+
self.scheme_name = scheme_name or self.__class__.__name__
|
| 87 |
+
self.auto_error = auto_error
|
| 88 |
+
|
| 89 |
+
async def __call__(self, request: Request) -> Optional[str]:
|
| 90 |
+
api_key = request.cookies.get(self.model.name)
|
| 91 |
+
if not api_key:
|
| 92 |
+
if self.auto_error:
|
| 93 |
+
raise HTTPException(
|
| 94 |
+
status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
|
| 95 |
+
)
|
| 96 |
+
else:
|
| 97 |
+
return None
|
| 98 |
+
return api_key
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/security/base.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi.openapi.models import SecurityBase as SecurityBaseModel
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class SecurityBase:
|
| 5 |
+
model: SecurityBaseModel
|
| 6 |
+
scheme_name: str
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/security/http.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import binascii
|
| 2 |
+
from base64 import b64decode
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
from fastapi.exceptions import HTTPException
|
| 6 |
+
from fastapi.openapi.models import HTTPBase as HTTPBaseModel
|
| 7 |
+
from fastapi.openapi.models import HTTPBearer as HTTPBearerModel
|
| 8 |
+
from fastapi.security.base import SecurityBase
|
| 9 |
+
from fastapi.security.utils import get_authorization_scheme_param
|
| 10 |
+
from pydantic import BaseModel
|
| 11 |
+
from starlette.requests import Request
|
| 12 |
+
from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class HTTPBasicCredentials(BaseModel):
|
| 16 |
+
username: str
|
| 17 |
+
password: str
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class HTTPAuthorizationCredentials(BaseModel):
|
| 21 |
+
scheme: str
|
| 22 |
+
credentials: str
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class HTTPBase(SecurityBase):
|
| 26 |
+
def __init__(
|
| 27 |
+
self,
|
| 28 |
+
*,
|
| 29 |
+
scheme: str,
|
| 30 |
+
scheme_name: Optional[str] = None,
|
| 31 |
+
description: Optional[str] = None,
|
| 32 |
+
auto_error: bool = True,
|
| 33 |
+
):
|
| 34 |
+
self.model = HTTPBaseModel(scheme=scheme, description=description)
|
| 35 |
+
self.scheme_name = scheme_name or self.__class__.__name__
|
| 36 |
+
self.auto_error = auto_error
|
| 37 |
+
|
| 38 |
+
async def __call__(
|
| 39 |
+
self, request: Request
|
| 40 |
+
) -> Optional[HTTPAuthorizationCredentials]:
|
| 41 |
+
authorization = request.headers.get("Authorization")
|
| 42 |
+
scheme, credentials = get_authorization_scheme_param(authorization)
|
| 43 |
+
if not (authorization and scheme and credentials):
|
| 44 |
+
if self.auto_error:
|
| 45 |
+
raise HTTPException(
|
| 46 |
+
status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
|
| 47 |
+
)
|
| 48 |
+
else:
|
| 49 |
+
return None
|
| 50 |
+
return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class HTTPBasic(HTTPBase):
|
| 54 |
+
def __init__(
|
| 55 |
+
self,
|
| 56 |
+
*,
|
| 57 |
+
scheme_name: Optional[str] = None,
|
| 58 |
+
realm: Optional[str] = None,
|
| 59 |
+
description: Optional[str] = None,
|
| 60 |
+
auto_error: bool = True,
|
| 61 |
+
):
|
| 62 |
+
self.model = HTTPBaseModel(scheme="basic", description=description)
|
| 63 |
+
self.scheme_name = scheme_name or self.__class__.__name__
|
| 64 |
+
self.realm = realm
|
| 65 |
+
self.auto_error = auto_error
|
| 66 |
+
|
| 67 |
+
async def __call__( # type: ignore
|
| 68 |
+
self, request: Request
|
| 69 |
+
) -> Optional[HTTPBasicCredentials]:
|
| 70 |
+
authorization = request.headers.get("Authorization")
|
| 71 |
+
scheme, param = get_authorization_scheme_param(authorization)
|
| 72 |
+
if self.realm:
|
| 73 |
+
unauthorized_headers = {"WWW-Authenticate": f'Basic realm="{self.realm}"'}
|
| 74 |
+
else:
|
| 75 |
+
unauthorized_headers = {"WWW-Authenticate": "Basic"}
|
| 76 |
+
if not authorization or scheme.lower() != "basic":
|
| 77 |
+
if self.auto_error:
|
| 78 |
+
raise HTTPException(
|
| 79 |
+
status_code=HTTP_401_UNAUTHORIZED,
|
| 80 |
+
detail="Not authenticated",
|
| 81 |
+
headers=unauthorized_headers,
|
| 82 |
+
)
|
| 83 |
+
else:
|
| 84 |
+
return None
|
| 85 |
+
invalid_user_credentials_exc = HTTPException(
|
| 86 |
+
status_code=HTTP_401_UNAUTHORIZED,
|
| 87 |
+
detail="Invalid authentication credentials",
|
| 88 |
+
headers=unauthorized_headers,
|
| 89 |
+
)
|
| 90 |
+
try:
|
| 91 |
+
data = b64decode(param).decode("ascii")
|
| 92 |
+
except (ValueError, UnicodeDecodeError, binascii.Error):
|
| 93 |
+
raise invalid_user_credentials_exc
|
| 94 |
+
username, separator, password = data.partition(":")
|
| 95 |
+
if not separator:
|
| 96 |
+
raise invalid_user_credentials_exc
|
| 97 |
+
return HTTPBasicCredentials(username=username, password=password)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class HTTPBearer(HTTPBase):
|
| 101 |
+
def __init__(
|
| 102 |
+
self,
|
| 103 |
+
*,
|
| 104 |
+
bearerFormat: Optional[str] = None,
|
| 105 |
+
scheme_name: Optional[str] = None,
|
| 106 |
+
description: Optional[str] = None,
|
| 107 |
+
auto_error: bool = True,
|
| 108 |
+
):
|
| 109 |
+
self.model = HTTPBearerModel(bearerFormat=bearerFormat, description=description)
|
| 110 |
+
self.scheme_name = scheme_name or self.__class__.__name__
|
| 111 |
+
self.auto_error = auto_error
|
| 112 |
+
|
| 113 |
+
async def __call__(
|
| 114 |
+
self, request: Request
|
| 115 |
+
) -> Optional[HTTPAuthorizationCredentials]:
|
| 116 |
+
authorization = request.headers.get("Authorization")
|
| 117 |
+
scheme, credentials = get_authorization_scheme_param(authorization)
|
| 118 |
+
if not (authorization and scheme and credentials):
|
| 119 |
+
if self.auto_error:
|
| 120 |
+
raise HTTPException(
|
| 121 |
+
status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
|
| 122 |
+
)
|
| 123 |
+
else:
|
| 124 |
+
return None
|
| 125 |
+
if scheme.lower() != "bearer":
|
| 126 |
+
if self.auto_error:
|
| 127 |
+
raise HTTPException(
|
| 128 |
+
status_code=HTTP_403_FORBIDDEN,
|
| 129 |
+
detail="Invalid authentication credentials",
|
| 130 |
+
)
|
| 131 |
+
else:
|
| 132 |
+
return None
|
| 133 |
+
return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class HTTPDigest(HTTPBase):
|
| 137 |
+
def __init__(
|
| 138 |
+
self,
|
| 139 |
+
*,
|
| 140 |
+
scheme_name: Optional[str] = None,
|
| 141 |
+
description: Optional[str] = None,
|
| 142 |
+
auto_error: bool = True,
|
| 143 |
+
):
|
| 144 |
+
self.model = HTTPBaseModel(scheme="digest", description=description)
|
| 145 |
+
self.scheme_name = scheme_name or self.__class__.__name__
|
| 146 |
+
self.auto_error = auto_error
|
| 147 |
+
|
| 148 |
+
async def __call__(
|
| 149 |
+
self, request: Request
|
| 150 |
+
) -> Optional[HTTPAuthorizationCredentials]:
|
| 151 |
+
authorization = request.headers.get("Authorization")
|
| 152 |
+
scheme, credentials = get_authorization_scheme_param(authorization)
|
| 153 |
+
if not (authorization and scheme and credentials):
|
| 154 |
+
if self.auto_error:
|
| 155 |
+
raise HTTPException(
|
| 156 |
+
status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
|
| 157 |
+
)
|
| 158 |
+
else:
|
| 159 |
+
return None
|
| 160 |
+
if scheme.lower() != "digest":
|
| 161 |
+
raise HTTPException(
|
| 162 |
+
status_code=HTTP_403_FORBIDDEN,
|
| 163 |
+
detail="Invalid authentication credentials",
|
| 164 |
+
)
|
| 165 |
+
return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)
|
evalkit_tf437/lib/python3.10/site-packages/fastapi/security/open_id_connect_url.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
|
| 3 |
+
from fastapi.openapi.models import OpenIdConnect as OpenIdConnectModel
|
| 4 |
+
from fastapi.security.base import SecurityBase
|
| 5 |
+
from starlette.exceptions import HTTPException
|
| 6 |
+
from starlette.requests import Request
|
| 7 |
+
from starlette.status import HTTP_403_FORBIDDEN
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class OpenIdConnect(SecurityBase):
|
| 11 |
+
def __init__(
|
| 12 |
+
self,
|
| 13 |
+
*,
|
| 14 |
+
openIdConnectUrl: str,
|
| 15 |
+
scheme_name: Optional[str] = None,
|
| 16 |
+
description: Optional[str] = None,
|
| 17 |
+
auto_error: bool = True,
|
| 18 |
+
):
|
| 19 |
+
self.model = OpenIdConnectModel(
|
| 20 |
+
openIdConnectUrl=openIdConnectUrl, description=description
|
| 21 |
+
)
|
| 22 |
+
self.scheme_name = scheme_name or self.__class__.__name__
|
| 23 |
+
self.auto_error = auto_error
|
| 24 |
+
|
| 25 |
+
async def __call__(self, request: Request) -> Optional[str]:
|
| 26 |
+
authorization = request.headers.get("Authorization")
|
| 27 |
+
if not authorization:
|
| 28 |
+
if self.auto_error:
|
| 29 |
+
raise HTTPException(
|
| 30 |
+
status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
|
| 31 |
+
)
|
| 32 |
+
else:
|
| 33 |
+
return None
|
| 34 |
+
return authorization
|