





"""simple docstring"""





import unittest

from transformers import is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
       from PIL import Image
else:

       class 		lowercase					:





             @staticmethod
             def     _snake_case			(       *lowercase      ,						**lowercase )		->     Any:
                   pass

@is_pipeline_test
@require_vision
class 		lowercase					(					unittest.TestCase					):





      @require_torch
      def     _snake_case			(       self )		->     List[str]:
            lowerCAmelCase  						=       pipeline(
                model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification"""      ,						)
            lowerCAmelCase  						=       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
            lowerCAmelCase  						=       image_classifier(lowercase      ,						candidate_labels=["""a""", """b""", """c"""] )

            # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across
            # python and torch versions.
            self.assertIn(
                nested_simplify(lowercase )      ,						[
                    [{"""score""": 0.333, """label""": """a"""}, {"""score""": 0.333, """label""": """b"""}, {"""score""": 0.333, """label""": """c"""}],
                    [{"""score""": 0.333, """label""": """a"""}, {"""score""": 0.333, """label""": """c"""}, {"""score""": 0.333, """label""": """b"""}],
                ]      ,						)

            lowerCAmelCase  						=       image_classifier([image] * 5      ,						candidate_labels=["""A""", """B""", """C"""]      ,						batch_size=2 )
            self.assertEqual(
                nested_simplify(lowercase )      ,						[
                    [
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                    ],
                    [
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                    ],
                    [
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                    ],
                    [
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                    ],
                    [
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                    ],
                ]      ,						)





      @require_tf
      def     _snake_case			(       self )		->     List[str]:
            lowerCAmelCase  						=       pipeline(
                model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification"""      ,						framework="""tf""" )
            lowerCAmelCase  						=       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
            lowerCAmelCase  						=       image_classifier(lowercase      ,						candidate_labels=["""a""", """b""", """c"""] )

            self.assertEqual(
                nested_simplify(lowercase )      ,						[{"""score""": 0.333, """label""": """a"""}, {"""score""": 0.333, """label""": """b"""}, {"""score""": 0.333, """label""": """c"""}]      ,						)

            lowerCAmelCase  						=       image_classifier([image] * 5      ,						candidate_labels=["""A""", """B""", """C"""]      ,						batch_size=2 )
            self.assertEqual(
                nested_simplify(lowercase )      ,						[
                    [
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                    ],
                    [
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                    ],
                    [
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                    ],
                    [
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                    ],
                    [
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                    ],
                ]      ,						)





      @slow
      @require_torch
      def     _snake_case			(       self )		->     Union[str, Any]:
            lowerCAmelCase  						=       pipeline(
                task="""zero-shot-image-classification"""      ,						model="""openai/clip-vit-base-patch32"""      ,						)
            # This is an image of 2 cats with remotes and no planes
            lowerCAmelCase  						=       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
            lowerCAmelCase  						=       image_classifier(lowercase      ,						candidate_labels=["""cat""", """plane""", """remote"""] )

            self.assertEqual(
                nested_simplify(lowercase )      ,						[
                    {"""score""": 0.511, """label""": """remote"""},
                    {"""score""": 0.485, """label""": """cat"""},
                    {"""score""": 0.004, """label""": """plane"""},
                ]      ,						)

            lowerCAmelCase  						=       image_classifier([image] * 5      ,						candidate_labels=["""cat""", """plane""", """remote"""]      ,						batch_size=2 )
            self.assertEqual(
                nested_simplify(lowercase )      ,						[
                    [
                        {"""score""": 0.511, """label""": """remote"""},
                        {"""score""": 0.485, """label""": """cat"""},
                        {"""score""": 0.004, """label""": """plane"""},
                    ],
                ]
                * 5      ,						)





      @slow
      @require_tf
      def     _snake_case			(       self )		->     Optional[Any]:
            lowerCAmelCase  						=       pipeline(
                task="""zero-shot-image-classification"""      ,						model="""openai/clip-vit-base-patch32"""      ,						framework="""tf""" )
            # This is an image of 2 cats with remotes and no planes
            lowerCAmelCase  						=       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
            lowerCAmelCase  						=       image_classifier(lowercase      ,						candidate_labels=["""cat""", """plane""", """remote"""] )
            self.assertEqual(
                nested_simplify(lowercase )      ,						[
                    {"""score""": 0.511, """label""": """remote"""},
                    {"""score""": 0.485, """label""": """cat"""},
                    {"""score""": 0.004, """label""": """plane"""},
                ]      ,						)

            lowerCAmelCase  						=       image_classifier([image] * 5      ,						candidate_labels=["""cat""", """plane""", """remote"""]      ,						batch_size=2 )
            self.assertEqual(
                nested_simplify(lowercase )      ,						[
                    [
                        {"""score""": 0.511, """label""": """remote"""},
                        {"""score""": 0.485, """label""": """cat"""},
                        {"""score""": 0.004, """label""": """plane"""},
                    ],
                ]
                * 5      ,						)













