






from collections import OrderedDict
from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import TensorType, logging


if TYPE_CHECKING:
     from ...onnx.config import PatchingSpec
     from ...tokenization_utils_base import PreTrainedTokenizerBase


lowerCamelCase__							=     logging.get_logger(__name__)

lowerCamelCase__							=     {
    """allenai/longformer-base-4096""": """https://huggingface.co/allenai/longformer-base-4096/resolve/main/config.json""",
    """allenai/longformer-large-4096""": """https://huggingface.co/allenai/longformer-large-4096/resolve/main/config.json""",
    """allenai/longformer-large-4096-finetuned-triviaqa""": (
        """https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/config.json"""
    ),
    """allenai/longformer-base-4096-extra.pos.embd.only""": (
        """https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/config.json"""
    ),
    """allenai/longformer-large-4096-extra.pos.embd.only""": (
        """https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/config.json"""
    ),
}




class 			snake_case__   (							__lowerCamelCase):

       '''simple docstring'''
       lowerCamelCase							:				Optional[int] 				= '''longformer'''



       def __init__(							self			,						a__ = 5_12			,						a__ = 2			,						a__ = 1			,						a__ = 0			,						a__ = 2			,						a__ = 3_05_22			,						a__ = 7_68			,						a__ = 12			,						a__ = 12			,						a__ = 30_72			,						a__ = "gelu"			,						a__ = 0.1			,						a__ = 0.1			,						a__ = 5_12			,						a__ = 2			,						a__ = 0.02			,						a__ = 1e-12			,						a__ = False			,						**a__			,						) ->      List[Any]:






            '''simple docstring'''





            super().__init__(pad_token_id=a_			,						**a_    )

            __snake_case			:str          =						attention_window
            __snake_case			:Union[str, Any]          =						sep_token_id
            __snake_case			:Dict          =						bos_token_id
            __snake_case			:List[Any]          =						eos_token_id
            __snake_case			:str          =						vocab_size
            __snake_case			:Union[str, Any]          =						hidden_size
            __snake_case			:Optional[Any]          =						num_hidden_layers
            __snake_case			:List[Any]          =						num_attention_heads
            __snake_case			:str          =						hidden_act
            __snake_case			:List[str]          =						intermediate_size
            __snake_case			:Optional[int]          =						hidden_dropout_prob
            __snake_case			:Optional[Any]          =						attention_probs_dropout_prob
            __snake_case			:Optional[int]          =						max_position_embeddings
            __snake_case			:Any          =						type_vocab_size
            __snake_case			:Union[str, Any]          =						initializer_range
            __snake_case			:Any          =						layer_norm_eps
            __snake_case			:Optional[int]          =						onnx_export




class 			snake_case__   (							__lowerCamelCase):

       '''simple docstring'''



       def __init__(							self			,						a__			,						a__ = "default"			,						a__ = None    ) ->      Dict:






            '''simple docstring'''





            super().__init__(a_			,						a_			,						a_    )
            __snake_case			:Union[str, Any]          =						True



       @property
       def 					__lowercase						(							self    ) ->      int:






            '''simple docstring'''





            if self.task == "multiple-choice":
                 __snake_case			:str          =						{0: "batch", 1: "choice", 2: "sequence"}
            else:
                 __snake_case			:Dict          =						{0: "batch", 1: "sequence"}
            return OrderedDict(
                [
                    ("""input_ids""", dynamic_axis),
                    ("""attention_mask""", dynamic_axis),
                    ("""global_attention_mask""", dynamic_axis),
                ]    )



       @property
       def 					__lowercase						(							self    ) ->      Union[str, Any]:






            '''simple docstring'''





            __snake_case			:List[str]          =						super().outputs
            if self.task == "default":
                 __snake_case			:Optional[int]          =						{0: "batch"}
            return outputs



       @property
       def 					__lowercase						(							self    ) ->      int:






            '''simple docstring'''





            return 1e-4



       @property
       def 					__lowercase						(							self    ) ->      List[str]:






            '''simple docstring'''





            return max(super().default_onnx_opset			,						14    )



       def 					__lowercase						(							self			,						a__			,						a__ = -1			,						a__ = -1			,						a__ = False			,						a__ = None			,						) ->      Optional[Any]:






            '''simple docstring'''





            __snake_case			:int          =						super().generate_dummy_inputs(
                preprocessor=a_			,						batch_size=a_			,						seq_length=a_			,						is_pair=a_			,						framework=a_    )
            import torch

            # for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64)
            # makes the export fail randomly
            __snake_case			:int          =						torch.zeros_like(inputs["""input_ids"""]    )
            # make every second token global
            __snake_case			:List[str]          =						1

            return inputs










# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

import torch

from ..models.auto import AutoModelForVisualQuestionAnswering, AutoProcessor
from ..utils import requires_backends
from .base import PipelineTool


if TYPE_CHECKING:
     from PIL import Image




class 			snake_case__   (							lowercase_):

       '''simple docstring'''
       lowerCamelCase							:				Tuple 				= "dandelin/vilt-b32-finetuned-vqa"
       lowerCamelCase							:				List[str] 				= (
           "This is a tool that answers a question about an image. It takes an input named `image` which should be the "
           "image containing the information, as well as a `question` which should be the question in English. It "
           "returns a text that is the answer to the question."
       )
       lowerCamelCase							:				Optional[Any] 				= "image_qa"
       lowerCamelCase							:				str 				= AutoProcessor
       lowerCamelCase							:				Union[str, Any] 				= AutoModelForVisualQuestionAnswering

       lowerCamelCase							:				Any 				= ["image", "text"]
       lowerCamelCase							:				Dict 				= ["text"]



       def __init__(							self			,						*a__			,						**a__    ) ->      Any:






            '''simple docstring'''





            requires_backends(self			,						["""vision"""]    )
            super().__init__(*a__			,						**a__    )



       def 					__lowercase						(							self			,						a__			,						a__    ) ->      int:






            '''simple docstring'''





            return self.pre_processor(a__			,						a__			,						return_tensors="""pt"""    )



       def 					__lowercase						(							self			,						a__    ) ->      Union[str, Any]:






            '''simple docstring'''





            with torch.no_grad():
                 return self.model(**a__    ).logits



       def 					__lowercase						(							self			,						a__    ) ->      Tuple:






            '''simple docstring'''





            __snake_case			:str          =						outputs.argmax(-1    ).item()
            return self.model.config.idalabel[idx]