"""simple docstring"""





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


SCREAMING_SNAKE_CASE__					=   logging.get_logger(__name__)

SCREAMING_SNAKE_CASE__					=   {
    "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 		lowercase					(					_UpperCAmelCase					):
      _SCREAMING_SNAKE_CASE					=      'longformer'





      def __init__(       self      ,						lowercase = 512      ,						lowercase = 2      ,						lowercase = 1      ,						lowercase = 0      ,						lowercase = 2      ,						lowercase = 30_522      ,						lowercase = 768      ,						lowercase = 12      ,						lowercase = 12      ,						lowercase = 3_072      ,						lowercase = "gelu"      ,						lowercase = 0.1      ,						lowercase = 0.1      ,						lowercase = 512      ,						lowercase = 2      ,						lowercase = 0.02      ,						lowercase = 1e-12      ,						lowercase = False      ,						**lowercase      ,						)		->     Optional[int]:
            super().__init__(pad_token_id=lowercase      ,						**lowercase )

            lowerCAmelCase  						=       attention_window
            lowerCAmelCase  						=       sep_token_id
            lowerCAmelCase  						=       bos_token_id
            lowerCAmelCase  						=       eos_token_id
            lowerCAmelCase  						=       vocab_size
            lowerCAmelCase  						=       hidden_size
            lowerCAmelCase  						=       num_hidden_layers
            lowerCAmelCase  						=       num_attention_heads
            lowerCAmelCase  						=       hidden_act
            lowerCAmelCase  						=       intermediate_size
            lowerCAmelCase  						=       hidden_dropout_prob
            lowerCAmelCase  						=       attention_probs_dropout_prob
            lowerCAmelCase  						=       max_position_embeddings
            lowerCAmelCase  						=       type_vocab_size
            lowerCAmelCase  						=       initializer_range
            lowerCAmelCase  						=       layer_norm_eps
            lowerCAmelCase  						=       onnx_export







class 		lowercase					(					_UpperCAmelCase					):





      def __init__(       self      ,						lowercase      ,						lowercase = "default"      ,						lowercase = None )		->     Tuple:
            super().__init__(lowercase      ,						lowercase      ,						lowercase )
            lowerCAmelCase  						=       True





      @property
      def     _snake_case			(       self )		->     Mapping[str, Mapping[int, str]]:
            if self.task == "multiple-choice":
                  lowerCAmelCase  						=       {0: """batch""", 1: """choice""", 2: """sequence"""}
            else:
                  lowerCAmelCase  						=       {0: """batch""", 1: """sequence"""}
            return OrderedDict(
                [
                    ("""input_ids""", dynamic_axis),
                    ("""attention_mask""", dynamic_axis),
                    ("""global_attention_mask""", dynamic_axis),
                ] )





      @property
      def     _snake_case			(       self )		->     Mapping[str, Mapping[int, str]]:
            lowerCAmelCase  						=       super().outputs
            if self.task == "default":
                  lowerCAmelCase  						=       {0: """batch"""}
            return outputs





      @property
      def     _snake_case			(       self )		->     float:
            return 1e-4





      @property
      def     _snake_case			(       self )		->     int:
            # needs to be >= 14 to support tril operator
            return max(super().default_onnx_opset      ,						14 )





      def     _snake_case			(       self      ,						lowercase      ,						lowercase = -1      ,						lowercase = -1      ,						lowercase = False      ,						lowercase = None      ,						)		->     Mapping[str, Any]:
            lowerCAmelCase  						=       super().generate_dummy_inputs(
                preprocessor=lowercase      ,						batch_size=lowercase      ,						seq_length=lowercase      ,						is_pair=lowercase      ,						framework=lowercase )
            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
            lowerCAmelCase  						=       torch.zeros_like(inputs["""input_ids"""] )
            # make every second token global
            lowerCAmelCase  						=       1

            return inputs






